org.el 897 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637
  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-2018 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: https://orgmode.org
  9. ;; Version: 9.1.13
  10. ;;
  11. ;; This file is part of GNU Emacs.
  12. ;;
  13. ;; GNU Emacs is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;; GNU Emacs is distributed in the hope that it will be useful,
  18. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ;; GNU General Public License for more details.
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  23. ;;
  24. ;;; Commentary:
  25. ;;
  26. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  27. ;; project planning with a fast and effective plain-text system.
  28. ;;
  29. ;; Org mode develops organizational tasks around NOTES files that
  30. ;; contain information about projects as plain text. Org mode is
  31. ;; implemented on top of outline-mode, which makes it possible to keep
  32. ;; the content of large files well structured. Visibility cycling and
  33. ;; structure editing help to work with the tree. Tables are easily
  34. ;; created with a built-in table editor. Org mode supports ToDo
  35. ;; items, deadlines, time stamps, and scheduling. It dynamically
  36. ;; compiles entries into an agenda that utilizes and smoothly
  37. ;; integrates much of the Emacs calendar and diary. Plain text
  38. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  39. ;; entries, and any files related to the projects. For printing and
  40. ;; sharing of notes, an Org file can be exported as a structured ASCII
  41. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  42. ;; file. It can also serve as a publishing tool for a set of linked
  43. ;; webpages.
  44. ;;
  45. ;; Installation and Activation
  46. ;; ---------------------------
  47. ;; See the corresponding sections in the manual at
  48. ;;
  49. ;; https://orgmode.org/org.html#Installation
  50. ;;
  51. ;; Documentation
  52. ;; -------------
  53. ;; The documentation of Org mode can be found in the TeXInfo file. The
  54. ;; distribution also contains a PDF version of it. At the homepage of
  55. ;; Org mode, you can read the same text online as HTML. There is also an
  56. ;; excellent reference card made by Philip Rooke. This card can be found
  57. ;; in the doc/ directory.
  58. ;;
  59. ;; A list of recent changes can be found at
  60. ;; https://orgmode.org/Changes.html
  61. ;;
  62. ;;; Code:
  63. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  64. (defvar-local org-table-formula-constants-local nil
  65. "Local version of `org-table-formula-constants'.")
  66. (defvar org-inlinetask-min-level)
  67. ;;;; Require other packages
  68. (require 'cl-lib)
  69. (eval-when-compile (require 'gnus-sum))
  70. (require 'calendar)
  71. (require 'find-func)
  72. (require 'format-spec)
  73. (or (eq this-command 'eval-buffer)
  74. (condition-case nil
  75. (load (concat (file-name-directory load-file-name)
  76. "org-loaddefs.el")
  77. nil t t t)
  78. (error
  79. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  80. (sit-for 3)
  81. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  82. (sit-for 3))))
  83. (eval-and-compile (require 'org-macs))
  84. (require 'org-compat)
  85. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  86. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  87. (defvar org-outline-regexp "\\*+ "
  88. "Regexp to match Org headlines.")
  89. (defvar org-outline-regexp-bol "^\\*+ "
  90. "Regexp to match Org headlines.
  91. This is similar to `org-outline-regexp' but additionally makes
  92. sure that we are at the beginning of the line.")
  93. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  94. "Matches a headline, putting stars and text into groups.
  95. Stars are put in group 1 and the trimmed body in group 2.")
  96. (declare-function calendar-check-holidays "holidays" (date))
  97. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  98. (declare-function cdlatex-math-symbol "ext:cdlatex")
  99. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  100. (declare-function org-add-archive-files "org-archive" (files))
  101. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  102. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  103. (declare-function org-agenda-redo "org-agenda" (&optional all))
  104. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  105. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  106. (declare-function org-archive-subtree-default "org-archive" ())
  107. (declare-function org-archive-to-archive-sibling "org-archive" ())
  108. (declare-function org-attach "org-attach" ())
  109. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  110. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  111. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  112. (declare-function org-clock-cancel "org-clock" ())
  113. (declare-function org-clock-display "org-clock" (&optional arg))
  114. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  115. (declare-function org-clock-goto "org-clock" (&optional select))
  116. (declare-function org-clock-in "org-clock" (&optional select start-time))
  117. (declare-function org-clock-in-last "org-clock" (&optional arg))
  118. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  119. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  120. (declare-function org-clock-report "org-clock" (&optional arg))
  121. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  122. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  123. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  124. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  125. (declare-function org-clock-update-time-maybe "org-clock" ())
  126. (declare-function org-clocking-buffer "org-clock" ())
  127. (declare-function org-clocktable-shift "org-clock" (dir n))
  128. (declare-function org-columns-insert-dblock "org-colview" ())
  129. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  130. (declare-function org-element-at-point "org-element" ())
  131. (declare-function org-element-cache-refresh "org-element" (pos))
  132. (declare-function org-element-cache-reset "org-element" (&optional all))
  133. (declare-function org-element-contents "org-element" (element))
  134. (declare-function org-element-context "org-element" (&optional element))
  135. (declare-function org-element-copy "org-element" (datum))
  136. (declare-function org-element-create "org-element" (type &optional props &rest children))
  137. (declare-function org-element-interpret-data "org-element" (data))
  138. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  139. (declare-function org-element-link-parser "org-element" ())
  140. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  141. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  142. (declare-function org-element-property "org-element" (property element))
  143. (declare-function org-element-put-property "org-element" (element property value))
  144. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  145. (declare-function org-element-timestamp-parser "org-element" ())
  146. (declare-function org-element-type "org-element" (element))
  147. (declare-function org-element-update-syntax "org-element" ())
  148. (declare-function org-export-dispatch "ox" (&optional arg))
  149. (declare-function org-export-get-backend "ox" (name))
  150. (declare-function org-export-get-backend "ox" (name))
  151. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  152. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  153. (declare-function org-feed-goto-inbox "org-feed" (feed))
  154. (declare-function org-feed-update-all "org-feed" ())
  155. (declare-function org-goto "org-goto" (&optional alternative-interface))
  156. (declare-function org-goto "org-goto" (&optional alternative-interface))
  157. (declare-function org-id-find-id-file "org-id" (id))
  158. (declare-function org-id-get-create "org-id" (&optional force))
  159. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  160. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  161. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  162. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  163. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  164. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  165. (declare-function org-table--shrunk-field "org-table" ()) ;; For `org-table-with-shrunk-field'.
  166. (declare-function org-table-align "org-table" ())
  167. (declare-function org-table-begin "org-table" (&optional table-type))
  168. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  169. (declare-function org-table-blank-field "org-table" ())
  170. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  171. (declare-function org-table-copy-down "org-table" (N))
  172. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  173. (declare-function org-table-create-or-convert-from-region "org-table" (arg))
  174. (declare-function org-table-create-with-table.el "org-table" ())
  175. (declare-function org-table-cut-region "org-table" (beg end))
  176. (declare-function org-table-edit-field "org-table" (arg))
  177. (declare-function org-table-end "org-table" (&optional table-type))
  178. (declare-function org-table-end-of-field "org-table" (&optional n))
  179. (declare-function org-table-eval-formula "org-table" (&optional arg equation suppress-align suppress-const suppress-store suppress-analysis))
  180. (declare-function org-table-field-info "org-table" (arg))
  181. (declare-function org-table-insert-row "org-table" (&optional arg))
  182. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  183. (declare-function org-table-maybe-eval-formula "org-table" ())
  184. (declare-function org-table-maybe-recalculate-line "org-table" ())
  185. (declare-function org-table-next-row "org-table" ())
  186. (declare-function org-table-paste-rectangle "org-table" ())
  187. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  188. (declare-function org-table-rotate-recalc-marks "org-table" (&optional newchar))
  189. (declare-function org-table-shrink "org-table" (&optional begin end))
  190. (declare-function org-table-sort-lines "org-table" (&optional with-case sorting-type getkey-func compare-func interactive?))
  191. (declare-function org-table-sum "org-table" (&optional beg end nlast))
  192. (declare-function org-table-toggle-column-width "org-table" (&optional arg))
  193. (declare-function org-table-toggle-coordinate-overlays "org-table" ())
  194. (declare-function org-table-toggle-formula-debugger "org-table" ())
  195. (declare-function org-table-wrap-region "org-table" (arg))
  196. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  197. (declare-function org-timer "org-timer" (&optional restart no-insert))
  198. (declare-function org-timer-item "org-timer" (&optional arg))
  199. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  200. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  201. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  202. (declare-function org-timer-start "org-timer" (&optional offset))
  203. (declare-function org-timer-stop "org-timer" ())
  204. (declare-function org-timer-stop "org-timer" ())
  205. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  206. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  207. (declare-function orgtbl-mode "org-table" (&optional arg))
  208. (defvar ffap-url-regexp)
  209. (defvar org-element-paragraph-separate)
  210. (defvar org-indent-indentation-per-level)
  211. ;; load languages based on value of `org-babel-load-languages'
  212. (defvar org-babel-load-languages)
  213. ;;;###autoload
  214. (defun org-babel-do-load-languages (sym value)
  215. "Load the languages defined in `org-babel-load-languages'."
  216. (set-default sym value)
  217. (dolist (pair org-babel-load-languages)
  218. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  219. (if active
  220. (require (intern (concat "ob-" lang)))
  221. (fmakunbound
  222. (intern (concat "org-babel-execute:" lang)))
  223. (fmakunbound
  224. (intern (concat "org-babel-expand-body:" lang)))))))
  225. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  226. ;;;###autoload
  227. (defun org-babel-load-file (file &optional compile)
  228. "Load Emacs Lisp source code blocks in the Org FILE.
  229. This function exports the source code using `org-babel-tangle'
  230. and then loads the resulting file using `load-file'. With prefix
  231. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  232. file to byte-code before it is loaded."
  233. (interactive "fFile to load: \nP")
  234. (let* ((age (lambda (file)
  235. (float-time
  236. (time-subtract (current-time)
  237. (nth 5 (or (file-attributes (file-truename file))
  238. (file-attributes file)))))))
  239. (base-name (file-name-sans-extension file))
  240. (exported-file (concat base-name ".el")))
  241. ;; tangle if the Org file is newer than the elisp file
  242. (unless (and (file-exists-p exported-file)
  243. (> (funcall age file) (funcall age exported-file)))
  244. ;; Tangle-file traversal returns reversed list of tangled files
  245. ;; and we want to evaluate the first target.
  246. (setq exported-file
  247. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  248. (message "%s %s"
  249. (if compile
  250. (progn (byte-compile-file exported-file 'load)
  251. "Compiled and loaded")
  252. (progn (load-file exported-file) "Loaded"))
  253. exported-file)))
  254. (defcustom org-babel-load-languages '((emacs-lisp . t))
  255. "Languages which can be evaluated in Org buffers.
  256. \\<org-mode-map>
  257. This list can be used to load support for any of the languages
  258. below. Each language will depend on a different set of system
  259. executables and/or Emacs modes.
  260. When a language is \"loaded\", code blocks in that language can
  261. be evaluated with `org-babel-execute-src-block', which is bound
  262. by default to \\[org-ctrl-c-ctrl-c].
  263. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  264. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  265. default, only Emacs Lisp is loaded, since it has no specific
  266. requirement."
  267. :group 'org-babel
  268. :set 'org-babel-do-load-languages
  269. :version "24.1"
  270. :type '(alist :tag "Babel Languages"
  271. :key-type
  272. (choice
  273. (const :tag "Awk" awk)
  274. (const :tag "C" C)
  275. (const :tag "R" R)
  276. (const :tag "Asymptote" asymptote)
  277. (const :tag "Calc" calc)
  278. (const :tag "Clojure" clojure)
  279. (const :tag "CSS" css)
  280. (const :tag "Ditaa" ditaa)
  281. (const :tag "Dot" dot)
  282. (const :tag "Ebnf2ps" ebnf2ps)
  283. (const :tag "Emacs Lisp" emacs-lisp)
  284. (const :tag "Forth" forth)
  285. (const :tag "Fortran" fortran)
  286. (const :tag "Gnuplot" gnuplot)
  287. (const :tag "Haskell" haskell)
  288. (const :tag "hledger" hledger)
  289. (const :tag "IO" io)
  290. (const :tag "J" J)
  291. (const :tag "Java" java)
  292. (const :tag "Javascript" js)
  293. (const :tag "LaTeX" latex)
  294. (const :tag "Ledger" ledger)
  295. (const :tag "Lilypond" lilypond)
  296. (const :tag "Lisp" lisp)
  297. (const :tag "Makefile" makefile)
  298. (const :tag "Maxima" maxima)
  299. (const :tag "Matlab" matlab)
  300. (const :tag "Mscgen" mscgen)
  301. (const :tag "Ocaml" ocaml)
  302. (const :tag "Octave" octave)
  303. (const :tag "Org" org)
  304. (const :tag "Perl" perl)
  305. (const :tag "Pico Lisp" picolisp)
  306. (const :tag "PlantUML" plantuml)
  307. (const :tag "Python" python)
  308. (const :tag "Ruby" ruby)
  309. (const :tag "Sass" sass)
  310. (const :tag "Scala" scala)
  311. (const :tag "Scheme" scheme)
  312. (const :tag "Screen" screen)
  313. (const :tag "Shell Script" shell)
  314. (const :tag "Shen" shen)
  315. (const :tag "Sql" sql)
  316. (const :tag "Sqlite" sqlite)
  317. (const :tag "Stan" stan)
  318. (const :tag "Vala" vala))
  319. :value-type (boolean :tag "Activate" :value t)))
  320. ;;;; Customization variables
  321. (defcustom org-clone-delete-id nil
  322. "Remove ID property of clones of a subtree.
  323. When non-nil, clones of a subtree don't inherit the ID property.
  324. Otherwise they inherit the ID property with a new unique
  325. identifier."
  326. :type 'boolean
  327. :version "24.1"
  328. :group 'org-id)
  329. ;;; Version
  330. (org-check-version)
  331. ;;;###autoload
  332. (defun org-version (&optional here full message)
  333. "Show the Org version.
  334. Interactively, or when MESSAGE is non-nil, show it in echo area.
  335. With prefix argument, or when HERE is non-nil, insert it at point.
  336. In non-interactive uses, a reduced version string is output unless
  337. FULL is given."
  338. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  339. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  340. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  341. (load-suffixes (list ".el"))
  342. (org-install-dir
  343. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  344. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  345. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  346. (let* ((load-suffixes save-load-suffixes)
  347. (release (org-release))
  348. (git-version (org-git-version))
  349. (version (format "Org mode version %s (%s @ %s)"
  350. release
  351. git-version
  352. (if org-install-dir
  353. (if (string= org-dir org-install-dir)
  354. org-install-dir
  355. (concat "mixed installation! "
  356. org-install-dir
  357. " and "
  358. org-dir))
  359. "org-loaddefs.el can not be found!")))
  360. (version1 (if full version release)))
  361. (when here (insert version1))
  362. (when message (message "%s" version1))
  363. version1)))
  364. (defconst org-version (org-version))
  365. ;;; Syntax Constants
  366. ;;;; Block
  367. (defconst org-block-regexp
  368. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  369. "Regular expression for hiding blocks.")
  370. (defconst org-dblock-start-re
  371. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  372. "Matches the start line of a dynamic block, with parameters.")
  373. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  374. "Matches the end of a dynamic block.")
  375. ;;;; Clock and Planning
  376. (defconst org-clock-string "CLOCK:"
  377. "String used as prefix for timestamps clocking work hours on an item.")
  378. (defvar org-closed-string "CLOSED:"
  379. "String used as the prefix for timestamps logging closing a TODO entry.")
  380. (defvar org-deadline-string "DEADLINE:"
  381. "String to mark deadline entries.
  382. \\<org-mode-map>
  383. A deadline is this string, followed by a time stamp. It must be
  384. a word, terminated by a colon. You can insert a schedule keyword
  385. and a timestamp with `\\[org-deadline]'.")
  386. (defvar org-scheduled-string "SCHEDULED:"
  387. "String to mark scheduled TODO entries.
  388. \\<org-mode-map>
  389. A schedule is this string, followed by a time stamp. It must be
  390. a word, terminated by a colon. You can insert a schedule keyword
  391. and a timestamp with `\\[org-schedule]'.")
  392. (defconst org-ds-keyword-length
  393. (+ 2
  394. (apply #'max
  395. (mapcar #'length
  396. (list org-deadline-string org-scheduled-string
  397. org-clock-string org-closed-string))))
  398. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  399. (defconst org-planning-line-re
  400. (concat "^[ \t]*"
  401. (regexp-opt
  402. (list org-closed-string org-deadline-string org-scheduled-string)
  403. t))
  404. "Matches a line with planning info.
  405. Matched keyword is in group 1.")
  406. (defconst org-clock-line-re
  407. (concat "^[ \t]*" org-clock-string)
  408. "Matches a line with clock info.")
  409. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  410. "Matches the DEADLINE keyword.")
  411. (defconst org-deadline-time-regexp
  412. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  413. "Matches the DEADLINE keyword together with a time stamp.")
  414. (defconst org-deadline-time-hour-regexp
  415. (concat "\\<" org-deadline-string
  416. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  417. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  418. (defconst org-deadline-line-regexp
  419. (concat "\\<\\(" org-deadline-string "\\).*")
  420. "Matches the DEADLINE keyword and the rest of the line.")
  421. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  422. "Matches the SCHEDULED keyword.")
  423. (defconst org-scheduled-time-regexp
  424. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  425. "Matches the SCHEDULED keyword together with a time stamp.")
  426. (defconst org-scheduled-time-hour-regexp
  427. (concat "\\<" org-scheduled-string
  428. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  429. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  430. (defconst org-closed-time-regexp
  431. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  432. "Matches the CLOSED keyword together with a time stamp.")
  433. (defconst org-keyword-time-regexp
  434. (concat "\\<"
  435. (regexp-opt
  436. (list org-scheduled-string org-deadline-string org-closed-string
  437. org-clock-string)
  438. t)
  439. " *[[<]\\([^]>]+\\)[]>]")
  440. "Matches any of the 4 keywords, together with the time stamp.")
  441. (defconst org-keyword-time-not-clock-regexp
  442. (concat
  443. "\\<"
  444. (regexp-opt
  445. (list org-scheduled-string org-deadline-string org-closed-string) t)
  446. " *[[<]\\([^]>]+\\)[]>]")
  447. "Matches any of the 3 keywords, together with the time stamp.")
  448. (defconst org-maybe-keyword-time-regexp
  449. (concat "\\(\\<"
  450. (regexp-opt
  451. (list org-scheduled-string org-deadline-string org-closed-string
  452. org-clock-string)
  453. t)
  454. "\\)?"
  455. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  456. "\\|"
  457. "<%%([^\r\n>]*>\\)")
  458. "Matches a timestamp, possibly preceded by a keyword.")
  459. (defconst org-all-time-keywords
  460. (mapcar (lambda (w) (substring w 0 -1))
  461. (list org-scheduled-string org-deadline-string
  462. org-clock-string org-closed-string))
  463. "List of time keywords.")
  464. ;;;; Drawer
  465. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  466. "Matches first or last line of a hidden block.
  467. Group 1 contains drawer's name or \"END\".")
  468. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  469. "Regular expression matching the first line of a property drawer.")
  470. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  471. "Regular expression matching the last line of a property drawer.")
  472. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  473. "Regular expression matching the first line of a clock drawer.")
  474. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  475. "Regular expression matching the last line of a clock drawer.")
  476. (defconst org-property-drawer-re
  477. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  478. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  479. "[ \t]*:END:[ \t]*$")
  480. "Matches an entire property drawer.")
  481. (defconst org-clock-drawer-re
  482. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  483. org-clock-drawer-end-re "\\)\n?")
  484. "Matches an entire clock drawer.")
  485. ;;;; Headline
  486. (defconst org-heading-keyword-regexp-format
  487. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  488. "Printf format for a regexp matching a headline with some keyword.
  489. This regexp will match the headline of any node which has the
  490. exact keyword that is put into the format. The keyword isn't in
  491. any group by default, but the stars and the body are.")
  492. (defconst org-heading-keyword-maybe-regexp-format
  493. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  494. "Printf format for a regexp matching a headline, possibly with some keyword.
  495. This regexp can match any headline with the specified keyword, or
  496. without a keyword. The keyword isn't in any group by default,
  497. but the stars and the body are.")
  498. (defconst org-archive-tag "ARCHIVE"
  499. "The tag that marks a subtree as archived.
  500. An archived subtree does not open during visibility cycling, and does
  501. not contribute to the agenda listings.")
  502. (defconst org-tag-re "[[:alnum:]_@#%]+"
  503. "Regexp matching a single tag.")
  504. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  505. "Regexp matching the tag group at the end of a line, with leading spaces.
  506. Tags are stored in match group 1. Match group 2 stores the tags
  507. without the enclosing colons.")
  508. (defconst org-tag-line-re
  509. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  510. "Regexp matching tags in a headline.
  511. Tags are stored in match group 1. Match group 2 stores the tags
  512. without the enclosing colons.")
  513. (eval-and-compile
  514. (defconst org-comment-string "COMMENT"
  515. "Entries starting with this keyword will never be exported.
  516. \\<org-mode-map>
  517. An entry can be toggled between COMMENT and normal with
  518. `\\[org-toggle-comment]'."))
  519. ;;;; LaTeX Environments and Fragments
  520. (defconst org-latex-regexps
  521. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  522. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  523. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  524. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  525. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  526. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  527. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  528. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  529. "Regular expressions for matching embedded LaTeX.")
  530. ;;;; Node Property
  531. (defconst org-effort-property "Effort"
  532. "The property that is being used to keep track of effort estimates.
  533. Effort estimates given in this property need to have the format H:MM.")
  534. ;;;; Table
  535. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  536. "Detect an org-type or table-type table.")
  537. (defconst org-table-line-regexp "^[ \t]*|"
  538. "Detect an org-type table line.")
  539. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  540. "Detect an org-type table line.")
  541. (defconst org-table-hline-regexp "^[ \t]*|-"
  542. "Detect an org-type table hline.")
  543. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  544. "Detect a table-type table hline.")
  545. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  546. "Detect the first line outside a table when searching from within it.
  547. This works for both table types.")
  548. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  549. "Detect a #+TBLFM line.")
  550. ;;;; Timestamp
  551. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  552. "Regular expression for fast time stamp matching.")
  553. (defconst org-ts-regexp-inactive
  554. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  555. "Regular expression for fast inactive time stamp matching.")
  556. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  557. "Regular expression for fast time stamp matching.")
  558. (defconst org-ts-regexp0
  559. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  560. "Regular expression matching time strings for analysis.
  561. This one does not require the space after the date, so it can be used
  562. on a string that terminates immediately after the date.")
  563. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  564. "Regular expression matching time strings for analysis.")
  565. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  566. "Regular expression matching time stamps, with groups.")
  567. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  568. "Regular expression matching time stamps (also [..]), with groups.")
  569. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  570. "Regular expression matching a time stamp range.")
  571. (defconst org-tr-regexp-both
  572. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  573. "Regular expression matching a time stamp range.")
  574. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  575. org-ts-regexp "\\)?")
  576. "Regular expression matching a time stamp or time stamp range.")
  577. (defconst org-tsr-regexp-both
  578. (concat org-ts-regexp-both "\\(--?-?"
  579. org-ts-regexp-both "\\)?")
  580. "Regular expression matching a time stamp or time stamp range.
  581. The time stamps may be either active or inactive.")
  582. (defconst org-repeat-re
  583. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  584. "Regular expression for specifying repeated events.
  585. After a match, group 1 contains the repeat expression.")
  586. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  587. "Formats for `format-time-string' which are used for time stamps.")
  588. ;;; The custom variables
  589. (defgroup org nil
  590. "Outline-based notes management and organizer."
  591. :tag "Org"
  592. :group 'outlines
  593. :group 'calendar)
  594. (defcustom org-mode-hook nil
  595. "Mode hook for Org mode, run after the mode was turned on."
  596. :group 'org
  597. :type 'hook)
  598. (defcustom org-load-hook nil
  599. "Hook that is run after org.el has been loaded."
  600. :group 'org
  601. :type 'hook)
  602. (defcustom org-log-buffer-setup-hook nil
  603. "Hook that is run after an Org log buffer is created."
  604. :group 'org
  605. :version "24.1"
  606. :type 'hook)
  607. (defvar org-modules) ; defined below
  608. (defvar org-modules-loaded nil
  609. "Have the modules been loaded already?")
  610. (defun org-load-modules-maybe (&optional force)
  611. "Load all extensions listed in `org-modules'."
  612. (when (or force (not org-modules-loaded))
  613. (dolist (ext org-modules)
  614. (condition-case nil (require ext)
  615. (error (message "Problems while trying to load feature `%s'" ext))))
  616. (setq org-modules-loaded t)))
  617. (defun org-set-modules (var value)
  618. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  619. (set var value)
  620. (when (featurep 'org)
  621. (org-load-modules-maybe 'force)
  622. (org-element-cache-reset 'all)))
  623. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail org-eww)
  624. "Modules that should always be loaded together with org.el.
  625. If a description starts with <C>, the file is not part of Emacs
  626. and loading it will require that you have downloaded and properly
  627. installed the Org mode distribution.
  628. You can also use this system to load external packages (i.e. neither Org
  629. core modules, nor modules from the CONTRIB directory). Just add symbols
  630. to the end of the list. If the package is called org-xyz.el, then you need
  631. to add the symbol `xyz', and the package must have a call to:
  632. (provide \\='org-xyz)
  633. For export specific modules, see also `org-export-backends'."
  634. :group 'org
  635. :set 'org-set-modules
  636. :version "26.1"
  637. :package-version '(Org . "9.2")
  638. :type
  639. '(set :greedy t
  640. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  641. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  642. (const :tag " crypt: Encryption of subtrees" org-crypt)
  643. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  644. (const :tag " docview: Links to doc-view buffers" org-docview)
  645. (const :tag " eww: Store link to url of eww" org-eww)
  646. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  647. (const :tag " habit: Track your consistency with habits" org-habit)
  648. (const :tag " id: Global IDs for identifying entries" org-id)
  649. (const :tag " info: Links to Info nodes" org-info)
  650. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  651. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  652. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  653. (const :tag " mouse: Additional mouse support" org-mouse)
  654. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  655. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  656. (const :tag " tempo: Fast completion for structures" org-tempo)
  657. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  658. (const :tag " eshell: Support for links to working directories in eshell" org-eshell)
  659. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  660. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  661. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  662. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  663. (const :tag "C collector: Collect properties into tables" org-collector)
  664. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  665. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  666. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  667. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  668. (const :tag "C eval: Include command output as text" org-eval)
  669. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  670. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  671. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  672. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  673. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  674. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  675. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  676. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  677. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  678. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  679. (const :tag "C notify: Notifications for Org-mode" org-notify)
  680. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  681. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  682. (const :tag "C registry: A registry for Org links" org-registry)
  683. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  684. (const :tag "C screenshot: Take and manage screenshots in Org-mode files" org-screenshot)
  685. (const :tag "C secretary: Team management with Org" org-secretary)
  686. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  687. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  688. (const :tag "C track: Keep up with Org mode development" org-track)
  689. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  690. (const :tag "C vm: Links to VM folders/messages" org-vm)
  691. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  692. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  693. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  694. (defvar org-export-registered-backends) ; From ox.el.
  695. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  696. (declare-function org-export-backend-name "ox" (backend) t)
  697. (defcustom org-export-backends '(ascii html icalendar latex odt)
  698. "List of export back-ends that should be always available.
  699. If a description starts with <C>, the file is not part of Emacs
  700. and loading it will require that you have downloaded and properly
  701. installed the Org mode distribution.
  702. Unlike to `org-modules', libraries in this list will not be
  703. loaded along with Org, but only once the export framework is
  704. needed.
  705. This variable needs to be set before org.el is loaded. If you
  706. need to make a change while Emacs is running, use the customize
  707. interface or run the following code, where VAL stands for the new
  708. value of the variable, after updating it:
  709. (progn
  710. (setq org-export-registered-backends
  711. (cl-remove-if-not
  712. (lambda (backend)
  713. (let ((name (org-export-backend-name backend)))
  714. (or (memq name val)
  715. (catch \\='parentp
  716. (dolist (b val)
  717. (and (org-export-derived-backend-p b name)
  718. (throw \\='parentp t)))))))
  719. org-export-registered-backends))
  720. (let ((new-list (mapcar #\\='org-export-backend-name
  721. org-export-registered-backends)))
  722. (dolist (backend val)
  723. (cond
  724. ((not (load (format \"ox-%s\" backend) t t))
  725. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  726. backend))
  727. ((not (memq backend new-list)) (push backend new-list))))
  728. (set-default \\='org-export-backends new-list)))
  729. Adding a back-end to this list will also pull the back-end it
  730. depends on, if any."
  731. :group 'org
  732. :group 'org-export
  733. :version "26.1"
  734. :package-version '(Org . "9.0")
  735. :initialize 'custom-initialize-set
  736. :set (lambda (var val)
  737. (if (not (featurep 'ox)) (set-default var val)
  738. ;; Any back-end not required anymore (not present in VAL and not
  739. ;; a parent of any back-end in the new value) is removed from the
  740. ;; list of registered back-ends.
  741. (setq org-export-registered-backends
  742. (cl-remove-if-not
  743. (lambda (backend)
  744. (let ((name (org-export-backend-name backend)))
  745. (or (memq name val)
  746. (catch 'parentp
  747. (dolist (b val)
  748. (and (org-export-derived-backend-p b name)
  749. (throw 'parentp t)))))))
  750. org-export-registered-backends))
  751. ;; Now build NEW-LIST of both new back-ends and required
  752. ;; parents.
  753. (let ((new-list (mapcar #'org-export-backend-name
  754. org-export-registered-backends)))
  755. (dolist (backend val)
  756. (cond
  757. ((not (load (format "ox-%s" backend) t t))
  758. (message "Problems while trying to load export back-end `%s'"
  759. backend))
  760. ((not (memq backend new-list)) (push backend new-list))))
  761. ;; Set VAR to that list with fixed dependencies.
  762. (set-default var new-list))))
  763. :type '(set :greedy t
  764. (const :tag " ascii Export buffer to ASCII format" ascii)
  765. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  766. (const :tag " html Export buffer to HTML format" html)
  767. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  768. (const :tag " latex Export buffer to LaTeX format" latex)
  769. (const :tag " man Export buffer to MAN format" man)
  770. (const :tag " md Export buffer to Markdown format" md)
  771. (const :tag " odt Export buffer to ODT format" odt)
  772. (const :tag " org Export buffer to Org format" org)
  773. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  774. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  775. (const :tag "C deck Export buffer to deck.js presentations" deck)
  776. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  777. (const :tag "C groff Export buffer to Groff format" groff)
  778. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  779. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  780. (const :tag "C s5 Export buffer to s5 presentations" s5)
  781. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  782. (eval-after-load 'ox
  783. '(dolist (backend org-export-backends)
  784. (condition-case nil (require (intern (format "ox-%s" backend)))
  785. (error (message "Problems while trying to load export back-end `%s'"
  786. backend)))))
  787. (defcustom org-support-shift-select nil
  788. "Non-nil means make shift-cursor commands select text when possible.
  789. \\<org-mode-map>\
  790. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  791. start selecting a region, or enlarge regions started in this way.
  792. In Org mode, in special contexts, these same keys are used for
  793. other purposes, important enough to compete with shift selection.
  794. Org tries to balance these needs by supporting `shift-select-mode'
  795. outside these special contexts, under control of this variable.
  796. The default of this variable is nil, to avoid confusing behavior. Shifted
  797. cursor keys will then execute Org commands in the following contexts:
  798. - on a headline, changing TODO state (left/right) and priority (up/down)
  799. - on a time stamp, changing the time
  800. - in a plain list item, changing the bullet type
  801. - in a property definition line, switching between allowed values
  802. - in the BEGIN line of a clock table (changing the time block).
  803. Outside these contexts, the commands will throw an error.
  804. When this variable is t and the cursor is not in a special
  805. context, Org mode will support shift-selection for making and
  806. enlarging regions. To make this more effective, the bullet
  807. cycling will no longer happen anywhere in an item line, but only
  808. if the cursor is exactly on the bullet.
  809. If you set this variable to the symbol `always', then the keys
  810. will not be special in headlines, property lines, and item lines,
  811. to make shift selection work there as well. If this is what you
  812. want, you can use the following alternative commands:
  813. `\\[org-todo]' and `\\[org-priority]' \
  814. to change TODO state and priority,
  815. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  816. can be used to switch TODO sets,
  817. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  818. and properties can be edited by hand or in column view.
  819. However, when the cursor is on a timestamp, shift-cursor commands
  820. will still edit the time stamp - this is just too good to give up."
  821. :group 'org
  822. :type '(choice
  823. (const :tag "Never" nil)
  824. (const :tag "When outside special context" t)
  825. (const :tag "Everywhere except timestamps" always)))
  826. (defcustom org-loop-over-headlines-in-active-region nil
  827. "Shall some commands act upon headlines in the active region?
  828. When set to t, some commands will be performed in all headlines
  829. within the active region.
  830. When set to `start-level', some commands will be performed in all
  831. headlines within the active region, provided that these headlines
  832. are of the same level than the first one.
  833. When set to a string, those commands will be performed on the
  834. matching headlines within the active region. Such string must be
  835. a tags/property/todo match as it is used in the agenda tags view.
  836. The list of commands is: `org-schedule', `org-deadline',
  837. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  838. `org-archive-to-archive-sibling'. The archiving commands skip
  839. already archived entries."
  840. :type '(choice (const :tag "Don't loop" nil)
  841. (const :tag "All headlines in active region" t)
  842. (const :tag "In active region, headlines at the same level than the first one" start-level)
  843. (string :tag "Tags/Property/Todo matcher"))
  844. :version "24.1"
  845. :group 'org-todo
  846. :group 'org-archive)
  847. (defcustom org-startup-folded t
  848. "Non-nil means entering Org mode will switch to OVERVIEW.
  849. This can also be configured on a per-file basis by adding one of
  850. the following lines anywhere in the buffer:
  851. #+STARTUP: fold (or `overview', this is equivalent)
  852. #+STARTUP: nofold (or `showall', this is equivalent)
  853. #+STARTUP: content
  854. #+STARTUP: showeverything
  855. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  856. to ignore this option when Org opens agenda files for the first
  857. time."
  858. :group 'org-startup
  859. :type '(choice
  860. (const :tag "nofold: show all" nil)
  861. (const :tag "fold: overview" t)
  862. (const :tag "content: all headlines" content)
  863. (const :tag "show everything, even drawers" showeverything)))
  864. (defcustom org-startup-truncated t
  865. "Non-nil means entering Org mode will set `truncate-lines'.
  866. This is useful since some lines containing links can be very long and
  867. uninteresting. Also tables look terrible when wrapped.
  868. The variable `org-startup-truncated' allows to configure
  869. truncation for Org mode different to the other modes that use the
  870. variable `truncate-lines' and as a shortcut instead of putting
  871. the variable `truncate-lines' into the `org-mode-hook'. If one
  872. wants to configure truncation for Org mode not statically but
  873. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  874. the variable `truncate-lines' has to be used because in such a
  875. case it is too late to set the variable `org-startup-truncated'."
  876. :group 'org-startup
  877. :type 'boolean)
  878. (defcustom org-startup-indented nil
  879. "Non-nil means turn on `org-indent-mode' on startup.
  880. This can also be configured on a per-file basis by adding one of
  881. the following lines anywhere in the buffer:
  882. #+STARTUP: indent
  883. #+STARTUP: noindent"
  884. :group 'org-structure
  885. :type '(choice
  886. (const :tag "Not" nil)
  887. (const :tag "Globally (slow on startup in large files)" t)))
  888. (defcustom org-use-sub-superscripts t
  889. "Non-nil means interpret \"_\" and \"^\" for display.
  890. If you want to control how Org exports those characters, see
  891. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  892. used to be an alias for `org-export-with-sub-superscripts' in
  893. Org <8.0, it is not anymore.
  894. When this option is turned on, you can use TeX-like syntax for
  895. sub- and superscripts within the buffer. Several characters after
  896. \"_\" or \"^\" will be considered as a single item - so grouping
  897. with {} is normally not needed. For example, the following things
  898. will be parsed as single sub- or superscripts:
  899. 10^24 or 10^tau several digits will be considered 1 item.
  900. 10^-12 or 10^-tau a leading sign with digits or a word
  901. x^2-y^3 will be read as x^2 - y^3, because items are
  902. terminated by almost any nonword/nondigit char.
  903. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  904. Still, ambiguity is possible. So when in doubt, use {} to enclose
  905. the sub/superscript. If you set this variable to the symbol `{}',
  906. the braces are *required* in order to trigger interpretations as
  907. sub/superscript. This can be helpful in documents that need \"_\"
  908. frequently in plain text."
  909. :group 'org-startup
  910. :version "24.4"
  911. :package-version '(Org . "8.0")
  912. :type '(choice
  913. (const :tag "Always interpret" t)
  914. (const :tag "Only with braces" {})
  915. (const :tag "Never interpret" nil)))
  916. (defcustom org-startup-with-beamer-mode nil
  917. "Non-nil means turn on `org-beamer-mode' on startup.
  918. This can also be configured on a per-file basis by adding one of
  919. the following lines anywhere in the buffer:
  920. #+STARTUP: beamer"
  921. :group 'org-startup
  922. :version "24.1"
  923. :type 'boolean)
  924. (defcustom org-startup-align-all-tables nil
  925. "Non-nil means align all tables when visiting a file.
  926. This can also be configured on a per-file basis by adding one of
  927. the following lines anywhere in the buffer:
  928. #+STARTUP: align
  929. #+STARTUP: noalign"
  930. :group 'org-startup
  931. :type 'boolean)
  932. (defcustom org-startup-shrink-all-tables nil
  933. "Non-nil means shrink all table columns with a width cookie.
  934. This can also be configured on a per-file basis by adding one of
  935. the following lines anywhere in the buffer:
  936. #+STARTUP: shrink"
  937. :group 'org-startup
  938. :type 'boolean
  939. :version "27.1"
  940. :package-version '(Org . "9.2")
  941. :safe #'booleanp)
  942. (defcustom org-startup-with-inline-images nil
  943. "Non-nil means show inline images when loading a new Org file.
  944. This can also be configured on a per-file basis by adding one of
  945. the following lines anywhere in the buffer:
  946. #+STARTUP: inlineimages
  947. #+STARTUP: noinlineimages"
  948. :group 'org-startup
  949. :version "24.1"
  950. :type 'boolean)
  951. (defcustom org-startup-with-latex-preview nil
  952. "Non-nil means preview LaTeX fragments when loading a new Org file.
  953. This can also be configured on a per-file basis by adding one of
  954. the following lines anywhere in the buffer:
  955. #+STARTUP: latexpreview
  956. #+STARTUP: nolatexpreview"
  957. :group 'org-startup
  958. :version "24.4"
  959. :package-version '(Org . "8.0")
  960. :type 'boolean)
  961. (defcustom org-insert-mode-line-in-empty-file nil
  962. "Non-nil means insert the first line setting Org mode in empty files.
  963. When the function `org-mode' is called interactively in an empty file, this
  964. normally means that the file name does not automatically trigger Org mode.
  965. To ensure that the file will always be in Org mode in the future, a
  966. line enforcing Org mode will be inserted into the buffer, if this option
  967. has been set."
  968. :group 'org-startup
  969. :type 'boolean)
  970. (defcustom org-replace-disputed-keys nil
  971. "Non-nil means use alternative key bindings for some keys.
  972. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  973. These keys are also used by other packages like Shift Select mode,
  974. CUA mode or Windmove. If you want to use Org mode together with
  975. one of these other modes, or more generally if you would like to
  976. move some Org mode commands to other keys, set this variable and
  977. configure the keys with the variable `org-disputed-keys'.
  978. This option is only relevant at load-time of Org mode, and must be set
  979. *before* org.el is loaded. Changing it requires a restart of Emacs to
  980. become effective."
  981. :group 'org-startup
  982. :type 'boolean)
  983. (defcustom org-use-extra-keys nil
  984. "Non-nil means use extra key sequence definitions for certain commands.
  985. This happens automatically if `window-system' is nil. This
  986. variable lets you do the same manually. You must set it before
  987. loading Org."
  988. :group 'org-startup
  989. :type 'boolean)
  990. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  991. (defcustom org-disputed-keys
  992. '(([(shift up)] . [(meta p)])
  993. ([(shift down)] . [(meta n)])
  994. ([(shift left)] . [(meta -)])
  995. ([(shift right)] . [(meta +)])
  996. ([(control shift right)] . [(meta shift +)])
  997. ([(control shift left)] . [(meta shift -)]))
  998. "Keys for which Org mode and other modes compete.
  999. This is an alist, cars are the default keys, second element specifies
  1000. the alternative to use when `org-replace-disputed-keys' is t.
  1001. Keys can be specified in any syntax supported by `define-key'.
  1002. The value of this option takes effect only at Org mode startup,
  1003. therefore you'll have to restart Emacs to apply it after changing."
  1004. :group 'org-startup
  1005. :type 'alist)
  1006. (defun org-key (key)
  1007. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  1008. Or return the original if not disputed."
  1009. (when org-replace-disputed-keys
  1010. (let* ((nkey (key-description key))
  1011. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  1012. org-disputed-keys)))
  1013. (setq key (if x (cdr x) key))))
  1014. key)
  1015. (defun org-defkey (keymap key def)
  1016. "Define a key, possibly translated, as returned by `org-key'."
  1017. (define-key keymap (org-key key) def))
  1018. (defcustom org-ellipsis nil
  1019. "The ellipsis to use in the Org mode outline.
  1020. When nil, just use the standard three dots. When a non-empty string,
  1021. use that string instead.
  1022. The change affects only Org mode (which will then use its own display table).
  1023. Changing this requires executing `\\[org-mode]' in a buffer to become
  1024. effective."
  1025. :group 'org-startup
  1026. :type '(choice (const :tag "Default" nil)
  1027. (string :tag "String" :value "...#"))
  1028. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  1029. (defvar org-display-table nil
  1030. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  1031. (defgroup org-keywords nil
  1032. "Keywords in Org mode."
  1033. :tag "Org Keywords"
  1034. :group 'org)
  1035. (defcustom org-closed-keep-when-no-todo nil
  1036. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  1037. :group 'org-todo
  1038. :group 'org-keywords
  1039. :version "24.4"
  1040. :package-version '(Org . "8.0")
  1041. :type 'boolean)
  1042. (defgroup org-structure nil
  1043. "Options concerning the general structure of Org files."
  1044. :tag "Org Structure"
  1045. :group 'org)
  1046. (defgroup org-reveal-location nil
  1047. "Options about how to make context of a location visible."
  1048. :tag "Org Reveal Location"
  1049. :group 'org-structure)
  1050. (defcustom org-show-context-detail '((agenda . local)
  1051. (bookmark-jump . lineage)
  1052. (isearch . lineage)
  1053. (default . ancestors))
  1054. "Alist between context and visibility span when revealing a location.
  1055. \\<org-mode-map>Some actions may move point into invisible
  1056. locations. As a consequence, Org always expose a neighborhood
  1057. around point. How much is shown depends on the initial action,
  1058. or context. Valid contexts are
  1059. agenda when exposing an entry from the agenda
  1060. org-goto when using the command `org-goto' (`\\[org-goto]')
  1061. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1062. tags-tree when constructing a sparse tree based on tags matches
  1063. link-search when exposing search matches associated with a link
  1064. mark-goto when exposing the jump goal of a mark
  1065. bookmark-jump when exposing a bookmark location
  1066. isearch when exiting from an incremental search
  1067. default default for all contexts not set explicitly
  1068. Allowed visibility spans are
  1069. minimal show current headline; if point is not on headline,
  1070. also show entry
  1071. local show current headline, entry and next headline
  1072. ancestors show current headline and its direct ancestors; if
  1073. point is not on headline, also show entry
  1074. lineage show current headline, its direct ancestors and all
  1075. their children; if point is not on headline, also show
  1076. entry and first child
  1077. tree show current headline, its direct ancestors and all
  1078. their children; if point is not on headline, also show
  1079. entry and all children
  1080. canonical show current headline, its direct ancestors along with
  1081. their entries and children; if point is not located on
  1082. the headline, also show current entry and all children
  1083. As special cases, a nil or t value means show all contexts in
  1084. `minimal' or `canonical' view, respectively.
  1085. Some views can make displayed information very compact, but also
  1086. make it harder to edit the location of the match. In such
  1087. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1088. more context."
  1089. :group 'org-reveal-location
  1090. :version "26.1"
  1091. :package-version '(Org . "9.0")
  1092. :type '(choice
  1093. (const :tag "Canonical" t)
  1094. (const :tag "Minimal" nil)
  1095. (repeat :greedy t :tag "Individual contexts"
  1096. (cons
  1097. (choice :tag "Context"
  1098. (const agenda)
  1099. (const org-goto)
  1100. (const occur-tree)
  1101. (const tags-tree)
  1102. (const link-search)
  1103. (const mark-goto)
  1104. (const bookmark-jump)
  1105. (const isearch)
  1106. (const default))
  1107. (choice :tag "Detail level"
  1108. (const minimal)
  1109. (const local)
  1110. (const ancestors)
  1111. (const lineage)
  1112. (const tree)
  1113. (const canonical))))))
  1114. (defcustom org-indirect-buffer-display 'other-window
  1115. "How should indirect tree buffers be displayed?
  1116. This applies to indirect buffers created with the commands
  1117. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1118. Valid values are:
  1119. current-window Display in the current window
  1120. other-window Just display in another window.
  1121. dedicated-frame Create one new frame, and re-use it each time.
  1122. new-frame Make a new frame each time. Note that in this case
  1123. previously-made indirect buffers are kept, and you need to
  1124. kill these buffers yourself."
  1125. :group 'org-structure
  1126. :group 'org-agenda-windows
  1127. :type '(choice
  1128. (const :tag "In current window" current-window)
  1129. (const :tag "In current frame, other window" other-window)
  1130. (const :tag "Each time a new frame" new-frame)
  1131. (const :tag "One dedicated frame" dedicated-frame)))
  1132. (defcustom org-use-speed-commands nil
  1133. "Non-nil means activate single letter commands at beginning of a headline.
  1134. This may also be a function to test for appropriate locations where speed
  1135. commands should be active.
  1136. For example, to activate speed commands when the point is on any
  1137. star at the beginning of the headline, you can do this:
  1138. (setq org-use-speed-commands
  1139. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1140. :group 'org-structure
  1141. :type '(choice
  1142. (const :tag "Never" nil)
  1143. (const :tag "At beginning of headline stars" t)
  1144. (function)))
  1145. (defcustom org-speed-commands-user nil
  1146. "Alist of additional speed commands.
  1147. This list will be checked before `org-speed-commands-default'
  1148. when the variable `org-use-speed-commands' is non-nil
  1149. and when the cursor is at the beginning of a headline.
  1150. The car of each entry is a string with a single letter, which must
  1151. be assigned to `self-insert-command' in the global map.
  1152. The cdr is either a command to be called interactively, a function
  1153. to be called, or a form to be evaluated.
  1154. An entry that is just a list with a single string will be interpreted
  1155. as a descriptive headline that will be added when listing the speed
  1156. commands in the Help buffer using the `?' speed command."
  1157. :group 'org-structure
  1158. :type '(repeat :value ("k" . ignore)
  1159. (choice :value ("k" . ignore)
  1160. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1161. (cons :tag "Letter and Command"
  1162. (string :tag "Command letter")
  1163. (choice
  1164. (function)
  1165. (sexp))))))
  1166. (defcustom org-bookmark-names-plist
  1167. '(:last-capture "org-capture-last-stored"
  1168. :last-refile "org-refile-last-stored"
  1169. :last-capture-marker "org-capture-last-stored-marker")
  1170. "Names for bookmarks automatically set by some Org commands.
  1171. This can provide strings as names for a number of bookmarks Org sets
  1172. automatically. The following keys are currently implemented:
  1173. :last-capture
  1174. :last-capture-marker
  1175. :last-refile
  1176. When a key does not show up in the property list, the corresponding bookmark
  1177. is not set."
  1178. :group 'org-structure
  1179. :type 'plist)
  1180. (defgroup org-cycle nil
  1181. "Options concerning visibility cycling in Org mode."
  1182. :tag "Org Cycle"
  1183. :group 'org-structure)
  1184. (defcustom org-cycle-skip-children-state-if-no-children t
  1185. "Non-nil means skip CHILDREN state in entries that don't have any."
  1186. :group 'org-cycle
  1187. :type 'boolean)
  1188. (defcustom org-cycle-max-level nil
  1189. "Maximum level which should still be subject to visibility cycling.
  1190. Levels higher than this will, for cycling, be treated as text, not a headline.
  1191. When `org-odd-levels-only' is set, a value of N in this variable actually
  1192. means 2N-1 stars as the limiting headline.
  1193. When nil, cycle all levels.
  1194. Note that the limiting level of cycling is also influenced by
  1195. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1196. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1197. than its value."
  1198. :group 'org-cycle
  1199. :type '(choice
  1200. (const :tag "No limit" nil)
  1201. (integer :tag "Maximum level")))
  1202. (defcustom org-hide-block-startup nil
  1203. "Non-nil means entering Org mode will fold all blocks.
  1204. This can also be set in on a per-file basis with
  1205. #+STARTUP: hideblocks
  1206. #+STARTUP: showblocks"
  1207. :group 'org-startup
  1208. :group 'org-cycle
  1209. :type 'boolean)
  1210. (defcustom org-cycle-global-at-bob nil
  1211. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1212. This makes it possible to do global cycling without having to use `S-TAB'
  1213. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1214. line of the buffer
  1215. must not be a headline -- it may be empty or some other text.
  1216. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1217. sure the cursor stays at the beginning of the buffer.
  1218. When this option is nil, don't do anything special at the beginning of
  1219. the buffer."
  1220. :group 'org-cycle
  1221. :type 'boolean)
  1222. (defcustom org-cycle-level-after-item/entry-creation t
  1223. "Non-nil means cycle entry level or item indentation in new empty entries.
  1224. When the cursor is at the end of an empty headline, i.e., with only stars
  1225. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1226. and then all possible ancestor states, before returning to the original state.
  1227. This makes data entry extremely fast: M-RET to create a new headline,
  1228. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1229. When the cursor is at the end of an empty plain list item, one TAB will
  1230. make it a subitem, two or more tabs will back up to make this an item
  1231. higher up in the item hierarchy."
  1232. :group 'org-cycle
  1233. :type 'boolean)
  1234. (defcustom org-cycle-emulate-tab t
  1235. "Where should `org-cycle' emulate TAB.
  1236. nil Never
  1237. white Only in completely white lines
  1238. whitestart Only at the beginning of lines, before the first non-white char
  1239. t Everywhere except in headlines
  1240. exc-hl-bol Everywhere except at the start of a headline
  1241. If TAB is used in a place where it does not emulate TAB, the current subtree
  1242. visibility is cycled."
  1243. :group 'org-cycle
  1244. :type '(choice (const :tag "Never" nil)
  1245. (const :tag "Only in completely white lines" white)
  1246. (const :tag "Before first char in a line" whitestart)
  1247. (const :tag "Everywhere except in headlines" t)
  1248. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1249. (defcustom org-cycle-separator-lines 2
  1250. "Number of empty lines needed to keep an empty line between collapsed trees.
  1251. If you leave an empty line between the end of a subtree and the following
  1252. headline, this empty line is hidden when the subtree is folded.
  1253. Org mode will leave (exactly) one empty line visible if the number of
  1254. empty lines is equal or larger to the number given in this variable.
  1255. So the default 2 means at least 2 empty lines after the end of a subtree
  1256. are needed to produce free space between a collapsed subtree and the
  1257. following headline.
  1258. If the number is negative, and the number of empty lines is at least -N,
  1259. all empty lines are shown.
  1260. Special case: when 0, never leave empty lines in collapsed view."
  1261. :group 'org-cycle
  1262. :type 'integer)
  1263. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1264. (defcustom org-pre-cycle-hook nil
  1265. "Hook that is run before visibility cycling is happening.
  1266. The function(s) in this hook must accept a single argument which indicates
  1267. the new state that will be set right after running this hook. The
  1268. argument is a symbol. Before a global state change, it can have the values
  1269. `overview', `content', or `all'. Before a local state change, it can have
  1270. the values `folded', `children', or `subtree'."
  1271. :group 'org-cycle
  1272. :type 'hook)
  1273. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1274. org-cycle-show-empty-lines
  1275. org-optimize-window-after-visibility-change)
  1276. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1277. The function(s) in this hook must accept a single argument which indicates
  1278. the new state that was set by the most recent `org-cycle' command. The
  1279. argument is a symbol. After a global state change, it can have the values
  1280. `overview', `contents', or `all'. After a local state change, it can have
  1281. the values `folded', `children', or `subtree'."
  1282. :group 'org-cycle
  1283. :type 'hook
  1284. :version "26.1"
  1285. :package-version '(Org . "8.3"))
  1286. (defgroup org-edit-structure nil
  1287. "Options concerning structure editing in Org mode."
  1288. :tag "Org Edit Structure"
  1289. :group 'org-structure)
  1290. (defcustom org-odd-levels-only nil
  1291. "Non-nil means skip even levels and only use odd levels for the outline.
  1292. This has the effect that two stars are being added/taken away in
  1293. promotion/demotion commands. It also influences how levels are
  1294. handled by the exporters.
  1295. Changing it requires restart of `font-lock-mode' to become effective
  1296. for fontification also in regions already fontified.
  1297. You may also set this on a per-file basis by adding one of the following
  1298. lines to the buffer:
  1299. #+STARTUP: odd
  1300. #+STARTUP: oddeven"
  1301. :group 'org-edit-structure
  1302. :group 'org-appearance
  1303. :type 'boolean)
  1304. (defcustom org-adapt-indentation t
  1305. "Non-nil means adapt indentation to outline node level.
  1306. When this variable is set, Org assumes that you write outlines by
  1307. indenting text in each node to align with the headline (after the
  1308. stars). The following issues are influenced by this variable:
  1309. - The indentation is increased by one space in a demotion
  1310. command, and decreased by one in a promotion command. However,
  1311. in the latter case, if shifting some line in the entry body
  1312. would alter document structure (e.g., insert a new headline),
  1313. indentation is not changed at all.
  1314. - Property drawers and planning information is inserted indented
  1315. when this variable is set. When nil, they will not be indented.
  1316. - TAB indents a line relative to current level. The lines below
  1317. a headline will be indented when this variable is set.
  1318. Note that this is all about true indentation, by adding and
  1319. removing space characters. See also \"org-indent.el\" which does
  1320. level-dependent indentation in a virtual way, i.e. at display
  1321. time in Emacs."
  1322. :group 'org-edit-structure
  1323. :type 'boolean
  1324. :safe #'booleanp)
  1325. (defcustom org-special-ctrl-a/e nil
  1326. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1327. When t, `C-a' will bring back the cursor to the beginning of the
  1328. headline text, i.e. after the stars and after a possible TODO
  1329. keyword. In an item, this will be the position after bullet and
  1330. check-box, if any. When the cursor is already at that position,
  1331. another `C-a' will bring it to the beginning of the line.
  1332. `C-e' will jump to the end of the headline, ignoring the presence
  1333. of tags in the headline. A second `C-e' will then jump to the
  1334. true end of the line, after any tags. This also means that, when
  1335. this variable is non-nil, `C-e' also will never jump beyond the
  1336. end of the heading of a folded section, i.e. not after the
  1337. ellipses.
  1338. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1339. normally, going to the true line boundary first. Only a directly
  1340. following, identical keypress will bring the cursor to the
  1341. special positions.
  1342. This may also be a cons cell where the behavior for `C-a' and
  1343. `C-e' is set separately."
  1344. :group 'org-edit-structure
  1345. :type '(choice
  1346. (const :tag "off" nil)
  1347. (const :tag "on: after stars/bullet and before tags first" t)
  1348. (const :tag "reversed: true line boundary first" reversed)
  1349. (cons :tag "Set C-a and C-e separately"
  1350. (choice :tag "Special C-a"
  1351. (const :tag "off" nil)
  1352. (const :tag "on: after stars/bullet first" t)
  1353. (const :tag "reversed: before stars/bullet first" reversed))
  1354. (choice :tag "Special C-e"
  1355. (const :tag "off" nil)
  1356. (const :tag "on: before tags first" t)
  1357. (const :tag "reversed: after tags first" reversed)))))
  1358. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1359. (defcustom org-special-ctrl-k nil
  1360. "Non-nil means `C-k' will behave specially in headlines.
  1361. When nil, `C-k' will call the default `kill-line' command.
  1362. When t, the following will happen while the cursor is in the headline:
  1363. - When the cursor is at the beginning of a headline, kill the entire
  1364. line and possible the folded subtree below the line.
  1365. - When in the middle of the headline text, kill the headline up to the tags.
  1366. - When after the headline text, kill the tags."
  1367. :group 'org-edit-structure
  1368. :type 'boolean)
  1369. (defcustom org-ctrl-k-protect-subtree nil
  1370. "Non-nil means, do not delete a hidden subtree with C-k.
  1371. When set to the symbol `error', simply throw an error when C-k is
  1372. used to kill (part-of) a headline that has hidden text behind it.
  1373. Any other non-nil value will result in a query to the user, if it is
  1374. OK to kill that hidden subtree. When nil, kill without remorse."
  1375. :group 'org-edit-structure
  1376. :version "24.1"
  1377. :type '(choice
  1378. (const :tag "Do not protect hidden subtrees" nil)
  1379. (const :tag "Protect hidden subtrees with a security query" t)
  1380. (const :tag "Never kill a hidden subtree with C-k" error)))
  1381. (defcustom org-special-ctrl-o t
  1382. "Non-nil means, make `C-o' insert a row in tables."
  1383. :group 'org-edit-structure
  1384. :type 'boolean)
  1385. (defcustom org-catch-invisible-edits nil
  1386. "Check if in invisible region before inserting or deleting a character.
  1387. Valid values are:
  1388. nil Do not check, so just do invisible edits.
  1389. error Throw an error and do nothing.
  1390. show Make point visible, and do the requested edit.
  1391. show-and-error Make point visible, then throw an error and abort the edit.
  1392. smart Make point visible, and do insertion/deletion if it is
  1393. adjacent to visible text and the change feels predictable.
  1394. Never delete a previously invisible character or add in the
  1395. middle or right after an invisible region. Basically, this
  1396. allows insertion and backward-delete right before ellipses.
  1397. FIXME: maybe in this case we should not even show?"
  1398. :group 'org-edit-structure
  1399. :version "24.1"
  1400. :type '(choice
  1401. (const :tag "Do not check" nil)
  1402. (const :tag "Throw error when trying to edit" error)
  1403. (const :tag "Unhide, but do not do the edit" show-and-error)
  1404. (const :tag "Show invisible part and do the edit" show)
  1405. (const :tag "Be smart and do the right thing" smart)))
  1406. (defcustom org-yank-folded-subtrees t
  1407. "Non-nil means when yanking subtrees, fold them.
  1408. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1409. it starts with a heading and all other headings in it are either children
  1410. or siblings, then fold all the subtrees. However, do this only if no
  1411. text after the yank would be swallowed into a folded tree by this action."
  1412. :group 'org-edit-structure
  1413. :type 'boolean)
  1414. (defcustom org-yank-adjusted-subtrees nil
  1415. "Non-nil means when yanking subtrees, adjust the level.
  1416. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1417. this function for details."
  1418. :group 'org-edit-structure
  1419. :type 'boolean)
  1420. (defcustom org-M-RET-may-split-line '((default . t))
  1421. "Non-nil means M-RET will split the line at the cursor position.
  1422. When nil, it will go to the end of the line before making a
  1423. new line.
  1424. You may also set this option in a different way for different
  1425. contexts. Valid contexts are:
  1426. headline when creating a new headline
  1427. item when creating a new item
  1428. table in a table field
  1429. default the value to be used for all contexts not explicitly
  1430. customized"
  1431. :group 'org-structure
  1432. :group 'org-table
  1433. :type '(choice
  1434. (const :tag "Always" t)
  1435. (const :tag "Never" nil)
  1436. (repeat :greedy t :tag "Individual contexts"
  1437. (cons
  1438. (choice :tag "Context"
  1439. (const headline)
  1440. (const item)
  1441. (const table)
  1442. (const default))
  1443. (boolean)))))
  1444. (defcustom org-insert-heading-respect-content nil
  1445. "Non-nil means insert new headings after the current subtree.
  1446. \\<org-mode-map>
  1447. When nil, the new heading is created directly after the current line.
  1448. The commands `\\[org-insert-heading-respect-content]' and \
  1449. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1450. for the duration of the command."
  1451. :group 'org-structure
  1452. :type 'boolean)
  1453. (defcustom org-blank-before-new-entry '((heading . auto)
  1454. (plain-list-item . auto))
  1455. "Should `org-insert-heading' leave a blank line before new heading/item?
  1456. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1457. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1458. which case Org will look at the surrounding headings/items and try to
  1459. make an intelligent decision whether to insert a blank line or not."
  1460. :group 'org-edit-structure
  1461. :type '(list
  1462. (cons (const heading)
  1463. (choice (const :tag "Never" nil)
  1464. (const :tag "Always" t)
  1465. (const :tag "Auto" auto)))
  1466. (cons (const plain-list-item)
  1467. (choice (const :tag "Never" nil)
  1468. (const :tag "Always" t)
  1469. (const :tag "Auto" auto)))))
  1470. (defcustom org-insert-heading-hook nil
  1471. "Hook being run after inserting a new heading."
  1472. :group 'org-edit-structure
  1473. :type 'hook)
  1474. (defcustom org-enable-fixed-width-editor t
  1475. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1476. This currently only means they are never auto-wrapped.
  1477. When nil, such lines will be treated like ordinary lines."
  1478. :group 'org-edit-structure
  1479. :type 'boolean)
  1480. (defgroup org-sparse-trees nil
  1481. "Options concerning sparse trees in Org mode."
  1482. :tag "Org Sparse Trees"
  1483. :group 'org-structure)
  1484. (defcustom org-highlight-sparse-tree-matches t
  1485. "Non-nil means highlight all matches that define a sparse tree.
  1486. The highlights will automatically disappear the next time the buffer is
  1487. changed by an edit command."
  1488. :group 'org-sparse-trees
  1489. :type 'boolean)
  1490. (defcustom org-remove-highlights-with-change t
  1491. "Non-nil means any change to the buffer will remove temporary highlights.
  1492. \\<org-mode-map>\
  1493. Such highlights are created by `org-occur' and `org-clock-display'.
  1494. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1495. to get rid of the highlights.
  1496. The highlights created by `org-toggle-latex-fragment' always need
  1497. `\\[org-toggle-latex-fragment]' to be removed."
  1498. :group 'org-sparse-trees
  1499. :group 'org-time
  1500. :type 'boolean)
  1501. (defcustom org-occur-case-fold-search t
  1502. "Non-nil means `org-occur' should be case-insensitive.
  1503. If set to `smart' the search will be case-insensitive only if it
  1504. doesn't specify any upper case character."
  1505. :group 'org-sparse-trees
  1506. :version "26.1"
  1507. :type '(choice
  1508. (const :tag "Case-sensitive" nil)
  1509. (const :tag "Case-insensitive" t)
  1510. (const :tag "Case-insensitive for lower case searches only" smart)))
  1511. (defcustom org-occur-hook '(org-first-headline-recenter)
  1512. "Hook that is run after `org-occur' has constructed a sparse tree.
  1513. This can be used to recenter the window to show as much of the structure
  1514. as possible."
  1515. :group 'org-sparse-trees
  1516. :type 'hook)
  1517. (defgroup org-table nil
  1518. "Options concerning tables in Org mode."
  1519. :tag "Org Table"
  1520. :group 'org)
  1521. (defcustom org-self-insert-cluster-for-undo nil
  1522. "Non-nil means cluster self-insert commands for undo when possible.
  1523. If this is set, then, like in the Emacs command loop, 20 consecutive
  1524. characters will be undone together.
  1525. This is configurable, because there is some impact on typing performance."
  1526. :group 'org-table
  1527. :type 'boolean)
  1528. (defcustom org-table-tab-recognizes-table.el t
  1529. "Non-nil means TAB will automatically notice a table.el table.
  1530. When it sees such a table, it moves point into it and - if necessary -
  1531. calls `table-recognize-table'."
  1532. :group 'org-table-editing
  1533. :type 'boolean)
  1534. (defgroup org-link nil
  1535. "Options concerning links in Org mode."
  1536. :tag "Org Link"
  1537. :group 'org)
  1538. (defvar-local org-link-abbrev-alist-local nil
  1539. "Buffer-local version of `org-link-abbrev-alist', which see.
  1540. The value of this is taken from the #+LINK lines.")
  1541. (defcustom org-link-parameters
  1542. '(("doi" :follow org--open-doi-link)
  1543. ("elisp" :follow org--open-elisp-link)
  1544. ("file" :complete org-file-complete-link)
  1545. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1546. ("help" :follow org--open-help-link)
  1547. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1548. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1549. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1550. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1551. ("shell" :follow org--open-shell-link))
  1552. "An alist of properties that defines all the links in Org mode.
  1553. The key in each association is a string of the link type.
  1554. Subsequent optional elements make up a p-list of link properties.
  1555. :follow - A function that takes the link path as an argument.
  1556. :export - A function that takes the link path, description and
  1557. export-backend as arguments.
  1558. :store - A function responsible for storing the link. See the
  1559. function `org-store-link-functions'.
  1560. :complete - A function that inserts a link with completion. The
  1561. function takes one optional prefix arg.
  1562. :face - A face for the link, or a function that returns a face.
  1563. The function takes one argument which is the link path. The
  1564. default face is `org-link'.
  1565. :mouse-face - The mouse-face. The default is `highlight'.
  1566. :display - `full' will not fold the link in descriptive
  1567. display. Default is `org-link'.
  1568. :help-echo - A string or function that takes (window object position)
  1569. as arguments and returns a string.
  1570. :keymap - A keymap that is active on the link. The default is
  1571. `org-mouse-map'.
  1572. :htmlize-link - A function for the htmlize-link. Defaults
  1573. to (list :uri \"type:path\")
  1574. :activate-func - A function to run at the end of font-lock
  1575. activation. The function must accept (link-start link-end path bracketp)
  1576. as arguments."
  1577. :group 'org-link
  1578. :type '(alist :tag "Link display parameters"
  1579. :value-type plist)
  1580. :version "26.1"
  1581. :package-version '(Org . "9.1"))
  1582. (defun org-link-get-parameter (type key)
  1583. "Get TYPE link property for KEY.
  1584. TYPE is a string and KEY is a plist keyword."
  1585. (plist-get
  1586. (cdr (assoc type org-link-parameters))
  1587. key))
  1588. (defun org-link-set-parameters (type &rest parameters)
  1589. "Set link TYPE properties to PARAMETERS.
  1590. PARAMETERS should be :key val pairs."
  1591. (let ((data (assoc type org-link-parameters)))
  1592. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1593. (push (cons type parameters) org-link-parameters)
  1594. (org-make-link-regexps)
  1595. (org-element-update-syntax))))
  1596. (defun org-link-types ()
  1597. "Return a list of known link types."
  1598. (mapcar #'car org-link-parameters))
  1599. (defcustom org-link-abbrev-alist nil
  1600. "Alist of link abbreviations.
  1601. The car of each element is a string, to be replaced at the start of a link.
  1602. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1603. links in Org buffers can have an optional tag after a double colon, e.g.,
  1604. [[linkkey:tag][description]]
  1605. The `linkkey' must be a single word, starting with a letter, followed
  1606. by letters, numbers, `-' or `_'.
  1607. If REPLACE is a string, the tag will simply be appended to create the link.
  1608. If the string contains \"%s\", the tag will be inserted there. If the string
  1609. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1610. at that point (see the function `url-hexify-string'). If the string contains
  1611. the specifier \"%(my-function)\", then the custom function `my-function' will
  1612. be invoked: this function takes the tag as its only argument and must return
  1613. a string.
  1614. REPLACE may also be a function that will be called with the tag as the
  1615. only argument to create the link, which should be returned as a string.
  1616. See the manual for examples."
  1617. :group 'org-link
  1618. :type '(repeat
  1619. (cons
  1620. (string :tag "Protocol")
  1621. (choice
  1622. (string :tag "Format")
  1623. (function)))))
  1624. (defcustom org-descriptive-links t
  1625. "Non-nil means Org will display descriptive links.
  1626. E.g. [[https://orgmode.org][Org website]] will be displayed as
  1627. \"Org Website\", hiding the link itself and just displaying its
  1628. description. When set to nil, Org will display the full links
  1629. literally.
  1630. You can interactively set the value of this variable by calling
  1631. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1632. :group 'org-link
  1633. :type 'boolean)
  1634. (defcustom org-link-file-path-type 'adaptive
  1635. "How the path name in file links should be stored.
  1636. Valid values are:
  1637. relative Relative to the current directory, i.e. the directory of the file
  1638. into which the link is being inserted.
  1639. absolute Absolute path, if possible with ~ for home directory.
  1640. noabbrev Absolute path, no abbreviation of home directory.
  1641. adaptive Use relative path for files in the current directory and sub-
  1642. directories of it. For other files, use an absolute path."
  1643. :group 'org-link
  1644. :type '(choice
  1645. (const relative)
  1646. (const absolute)
  1647. (const noabbrev)
  1648. (const adaptive)))
  1649. (defvaralias 'org-activate-links 'org-highlight-links)
  1650. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1651. "Types of links that should be highlighted in Org files.
  1652. This is a list of symbols, each one of them leading to the
  1653. highlighting of a certain link type.
  1654. You can still open links that are not highlighted.
  1655. In principle, it does not hurt to turn on highlighting for all
  1656. link types. There may be a small gain when turning off unused
  1657. link types. The types are:
  1658. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1659. angle Links in angular brackets that may contain whitespace like
  1660. <bbdb:Carsten Dominik>.
  1661. plain Plain links in normal text, no whitespace, like http://google.com.
  1662. radio Text that is matched by a radio target, see manual for details.
  1663. tag Tag settings in a headline (link to tag search).
  1664. date Time stamps (link to calendar).
  1665. footnote Footnote labels.
  1666. If you set this variable during an Emacs session, use `org-mode-restart'
  1667. in the Org buffer so that the change takes effect."
  1668. :group 'org-link
  1669. :group 'org-appearance
  1670. :type '(set :greedy t
  1671. (const :tag "Double bracket links" bracket)
  1672. (const :tag "Angular bracket links" angle)
  1673. (const :tag "Plain text links" plain)
  1674. (const :tag "Radio target matches" radio)
  1675. (const :tag "Tags" tag)
  1676. (const :tag "Timestamps" date)
  1677. (const :tag "Footnotes" footnote)))
  1678. (defcustom org-make-link-description-function nil
  1679. "Function to use for generating link descriptions from links.
  1680. This function must take two parameters: the first one is the
  1681. link, the second one is the description generated by
  1682. `org-insert-link'. The function should return the description to
  1683. use."
  1684. :group 'org-link
  1685. :type '(choice (const nil) (function)))
  1686. (defgroup org-link-store nil
  1687. "Options concerning storing links in Org mode."
  1688. :tag "Org Store Link"
  1689. :group 'org-link)
  1690. (defcustom org-url-hexify-p t
  1691. "When non-nil, hexify URL when creating a link."
  1692. :type 'boolean
  1693. :version "24.3"
  1694. :group 'org-link-store)
  1695. (defcustom org-email-link-description-format "Email %c: %.30s"
  1696. "Format of the description part of a link to an email or usenet message.
  1697. The following %-escapes will be replaced by corresponding information:
  1698. %F full \"From\" field
  1699. %f name, taken from \"From\" field, address if no name
  1700. %T full \"To\" field
  1701. %t first name in \"To\" field, address if no name
  1702. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1703. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1704. %s subject
  1705. %d date
  1706. %m message-id.
  1707. You may use normal field width specification between the % and the letter.
  1708. This is for example useful to limit the length of the subject.
  1709. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1710. :group 'org-link-store
  1711. :type 'string)
  1712. (defcustom org-from-is-user-regexp
  1713. (let (r1 r2)
  1714. (when (and user-mail-address (not (string= user-mail-address "")))
  1715. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1716. (when (and user-full-name (not (string= user-full-name "")))
  1717. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1718. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1719. "Regexp matched against the \"From:\" header of an email or usenet message.
  1720. It should match if the message is from the user him/herself."
  1721. :group 'org-link-store
  1722. :type 'regexp)
  1723. (defcustom org-context-in-file-links t
  1724. "Non-nil means file links from `org-store-link' contain context.
  1725. \\<org-mode-map>
  1726. A search string will be added to the file name with :: as separator
  1727. and used to find the context when the link is activated by the command
  1728. `org-open-at-point'. When this option is t, the entire active region
  1729. will be placed in the search string of the file link. If set to a
  1730. positive integer, only the first n lines of context will be stored.
  1731. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1732. \\[org-store-link]')
  1733. negates this setting for the duration of the command."
  1734. :group 'org-link-store
  1735. :type '(choice boolean integer))
  1736. (defcustom org-keep-stored-link-after-insertion nil
  1737. "Non-nil means keep link in list for entire session.
  1738. \\<org-mode-map>
  1739. The command `org-store-link' adds a link pointing to the current
  1740. location to an internal list. These links accumulate during a session.
  1741. The command `org-insert-link' can be used to insert links into any
  1742. Org file (offering completion for all stored links).
  1743. When this option is nil, every link which has been inserted once using
  1744. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1745. unused
  1746. links more efficient."
  1747. :group 'org-link-store
  1748. :type 'boolean)
  1749. (defgroup org-link-follow nil
  1750. "Options concerning following links in Org mode."
  1751. :tag "Org Follow Link"
  1752. :group 'org-link)
  1753. (defcustom org-link-translation-function nil
  1754. "Function to translate links with different syntax to Org syntax.
  1755. This can be used to translate links created for example by the Planner
  1756. or emacs-wiki packages to Org syntax.
  1757. The function must accept two parameters, a TYPE containing the link
  1758. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1759. which is everything after the link protocol. It should return a cons
  1760. with possibly modified values of type and path.
  1761. Org contains a function for this, so if you set this variable to
  1762. `org-translate-link-from-planner', you should be able follow many
  1763. links created by planner."
  1764. :group 'org-link-follow
  1765. :type '(choice (const nil) (function)))
  1766. (defcustom org-follow-link-hook nil
  1767. "Hook that is run after a link has been followed."
  1768. :group 'org-link-follow
  1769. :type 'hook)
  1770. (defcustom org-tab-follows-link nil
  1771. "Non-nil means on links TAB will follow the link.
  1772. Needs to be set before org.el is loaded.
  1773. This really should not be used, it does not make sense, and the
  1774. implementation is bad."
  1775. :group 'org-link-follow
  1776. :type 'boolean)
  1777. (defcustom org-return-follows-link nil
  1778. "Non-nil means on links RET will follow the link.
  1779. In tables, the special behavior of RET has precedence."
  1780. :group 'org-link-follow
  1781. :type 'boolean)
  1782. (defcustom org-mouse-1-follows-link
  1783. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1784. "Non-nil means mouse-1 on a link will follow the link.
  1785. A longer mouse click will still set point. Needs to be set
  1786. before org.el is loaded."
  1787. :group 'org-link-follow
  1788. :version "26.1"
  1789. :package-version '(Org . "8.3")
  1790. :type '(choice
  1791. (const :tag "A double click follows the link" double)
  1792. (const :tag "Unconditionally follow the link with mouse-1" t)
  1793. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1794. (defcustom org-mark-ring-length 4
  1795. "Number of different positions to be recorded in the ring.
  1796. Changing this requires a restart of Emacs to work correctly."
  1797. :group 'org-link-follow
  1798. :type 'integer)
  1799. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1800. "Non-nil means internal fuzzy links can only match headlines.
  1801. When nil, the a fuzzy link may point to a target or a named
  1802. construct in the document. When set to the special value
  1803. `query-to-create', offer to create a new headline when none
  1804. matched.
  1805. Spaces and statistics cookies are ignored during heading searches."
  1806. :group 'org-link-follow
  1807. :version "24.1"
  1808. :type '(choice
  1809. (const :tag "Use fuzzy text search" nil)
  1810. (const :tag "Match only exact headline" t)
  1811. (const :tag "Match exact headline or query to create it"
  1812. query-to-create))
  1813. :safe #'symbolp)
  1814. (defcustom org-link-frame-setup
  1815. '((vm . vm-visit-folder-other-frame)
  1816. (vm-imap . vm-visit-imap-folder-other-frame)
  1817. (gnus . org-gnus-no-new-news)
  1818. (file . find-file-other-window)
  1819. (wl . wl-other-frame))
  1820. "Setup the frame configuration for following links.
  1821. When following a link with Emacs, it may often be useful to display
  1822. this link in another window or frame. This variable can be used to
  1823. set this up for the different types of links.
  1824. For VM, use any of
  1825. `vm-visit-folder'
  1826. `vm-visit-folder-other-window'
  1827. `vm-visit-folder-other-frame'
  1828. For Gnus, use any of
  1829. `gnus'
  1830. `gnus-other-frame'
  1831. `org-gnus-no-new-news'
  1832. For FILE, use any of
  1833. `find-file'
  1834. `find-file-other-window'
  1835. `find-file-other-frame'
  1836. For Wanderlust use any of
  1837. `wl'
  1838. `wl-other-frame'
  1839. For the calendar, use the variable `calendar-setup'.
  1840. For BBDB, it is currently only possible to display the matches in
  1841. another window."
  1842. :group 'org-link-follow
  1843. :type '(list
  1844. (cons (const vm)
  1845. (choice
  1846. (const vm-visit-folder)
  1847. (const vm-visit-folder-other-window)
  1848. (const vm-visit-folder-other-frame)))
  1849. (cons (const vm-imap)
  1850. (choice
  1851. (const vm-visit-imap-folder)
  1852. (const vm-visit-imap-folder-other-window)
  1853. (const vm-visit-imap-folder-other-frame)))
  1854. (cons (const gnus)
  1855. (choice
  1856. (const gnus)
  1857. (const gnus-other-frame)
  1858. (const org-gnus-no-new-news)))
  1859. (cons (const file)
  1860. (choice
  1861. (const find-file)
  1862. (const find-file-other-window)
  1863. (const find-file-other-frame)))
  1864. (cons (const wl)
  1865. (choice
  1866. (const wl)
  1867. (const wl-other-frame)))))
  1868. (defcustom org-display-internal-link-with-indirect-buffer nil
  1869. "Non-nil means use indirect buffer to display infile links.
  1870. Activating internal links (from one location in a file to another location
  1871. in the same file) normally just jumps to the location. When the link is
  1872. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1873. is displayed in
  1874. another window. When this option is set, the other window actually displays
  1875. an indirect buffer clone of the current buffer, to avoid any visibility
  1876. changes to the current buffer."
  1877. :group 'org-link-follow
  1878. :type 'boolean)
  1879. (defcustom org-open-non-existing-files nil
  1880. "Non-nil means `org-open-file' will open non-existing files.
  1881. When nil, an error will be generated.
  1882. This variable applies only to external applications because they
  1883. might choke on non-existing files. If the link is to a file that
  1884. will be opened in Emacs, the variable is ignored."
  1885. :group 'org-link-follow
  1886. :type 'boolean)
  1887. (defcustom org-open-directory-means-index-dot-org nil
  1888. "Non-nil means a link to a directory really means to index.org.
  1889. When nil, following a directory link will run dired or open a finder/explorer
  1890. window on that directory."
  1891. :group 'org-link-follow
  1892. :type 'boolean)
  1893. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1894. "Non-nil means ask for confirmation before executing shell links.
  1895. Shell links can be dangerous: just think about a link
  1896. [[shell:rm -rf ~/*][Google Search]]
  1897. This link would show up in your Org document as \"Google Search\",
  1898. but really it would remove your entire home directory.
  1899. Therefore we advise against setting this variable to nil.
  1900. Just change it to `y-or-n-p' if you want to confirm with a
  1901. single keystroke rather than having to type \"yes\"."
  1902. :group 'org-link-follow
  1903. :type '(choice
  1904. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1905. (const :tag "with y-or-n (faster)" y-or-n-p)
  1906. (const :tag "no confirmation (dangerous)" nil)))
  1907. (put 'org-confirm-shell-link-function
  1908. 'safe-local-variable
  1909. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1910. (defcustom org-confirm-shell-link-not-regexp ""
  1911. "A regexp to skip confirmation for shell links."
  1912. :group 'org-link-follow
  1913. :version "24.1"
  1914. :type 'regexp)
  1915. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1916. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1917. Elisp links can be dangerous: just think about a link
  1918. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1919. This link would show up in your Org document as \"Google Search\",
  1920. but really it would remove your entire home directory.
  1921. Therefore we advise against setting this variable to nil.
  1922. Just change it to `y-or-n-p' if you want to confirm with a
  1923. single keystroke rather than having to type \"yes\"."
  1924. :group 'org-link-follow
  1925. :type '(choice
  1926. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1927. (const :tag "with y-or-n (faster)" y-or-n-p)
  1928. (const :tag "no confirmation (dangerous)" nil)))
  1929. (put 'org-confirm-shell-link-function
  1930. 'safe-local-variable
  1931. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1932. (defcustom org-confirm-elisp-link-not-regexp ""
  1933. "A regexp to skip confirmation for Elisp links."
  1934. :group 'org-link-follow
  1935. :version "24.1"
  1936. :type 'regexp)
  1937. (defconst org-file-apps-defaults-gnu
  1938. '((remote . emacs)
  1939. (system . mailcap)
  1940. (t . mailcap))
  1941. "Default file applications on a UNIX or GNU/Linux system.
  1942. See `org-file-apps'.")
  1943. (defconst org-file-apps-defaults-macosx
  1944. '((remote . emacs)
  1945. (system . "open %s")
  1946. ("ps.gz" . "gv %s")
  1947. ("eps.gz" . "gv %s")
  1948. ("dvi" . "xdvi %s")
  1949. ("fig" . "xfig %s")
  1950. (t . "open %s"))
  1951. "Default file applications on a macOS system.
  1952. The system \"open\" is known as a default, but we use X11 applications
  1953. for some files for which the OS does not have a good default.
  1954. See `org-file-apps'.")
  1955. (defconst org-file-apps-defaults-windowsnt
  1956. (list '(remote . emacs)
  1957. (cons 'system (lambda (file _path)
  1958. (with-no-warnings (w32-shell-execute "open" file))))
  1959. (cons t (lambda (file _path)
  1960. (with-no-warnings (w32-shell-execute "open" file)))))
  1961. "Default file applications on a Windows NT system.
  1962. The system \"open\" is used for most files.
  1963. See `org-file-apps'.")
  1964. (defcustom org-file-apps
  1965. '((auto-mode . emacs)
  1966. ("\\.mm\\'" . default)
  1967. ("\\.x?html?\\'" . default)
  1968. ("\\.pdf\\'" . default))
  1969. "External applications for opening `file:path' items in a document.
  1970. \\<org-mode-map>\
  1971. Org mode uses system defaults for different file types, but
  1972. you can use this variable to set the application for a given file
  1973. extension. The entries in this list are cons cells where the car identifies
  1974. files and the cdr the corresponding command.
  1975. Possible values for the file identifier are:
  1976. \"string\" A string as a file identifier can be interpreted in different
  1977. ways, depending on its contents:
  1978. - Alphanumeric characters only:
  1979. Match links with this file extension.
  1980. Example: (\"pdf\" . \"evince %s\")
  1981. to open PDFs with evince.
  1982. - Regular expression: Match links where the
  1983. filename matches the regexp. If you want to
  1984. use groups here, use shy groups.
  1985. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1986. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1987. to open *.html and *.xhtml with firefox.
  1988. - Regular expression which contains (non-shy) groups:
  1989. Match links where the whole link, including \"::\", and
  1990. anything after that, matches the regexp.
  1991. In a custom command string, %1, %2, etc. are replaced with
  1992. the parts of the link that were matched by the groups.
  1993. For backwards compatibility, if a command string is given
  1994. that does not use any of the group matches, this case is
  1995. handled identically to the second one (i.e. match against
  1996. file name only).
  1997. In a custom function, you can access the group matches with
  1998. (match-string n link).
  1999. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  2000. \"evince -p %1 %s\")
  2001. to open [[file:document.pdf::5]] with evince at page 5.
  2002. `directory' Matches a directory
  2003. `remote' Matches a remote file, accessible through tramp or efs.
  2004. Remote files most likely should be visited through Emacs
  2005. because external applications cannot handle such paths.
  2006. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  2007. so all files Emacs knows how to handle. Using this with
  2008. command `emacs' will open most files in Emacs. Beware that this
  2009. will also open html files inside Emacs, unless you add
  2010. (\"html\" . default) to the list as well.
  2011. `system' The system command to open files, like `open' on Windows
  2012. and macOS, and mailcap under GNU/Linux. This is the command
  2013. that will be selected if you call `org-open-at-point' with a
  2014. double prefix argument (`\\[universal-argument] \
  2015. \\[universal-argument] \\[org-open-at-point]').
  2016. t Default for files not matched by any of the other options.
  2017. Possible values for the command are:
  2018. `emacs' The file will be visited by the current Emacs process.
  2019. `default' Use the default application for this file type, which is the
  2020. association for t in the list, most likely in the system-specific
  2021. part. This can be used to overrule an unwanted setting in the
  2022. system-specific variable.
  2023. `system' Use the system command for opening files, like \"open\".
  2024. This command is specified by the entry whose car is `system'.
  2025. Most likely, the system-specific version of this variable
  2026. does define this command, but you can overrule/replace it
  2027. here.
  2028. `mailcap' Use command specified in the mailcaps.
  2029. string A command to be executed by a shell; %s will be replaced
  2030. by the path to the file.
  2031. function A Lisp function, which will be called with two arguments:
  2032. the file path and the original link string, without the
  2033. \"file:\" prefix.
  2034. For more examples, see the system specific constants
  2035. `org-file-apps-defaults-macosx'
  2036. `org-file-apps-defaults-windowsnt'
  2037. `org-file-apps-defaults-gnu'."
  2038. :group 'org-link-follow
  2039. :type '(repeat
  2040. (cons (choice :value ""
  2041. (string :tag "Extension")
  2042. (const :tag "System command to open files" system)
  2043. (const :tag "Default for unrecognized files" t)
  2044. (const :tag "Remote file" remote)
  2045. (const :tag "Links to a directory" directory)
  2046. (const :tag "Any files that have Emacs modes"
  2047. auto-mode))
  2048. (choice :value ""
  2049. (const :tag "Visit with Emacs" emacs)
  2050. (const :tag "Use default" default)
  2051. (const :tag "Use the system command" system)
  2052. (string :tag "Command")
  2053. (function :tag "Function")))))
  2054. (defcustom org-doi-server-url "http://dx.doi.org/"
  2055. "The URL of the DOI server."
  2056. :type 'string
  2057. :version "24.3"
  2058. :group 'org-link-follow)
  2059. (defgroup org-refile nil
  2060. "Options concerning refiling entries in Org mode."
  2061. :tag "Org Refile"
  2062. :group 'org)
  2063. (defcustom org-directory "~/org"
  2064. "Directory with Org files.
  2065. This is just a default location to look for Org files. There is no need
  2066. at all to put your files into this directory. It is used in the
  2067. following situations:
  2068. 1. When a capture template specifies a target file that is not an
  2069. absolute path. The path will then be interpreted relative to
  2070. `org-directory'
  2071. 2. When the value of variable `org-agenda-files' is a single file, any
  2072. relative paths in this file will be taken as relative to
  2073. `org-directory'."
  2074. :group 'org-refile
  2075. :group 'org-capture
  2076. :type 'directory)
  2077. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2078. "Default target for storing notes.
  2079. Used as a fall back file for org-capture.el, for templates that
  2080. do not specify a target file."
  2081. :group 'org-refile
  2082. :group 'org-capture
  2083. :type 'file)
  2084. (defcustom org-reverse-note-order nil
  2085. "Non-nil means store new notes at the beginning of a file or entry.
  2086. When nil, new notes will be filed to the end of a file or entry.
  2087. This can also be a list with cons cells of regular expressions that
  2088. are matched against file names, and values."
  2089. :group 'org-capture
  2090. :group 'org-refile
  2091. :type '(choice
  2092. (const :tag "Reverse always" t)
  2093. (const :tag "Reverse never" nil)
  2094. (repeat :tag "By file name regexp"
  2095. (cons regexp boolean))))
  2096. (defcustom org-log-refile nil
  2097. "Information to record when a task is refiled.
  2098. Possible values are:
  2099. nil Don't add anything
  2100. time Add a time stamp to the task
  2101. note Prompt for a note and add it with template `org-log-note-headings'
  2102. This option can also be set with on a per-file-basis with
  2103. #+STARTUP: nologrefile
  2104. #+STARTUP: logrefile
  2105. #+STARTUP: lognoterefile
  2106. You can have local logging settings for a subtree by setting the LOGGING
  2107. property to one or more of these keywords.
  2108. When bulk-refiling from the agenda, the value `note' is forbidden and
  2109. will temporarily be changed to `time'."
  2110. :group 'org-refile
  2111. :group 'org-progress
  2112. :version "24.1"
  2113. :type '(choice
  2114. (const :tag "No logging" nil)
  2115. (const :tag "Record timestamp" time)
  2116. (const :tag "Record timestamp with note." note)))
  2117. (defcustom org-refile-targets nil
  2118. "Targets for refiling entries with `\\[org-refile]'.
  2119. This is a list of cons cells. Each cell contains:
  2120. - a specification of the files to be considered, either a list of files,
  2121. or a symbol whose function or variable value will be used to retrieve
  2122. a file name or a list of file names. If you use `org-agenda-files' for
  2123. that, all agenda files will be scanned for targets. Nil means consider
  2124. headings in the current buffer.
  2125. - A specification of how to find candidate refile targets. This may be
  2126. any of:
  2127. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2128. This tag has to be present in all target headlines, inheritance will
  2129. not be considered.
  2130. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2131. todo keyword.
  2132. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2133. headlines that are refiling targets.
  2134. - a cons cell (:level . N). Any headline of level N is considered a target.
  2135. Note that, when `org-odd-levels-only' is set, level corresponds to
  2136. order in hierarchy, not to the number of stars.
  2137. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2138. Note that, when `org-odd-levels-only' is set, level corresponds to
  2139. order in hierarchy, not to the number of stars.
  2140. Each element of this list generates a set of possible targets.
  2141. The union of these sets is presented (with completion) to
  2142. the user by `org-refile'.
  2143. You can set the variable `org-refile-target-verify-function' to a function
  2144. to verify each headline found by the simple criteria above.
  2145. When this variable is nil, all top-level headlines in the current buffer
  2146. are used, equivalent to the value `((nil . (:level . 1))'."
  2147. :group 'org-refile
  2148. :type '(repeat
  2149. (cons
  2150. (choice :value org-agenda-files
  2151. (const :tag "All agenda files" org-agenda-files)
  2152. (const :tag "Current buffer" nil)
  2153. (function) (variable) (file))
  2154. (choice :tag "Identify target headline by"
  2155. (cons :tag "Specific tag" (const :value :tag) (string))
  2156. (cons :tag "TODO keyword" (const :value :todo) (string))
  2157. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2158. (cons :tag "Level number" (const :value :level) (integer))
  2159. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2160. (defcustom org-refile-target-verify-function nil
  2161. "Function to verify if the headline at point should be a refile target.
  2162. The function will be called without arguments, with point at the
  2163. beginning of the headline. It should return t and leave point
  2164. where it is if the headline is a valid target for refiling.
  2165. If the target should not be selected, the function must return nil.
  2166. In addition to this, it may move point to a place from where the search
  2167. should be continued. For example, the function may decide that the entire
  2168. subtree of the current entry should be excluded and move point to the end
  2169. of the subtree."
  2170. :group 'org-refile
  2171. :type '(choice
  2172. (const nil)
  2173. (function)))
  2174. (defcustom org-refile-use-cache nil
  2175. "Non-nil means cache refile targets to speed up the process.
  2176. \\<org-mode-map>\
  2177. The cache for a particular file will be updated automatically when
  2178. the buffer has been killed, or when any of the marker used for flagging
  2179. refile targets no longer points at a live buffer.
  2180. If you have added new entries to a buffer that might themselves be targets,
  2181. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2182. if you find that easier, \
  2183. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2184. \\[org-refile]'."
  2185. :group 'org-refile
  2186. :version "24.1"
  2187. :type 'boolean)
  2188. (defcustom org-refile-use-outline-path nil
  2189. "Non-nil means provide refile targets as paths.
  2190. So a level 3 headline will be available as level1/level2/level3.
  2191. When the value is `file', also include the file name (without directory)
  2192. into the path. In this case, you can also stop the completion after
  2193. the file name, to get entries inserted as top level in the file.
  2194. When `full-file-path', include the full file path.
  2195. When `buffer-name', use the buffer name."
  2196. :group 'org-refile
  2197. :type '(choice
  2198. (const :tag "Not" nil)
  2199. (const :tag "Yes" t)
  2200. (const :tag "Start with file name" file)
  2201. (const :tag "Start with full file path" full-file-path)
  2202. (const :tag "Start with buffer name" buffer-name)))
  2203. (defcustom org-outline-path-complete-in-steps t
  2204. "Non-nil means complete the outline path in hierarchical steps.
  2205. When Org uses the refile interface to select an outline path (see
  2206. `org-refile-use-outline-path'), the completion of the path can be
  2207. done in a single go, or it can be done in steps down the headline
  2208. hierarchy. Going in steps is probably the best if you do not use
  2209. a special completion package like `ido' or `icicles'. However,
  2210. when using these packages, going in one step can be very fast,
  2211. while still showing the whole path to the entry."
  2212. :group 'org-refile
  2213. :type 'boolean)
  2214. (defcustom org-refile-allow-creating-parent-nodes nil
  2215. "Non-nil means allow the creation of new nodes as refile targets.
  2216. New nodes are then created by adding \"/new node name\" to the completion
  2217. of an existing node. When the value of this variable is `confirm',
  2218. new node creation must be confirmed by the user (recommended).
  2219. When nil, the completion must match an existing entry.
  2220. Note that, if the new heading is not seen by the criteria
  2221. listed in `org-refile-targets', multiple instances of the same
  2222. heading would be created by trying again to file under the new
  2223. heading."
  2224. :group 'org-refile
  2225. :type '(choice
  2226. (const :tag "Never" nil)
  2227. (const :tag "Always" t)
  2228. (const :tag "Prompt for confirmation" confirm)))
  2229. (defcustom org-refile-active-region-within-subtree nil
  2230. "Non-nil means also refile active region within a subtree.
  2231. By default `org-refile' doesn't allow refiling regions if they
  2232. don't contain a set of subtrees, but it might be convenient to
  2233. do so sometimes: in that case, the first line of the region is
  2234. converted to a headline before refiling."
  2235. :group 'org-refile
  2236. :version "24.1"
  2237. :type 'boolean)
  2238. (defgroup org-todo nil
  2239. "Options concerning TODO items in Org mode."
  2240. :tag "Org TODO"
  2241. :group 'org)
  2242. (defgroup org-progress nil
  2243. "Options concerning Progress logging in Org mode."
  2244. :tag "Org Progress"
  2245. :group 'org-time)
  2246. (defvar org-todo-interpretation-widgets
  2247. '((:tag "Sequence (cycling hits every state)" sequence)
  2248. (:tag "Type (cycling directly to DONE)" type))
  2249. "The available interpretation symbols for customizing `org-todo-keywords'.
  2250. Interested libraries should add to this list.")
  2251. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2252. "List of TODO entry keyword sequences and their interpretation.
  2253. \\<org-mode-map>This is a list of sequences.
  2254. Each sequence starts with a symbol, either `sequence' or `type',
  2255. indicating if the keywords should be interpreted as a sequence of
  2256. action steps, or as different types of TODO items. The first
  2257. keywords are states requiring action - these states will select a headline
  2258. for inclusion into the global TODO list Org produces. If one of the
  2259. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2260. signify that no further action is necessary. If \"|\" is not found,
  2261. the last keyword is treated as the only DONE state of the sequence.
  2262. The command `\\[org-todo]' cycles an entry through these states, and one
  2263. additional state where no keyword is present. For details about this
  2264. cycling, see the manual.
  2265. TODO keywords and interpretation can also be set on a per-file basis with
  2266. the special #+SEQ_TODO and #+TYP_TODO lines.
  2267. Each keyword can optionally specify a character for fast state selection
  2268. \(in combination with the variable `org-use-fast-todo-selection')
  2269. and specifiers for state change logging, using the same syntax that
  2270. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2271. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2272. indicates to record a time stamp each time this state is selected.
  2273. Each keyword may also specify if a timestamp or a note should be
  2274. recorded when entering or leaving the state, by adding additional
  2275. characters in the parenthesis after the keyword. This looks like this:
  2276. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2277. record only the time of the state change. With X and Y being either
  2278. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2279. Y when leaving the state if and only if the *target* state does not
  2280. define X. You may omit any of the fast-selection key or X or /Y,
  2281. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2282. For backward compatibility, this variable may also be just a list
  2283. of keywords. In this case the interpretation (sequence or type) will be
  2284. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2285. :group 'org-todo
  2286. :group 'org-keywords
  2287. :type '(choice
  2288. (repeat :tag "Old syntax, just keywords"
  2289. (string :tag "Keyword"))
  2290. (repeat :tag "New syntax"
  2291. (cons
  2292. (choice
  2293. :tag "Interpretation"
  2294. ;;Quick and dirty way to see
  2295. ;;`org-todo-interpretations'. This takes the
  2296. ;;place of item arguments
  2297. :convert-widget
  2298. (lambda (widget)
  2299. (widget-put widget
  2300. :args (mapcar
  2301. (lambda (x)
  2302. (widget-convert
  2303. (cons 'const x)))
  2304. org-todo-interpretation-widgets))
  2305. widget))
  2306. (repeat
  2307. (string :tag "Keyword"))))))
  2308. (defvar-local org-todo-keywords-1 nil
  2309. "All TODO and DONE keywords active in a buffer.")
  2310. (defvar org-todo-keywords-for-agenda nil)
  2311. (defvar org-done-keywords-for-agenda nil)
  2312. (defvar org-todo-keyword-alist-for-agenda nil)
  2313. (defvar org-tag-alist-for-agenda nil
  2314. "Alist of all tags from all agenda files.")
  2315. (defvar org-tag-groups-alist-for-agenda nil
  2316. "Alist of all groups tags from all current agenda files.")
  2317. (defvar-local org-tag-groups-alist nil)
  2318. (defvar org-agenda-contributing-files nil)
  2319. (defvar-local org-current-tag-alist nil
  2320. "Alist of all tag groups in current buffer.
  2321. This variable takes into consideration `org-tag-alist',
  2322. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2323. (defvar-local org-not-done-keywords nil)
  2324. (defvar-local org-done-keywords nil)
  2325. (defvar-local org-todo-heads nil)
  2326. (defvar-local org-todo-sets nil)
  2327. (defvar-local org-todo-log-states nil)
  2328. (defvar-local org-todo-kwd-alist nil)
  2329. (defvar-local org-todo-key-alist nil)
  2330. (defvar-local org-todo-key-trigger nil)
  2331. (defcustom org-todo-interpretation 'sequence
  2332. "Controls how TODO keywords are interpreted.
  2333. This variable is in principle obsolete and is only used for
  2334. backward compatibility, if the interpretation of todo keywords is
  2335. not given already in `org-todo-keywords'. See that variable for
  2336. more information."
  2337. :group 'org-todo
  2338. :group 'org-keywords
  2339. :type '(choice (const sequence)
  2340. (const type)))
  2341. (defcustom org-use-fast-todo-selection t
  2342. "\\<org-mode-map>\
  2343. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2344. This variable describes if and under what circumstances the cycling
  2345. mechanism for TODO keywords will be replaced by a single-key, direct
  2346. selection scheme.
  2347. When nil, fast selection is never used.
  2348. When the symbol `prefix', it will be used when `org-todo' is called
  2349. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2350. in an Org buffer, and
  2351. `\\[universal-argument] t' in an agenda buffer.
  2352. When t, fast selection is used by default. In this case, the prefix
  2353. argument forces cycling instead.
  2354. In all cases, the special interface is only used if access keys have
  2355. actually been assigned by the user, i.e. if keywords in the configuration
  2356. are followed by a letter in parenthesis, like TODO(t)."
  2357. :group 'org-todo
  2358. :type '(choice
  2359. (const :tag "Never" nil)
  2360. (const :tag "By default" t)
  2361. (const :tag "Only with C-u C-c C-t" prefix)))
  2362. (defcustom org-provide-todo-statistics t
  2363. "Non-nil means update todo statistics after insert and toggle.
  2364. ALL-HEADLINES means update todo statistics by including headlines
  2365. with no TODO keyword as well, counting them as not done.
  2366. A list of TODO keywords means the same, but skip keywords that are
  2367. not in this list.
  2368. When set to a list of two lists, the first list contains keywords
  2369. to consider as TODO keywords, the second list contains keywords
  2370. to consider as DONE keywords.
  2371. When this is set, todo statistics is updated in the parent of the
  2372. current entry each time a todo state is changed."
  2373. :group 'org-todo
  2374. :type '(choice
  2375. (const :tag "Yes, only for TODO entries" t)
  2376. (const :tag "Yes, including all entries" all-headlines)
  2377. (repeat :tag "Yes, for TODOs in this list"
  2378. (string :tag "TODO keyword"))
  2379. (list :tag "Yes, for TODOs and DONEs in these lists"
  2380. (repeat (string :tag "TODO keyword"))
  2381. (repeat (string :tag "DONE keyword")))
  2382. (other :tag "No TODO statistics" nil)))
  2383. (defcustom org-hierarchical-todo-statistics t
  2384. "Non-nil means TODO statistics covers just direct children.
  2385. When nil, all entries in the subtree are considered.
  2386. This has only an effect if `org-provide-todo-statistics' is set.
  2387. To set this to nil for only a single subtree, use a COOKIE_DATA
  2388. property and include the word \"recursive\" into the value."
  2389. :group 'org-todo
  2390. :type 'boolean)
  2391. (defcustom org-after-todo-state-change-hook nil
  2392. "Hook which is run after the state of a TODO item was changed.
  2393. The new state (a string with a TODO keyword, or nil) is available in the
  2394. Lisp variable `org-state'."
  2395. :group 'org-todo
  2396. :type 'hook)
  2397. (defvar org-blocker-hook nil
  2398. "Hook for functions that are allowed to block a state change.
  2399. Functions in this hook should not modify the buffer.
  2400. Each function gets as its single argument a property list,
  2401. see `org-trigger-hook' for more information about this list.
  2402. If any of the functions in this hook returns nil, the state change
  2403. is blocked.")
  2404. (defvar org-trigger-hook nil
  2405. "Hook for functions that are triggered by a state change.
  2406. Each function gets as its single argument a property list with at
  2407. least the following elements:
  2408. (:type type-of-change :position pos-at-entry-start
  2409. :from old-state :to new-state)
  2410. Depending on the type, more properties may be present.
  2411. This mechanism is currently implemented for:
  2412. TODO state changes
  2413. ------------------
  2414. :type todo-state-change
  2415. :from previous state (keyword as a string), or nil, or a symbol
  2416. `todo' or `done', to indicate the general type of state.
  2417. :to new state, like in :from")
  2418. (defcustom org-enforce-todo-dependencies nil
  2419. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2420. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2421. be blocked if any prior sibling is not yet done.
  2422. Finally, if the parent is blocked because of ordered siblings of its own,
  2423. the child will also be blocked."
  2424. :set (lambda (var val)
  2425. (set var val)
  2426. (if val
  2427. (add-hook 'org-blocker-hook
  2428. 'org-block-todo-from-children-or-siblings-or-parent)
  2429. (remove-hook 'org-blocker-hook
  2430. 'org-block-todo-from-children-or-siblings-or-parent)))
  2431. :group 'org-todo
  2432. :type 'boolean)
  2433. (defcustom org-enforce-todo-checkbox-dependencies nil
  2434. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2435. When this is nil, checkboxes have no influence on switching TODO states.
  2436. When non-nil, you first need to check off all check boxes before the TODO
  2437. entry can be switched to DONE.
  2438. This variable needs to be set before org.el is loaded, and you need to
  2439. restart Emacs after a change to make the change effective. The only way
  2440. to change is while Emacs is running is through the customize interface."
  2441. :set (lambda (var val)
  2442. (set var val)
  2443. (if val
  2444. (add-hook 'org-blocker-hook
  2445. 'org-block-todo-from-checkboxes)
  2446. (remove-hook 'org-blocker-hook
  2447. 'org-block-todo-from-checkboxes)))
  2448. :group 'org-todo
  2449. :type 'boolean)
  2450. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2451. "Non-nil means inserting a TODO heading is treated as state change.
  2452. So when the command `\\[org-insert-todo-heading]' is used, state change
  2453. logging will apply if appropriate. When nil, the new TODO item will
  2454. be inserted directly, and no logging will take place."
  2455. :group 'org-todo
  2456. :type 'boolean)
  2457. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2458. "Non-nil means switching TODO states with S-cursor counts as state change.
  2459. This is the default behavior. However, setting this to nil allows a
  2460. convenient way to select a TODO state and bypass any logging associated
  2461. with that."
  2462. :group 'org-todo
  2463. :type 'boolean)
  2464. (defcustom org-todo-state-tags-triggers nil
  2465. "Tag changes that should be triggered by TODO state changes.
  2466. This is a list. Each entry is
  2467. (state-change (tag . flag) .......)
  2468. State-change can be a string with a state, and empty string to indicate the
  2469. state that has no TODO keyword, or it can be one of the symbols `todo'
  2470. or `done', meaning any not-done or done state, respectively."
  2471. :group 'org-todo
  2472. :group 'org-tags
  2473. :type '(repeat
  2474. (cons (choice :tag "When changing to"
  2475. (const :tag "Not-done state" todo)
  2476. (const :tag "Done state" done)
  2477. (string :tag "State"))
  2478. (repeat
  2479. (cons :tag "Tag action"
  2480. (string :tag "Tag")
  2481. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2482. (defcustom org-log-done nil
  2483. "Information to record when a task moves to the DONE state.
  2484. Possible values are:
  2485. nil Don't add anything, just change the keyword
  2486. time Add a time stamp to the task
  2487. note Prompt for a note and add it with template `org-log-note-headings'
  2488. This option can also be set with on a per-file-basis with
  2489. #+STARTUP: nologdone
  2490. #+STARTUP: logdone
  2491. #+STARTUP: lognotedone
  2492. You can have local logging settings for a subtree by setting the LOGGING
  2493. property to one or more of these keywords."
  2494. :group 'org-todo
  2495. :group 'org-progress
  2496. :type '(choice
  2497. (const :tag "No logging" nil)
  2498. (const :tag "Record CLOSED timestamp" time)
  2499. (const :tag "Record CLOSED timestamp with note." note)))
  2500. ;; Normalize old uses of org-log-done.
  2501. (cond
  2502. ((eq org-log-done t) (setq org-log-done 'time))
  2503. ((and (listp org-log-done) (memq 'done org-log-done))
  2504. (setq org-log-done 'note)))
  2505. (defcustom org-log-reschedule nil
  2506. "Information to record when the scheduling date of a tasks is modified.
  2507. Possible values are:
  2508. nil Don't add anything, just change the date
  2509. time Add a time stamp to the task
  2510. note Prompt for a note and add it with template `org-log-note-headings'
  2511. This option can also be set with on a per-file-basis with
  2512. #+STARTUP: nologreschedule
  2513. #+STARTUP: logreschedule
  2514. #+STARTUP: lognotereschedule"
  2515. :group 'org-todo
  2516. :group 'org-progress
  2517. :type '(choice
  2518. (const :tag "No logging" nil)
  2519. (const :tag "Record timestamp" time)
  2520. (const :tag "Record timestamp with note." note)))
  2521. (defcustom org-log-redeadline nil
  2522. "Information to record when the deadline date of a tasks is modified.
  2523. Possible values are:
  2524. nil Don't add anything, just change the date
  2525. time Add a time stamp to the task
  2526. note Prompt for a note and add it with template `org-log-note-headings'
  2527. This option can also be set with on a per-file-basis with
  2528. #+STARTUP: nologredeadline
  2529. #+STARTUP: logredeadline
  2530. #+STARTUP: lognoteredeadline
  2531. You can have local logging settings for a subtree by setting the LOGGING
  2532. property to one or more of these keywords."
  2533. :group 'org-todo
  2534. :group 'org-progress
  2535. :type '(choice
  2536. (const :tag "No logging" nil)
  2537. (const :tag "Record timestamp" time)
  2538. (const :tag "Record timestamp with note." note)))
  2539. (defcustom org-log-note-clock-out nil
  2540. "Non-nil means record a note when clocking out of an item.
  2541. This can also be configured on a per-file basis by adding one of
  2542. the following lines anywhere in the buffer:
  2543. #+STARTUP: lognoteclock-out
  2544. #+STARTUP: nolognoteclock-out"
  2545. :group 'org-todo
  2546. :group 'org-progress
  2547. :type 'boolean)
  2548. (defcustom org-log-done-with-time t
  2549. "Non-nil means the CLOSED time stamp will contain date and time.
  2550. When nil, only the date will be recorded."
  2551. :group 'org-progress
  2552. :type 'boolean)
  2553. (defcustom org-log-note-headings
  2554. '((done . "CLOSING NOTE %t")
  2555. (state . "State %-12s from %-12S %t")
  2556. (note . "Note taken on %t")
  2557. (reschedule . "Rescheduled from %S on %t")
  2558. (delschedule . "Not scheduled, was %S on %t")
  2559. (redeadline . "New deadline from %S on %t")
  2560. (deldeadline . "Removed deadline, was %S on %t")
  2561. (refile . "Refiled on %t")
  2562. (clock-out . ""))
  2563. "Headings for notes added to entries.
  2564. The value is an alist, with the car being a symbol indicating the
  2565. note context, and the cdr is the heading to be used. The heading
  2566. may also be the empty string. The following placeholders can be
  2567. used:
  2568. %t a time stamp.
  2569. %T an active time stamp instead the default inactive one
  2570. %d a short-format time stamp.
  2571. %D an active short-format time stamp.
  2572. %s the new TODO state or time stamp (inactive), in double quotes.
  2573. %S the old TODO state or time stamp (inactive), in double quotes.
  2574. %u the user name.
  2575. %U full user name.
  2576. In fact, it is not a good idea to change the `state' entry,
  2577. because Agenda Log mode depends on the format of these entries."
  2578. :group 'org-todo
  2579. :group 'org-progress
  2580. :type '(list :greedy t
  2581. (cons (const :tag "Heading when closing an item" done) string)
  2582. (cons (const :tag
  2583. "Heading when changing todo state (todo sequence only)"
  2584. state) string)
  2585. (cons (const :tag "Heading when just taking a note" note) string)
  2586. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2587. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2588. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2589. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2590. (cons (const :tag "Heading when refiling" refile) string)
  2591. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2592. (unless (assq 'note org-log-note-headings)
  2593. (push '(note . "%t") org-log-note-headings))
  2594. (defcustom org-log-into-drawer nil
  2595. "Non-nil means insert state change notes and time stamps into a drawer.
  2596. When nil, state changes notes will be inserted after the headline and
  2597. any scheduling and clock lines, but not inside a drawer.
  2598. The value of this variable should be the name of the drawer to use.
  2599. LOGBOOK is proposed as the default drawer for this purpose, you can
  2600. also set this to a string to define the drawer of your choice.
  2601. A value of t is also allowed, representing \"LOGBOOK\".
  2602. A value of t or nil can also be set with on a per-file-basis with
  2603. #+STARTUP: logdrawer
  2604. #+STARTUP: nologdrawer
  2605. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2606. will be ignored.
  2607. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2608. a subtree.
  2609. Do not check directly this variable in a Lisp program. Call
  2610. function `org-log-into-drawer' instead."
  2611. :group 'org-todo
  2612. :group 'org-progress
  2613. :type '(choice
  2614. (const :tag "Not into a drawer" nil)
  2615. (const :tag "LOGBOOK" t)
  2616. (string :tag "Other")))
  2617. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2618. (defun org-log-into-drawer ()
  2619. "Name of the log drawer, as a string, or nil.
  2620. This is the value of `org-log-into-drawer'. However, if the
  2621. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2622. be used instead of the default value."
  2623. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2624. (cond ((equal p "nil") nil)
  2625. ((equal p "t") "LOGBOOK")
  2626. ((stringp p) p)
  2627. (p "LOGBOOK")
  2628. ((stringp org-log-into-drawer) org-log-into-drawer)
  2629. (org-log-into-drawer "LOGBOOK"))))
  2630. (defcustom org-log-state-notes-insert-after-drawers nil
  2631. "Non-nil means insert state change notes after any drawers in entry.
  2632. Only the drawers that *immediately* follow the headline and the
  2633. deadline/scheduled line are skipped.
  2634. When nil, insert notes right after the heading and perhaps the line
  2635. with deadline/scheduling if present.
  2636. This variable will have no effect if `org-log-into-drawer' is
  2637. set."
  2638. :group 'org-todo
  2639. :group 'org-progress
  2640. :type 'boolean)
  2641. (defcustom org-log-states-order-reversed t
  2642. "Non-nil means the latest state note will be directly after heading.
  2643. When nil, the state change notes will be ordered according to time.
  2644. This option can also be set with on a per-file-basis with
  2645. #+STARTUP: logstatesreversed
  2646. #+STARTUP: nologstatesreversed"
  2647. :group 'org-todo
  2648. :group 'org-progress
  2649. :type 'boolean)
  2650. (defcustom org-todo-repeat-to-state nil
  2651. "The TODO state to which a repeater should return the repeating task.
  2652. By default this is the first task of a TODO sequence or the
  2653. previous state of a TYPE_TODO set. But you can specify to use
  2654. the previous state in a TODO sequence or a string.
  2655. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2656. entry, which has precedence over this option."
  2657. :group 'org-todo
  2658. :version "24.1"
  2659. :type '(choice (const :tag "Use the previous TODO state" t)
  2660. (const :tag "Use the head of the TODO sequence" nil)
  2661. (string :tag "Use a specific TODO state")))
  2662. (defcustom org-log-repeat 'time
  2663. "Non-nil means record moving through the DONE state when triggering repeat.
  2664. An auto-repeating task is immediately switched back to TODO when
  2665. marked DONE. If you are not logging state changes (by adding \"@\"
  2666. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2667. record a closing note, there will be no record of the task moving
  2668. through DONE. This variable forces taking a note anyway.
  2669. nil Don't force a record
  2670. time Record a time stamp
  2671. note Prompt for a note and add it with template `org-log-note-headings'
  2672. This option can also be set with on a per-file-basis with
  2673. #+STARTUP: nologrepeat
  2674. #+STARTUP: logrepeat
  2675. #+STARTUP: lognoterepeat
  2676. You can have local logging settings for a subtree by setting the LOGGING
  2677. property to one or more of these keywords."
  2678. :group 'org-todo
  2679. :group 'org-progress
  2680. :type '(choice
  2681. (const :tag "Don't force a record" nil)
  2682. (const :tag "Force recording the DONE state" time)
  2683. (const :tag "Force recording a note with the DONE state" note)))
  2684. (defgroup org-priorities nil
  2685. "Priorities in Org mode."
  2686. :tag "Org Priorities"
  2687. :group 'org-todo)
  2688. (defcustom org-enable-priority-commands t
  2689. "Non-nil means priority commands are active.
  2690. When nil, these commands will be disabled, so that you never accidentally
  2691. set a priority."
  2692. :group 'org-priorities
  2693. :type 'boolean)
  2694. (defcustom org-highest-priority ?A
  2695. "The highest priority of TODO items. A character like ?A, ?B etc.
  2696. Must have a smaller ASCII number than `org-lowest-priority'."
  2697. :group 'org-priorities
  2698. :type 'character)
  2699. (defcustom org-lowest-priority ?C
  2700. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2701. Must have a larger ASCII number than `org-highest-priority'."
  2702. :group 'org-priorities
  2703. :type 'character)
  2704. (defcustom org-default-priority ?B
  2705. "The default priority of TODO items.
  2706. This is the priority an item gets if no explicit priority is given.
  2707. When starting to cycle on an empty priority the first step in the cycle
  2708. depends on `org-priority-start-cycle-with-default'. The resulting first
  2709. step priority must not exceed the range from `org-highest-priority' to
  2710. `org-lowest-priority' which means that `org-default-priority' has to be
  2711. in this range exclusive or inclusive the range boundaries. Else the
  2712. first step refuses to set the default and the second will fall back
  2713. to (depending on the command used) the highest or lowest priority."
  2714. :group 'org-priorities
  2715. :type 'character)
  2716. (defcustom org-priority-start-cycle-with-default t
  2717. "Non-nil means start with default priority when starting to cycle.
  2718. When this is nil, the first step in the cycle will be (depending on the
  2719. command used) one higher or lower than the default priority.
  2720. See also `org-default-priority'."
  2721. :group 'org-priorities
  2722. :type 'boolean)
  2723. (defcustom org-get-priority-function nil
  2724. "Function to extract the priority from a string.
  2725. The string is normally the headline. If this is nil Org computes the
  2726. priority from the priority cookie like [#A] in the headline. It returns
  2727. an integer, increasing by 1000 for each priority level.
  2728. The user can set a different function here, which should take a string
  2729. as an argument and return the numeric priority."
  2730. :group 'org-priorities
  2731. :version "24.1"
  2732. :type '(choice
  2733. (const nil)
  2734. (function)))
  2735. (defgroup org-time nil
  2736. "Options concerning time stamps and deadlines in Org mode."
  2737. :tag "Org Time"
  2738. :group 'org)
  2739. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2740. "Number of minutes to round time stamps to.
  2741. \\<org-mode-map>\
  2742. These are two values, the first applies when first creating a time stamp.
  2743. The second applies when changing it with the commands `S-up' and `S-down'.
  2744. When changing the time stamp, this means that it will change in steps
  2745. of N minutes, as given by the second value.
  2746. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2747. numbers should be factors of 60, so for example 5, 10, 15.
  2748. When this is larger than 1, you can still force an exact time stamp by using
  2749. a double prefix argument to a time stamp command like \
  2750. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2751. and by using a prefix arg to `S-up/down' to specify the exact number
  2752. of minutes to shift."
  2753. :group 'org-time
  2754. :get (lambda (var) ; Make sure both elements are there
  2755. (if (integerp (default-value var))
  2756. (list (default-value var) 5)
  2757. (default-value var)))
  2758. :type '(list
  2759. (integer :tag "when inserting times")
  2760. (integer :tag "when modifying times")))
  2761. ;; Normalize old customizations of this variable.
  2762. (when (integerp org-time-stamp-rounding-minutes)
  2763. (setq org-time-stamp-rounding-minutes
  2764. (list org-time-stamp-rounding-minutes
  2765. org-time-stamp-rounding-minutes)))
  2766. (defcustom org-display-custom-times nil
  2767. "Non-nil means overlay custom formats over all time stamps.
  2768. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2769. To turn this on on a per-file basis, insert anywhere in the file:
  2770. #+STARTUP: customtime"
  2771. :group 'org-time
  2772. :set 'set-default
  2773. :type 'sexp)
  2774. (make-variable-buffer-local 'org-display-custom-times)
  2775. (defcustom org-time-stamp-custom-formats
  2776. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2777. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2778. These are overlaid over the default ISO format if the variable
  2779. `org-display-custom-times' is set. Time like %H:%M should be at the
  2780. end of the second format. The custom formats are also honored by export
  2781. commands, if custom time display is turned on at the time of export."
  2782. :group 'org-time
  2783. :type 'sexp)
  2784. (defun org-time-stamp-format (&optional long inactive)
  2785. "Get the right format for a time string."
  2786. (let ((f (if long (cdr org-time-stamp-formats)
  2787. (car org-time-stamp-formats))))
  2788. (if inactive
  2789. (concat "[" (substring f 1 -1) "]")
  2790. f)))
  2791. (defcustom org-deadline-warning-days 14
  2792. "Number of days before expiration during which a deadline becomes active.
  2793. This variable governs the display in sparse trees and in the agenda.
  2794. When 0 or negative, it means use this number (the absolute value of it)
  2795. even if a deadline has a different individual lead time specified.
  2796. Custom commands can set this variable in the options section."
  2797. :group 'org-time
  2798. :group 'org-agenda-daily/weekly
  2799. :type 'integer)
  2800. (defcustom org-scheduled-delay-days 0
  2801. "Number of days before a scheduled item becomes active.
  2802. This variable governs the display in sparse trees and in the agenda.
  2803. The default value (i.e. 0) means: don't delay scheduled item.
  2804. When negative, it means use this number (the absolute value of it)
  2805. even if a scheduled item has a different individual delay time
  2806. specified.
  2807. Custom commands can set this variable in the options section."
  2808. :group 'org-time
  2809. :group 'org-agenda-daily/weekly
  2810. :version "24.4"
  2811. :package-version '(Org . "8.0")
  2812. :type 'integer)
  2813. (defcustom org-read-date-prefer-future t
  2814. "Non-nil means assume future for incomplete date input from user.
  2815. This affects the following situations:
  2816. 1. The user gives a month but not a year.
  2817. For example, if it is April and you enter \"feb 2\", this will be read
  2818. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2819. 2. The user gives a day, but no month.
  2820. For example, if today is the 15th, and you enter \"3\", Org will read
  2821. this as the third of *next* month. However, if you enter \"17\",
  2822. it will be considered as *this* month.
  2823. If you set this variable to the symbol `time', then also the following
  2824. will work:
  2825. 3. If the user gives a time.
  2826. If the time is before now, it will be interpreted as tomorrow.
  2827. Currently none of this works for ISO week specifications.
  2828. When this option is nil, the current day, month and year will always be
  2829. used as defaults.
  2830. See also `org-agenda-jump-prefer-future'."
  2831. :group 'org-time
  2832. :type '(choice
  2833. (const :tag "Never" nil)
  2834. (const :tag "Check month and day" t)
  2835. (const :tag "Check month, day, and time" time)))
  2836. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2837. "Should the agenda jump command prefer the future for incomplete dates?
  2838. The default is to do the same as configured in `org-read-date-prefer-future'.
  2839. But you can also set a deviating value here.
  2840. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2841. :group 'org-agenda
  2842. :group 'org-time
  2843. :version "24.1"
  2844. :type '(choice
  2845. (const :tag "Use org-read-date-prefer-future"
  2846. org-read-date-prefer-future)
  2847. (const :tag "Never" nil)
  2848. (const :tag "Always" t)))
  2849. (defcustom org-read-date-force-compatible-dates t
  2850. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2851. Depending on the system Emacs is running on, certain dates cannot
  2852. be represented with the type used internally to represent time.
  2853. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2854. correctly. Some systems allow for earlier dates, some for later,
  2855. some for both. One way to find out it to insert any date into an
  2856. Org buffer, putting the cursor on the year and hitting S-up and
  2857. S-down to test the range.
  2858. When this variable is set to t, the date/time prompt will not let
  2859. you specify dates outside the 1970-2037 range, so it is certain that
  2860. these dates will work in whatever version of Emacs you are
  2861. running, and also that you can move a file from one Emacs implementation
  2862. to another. WHenever Org is forcing the year for you, it will display
  2863. a message and beep.
  2864. When this variable is nil, Org will check if the date is
  2865. representable in the specific Emacs implementation you are using.
  2866. If not, it will force a year, usually the current year, and beep
  2867. to remind you. Currently this setting is not recommended because
  2868. the likelihood that you will open your Org files in an Emacs that
  2869. has limited date range is not negligible.
  2870. A workaround for this problem is to use diary sexp dates for time
  2871. stamps outside of this range."
  2872. :group 'org-time
  2873. :version "24.1"
  2874. :type 'boolean)
  2875. (defcustom org-read-date-display-live t
  2876. "Non-nil means display current interpretation of date prompt live.
  2877. This display will be in an overlay, in the minibuffer."
  2878. :group 'org-time
  2879. :type 'boolean)
  2880. (defcustom org-read-date-popup-calendar t
  2881. "Non-nil means pop up a calendar when prompting for a date.
  2882. In the calendar, the date can be selected with mouse-1. However, the
  2883. minibuffer will also be active, and you can simply enter the date as well.
  2884. When nil, only the minibuffer will be available."
  2885. :group 'org-time
  2886. :type 'boolean)
  2887. (defvaralias 'org-popup-calendar-for-date-prompt
  2888. 'org-read-date-popup-calendar)
  2889. (defcustom org-extend-today-until 0
  2890. "The hour when your day really ends. Must be an integer.
  2891. This has influence for the following applications:
  2892. - When switching the agenda to \"today\". It it is still earlier than
  2893. the time given here, the day recognized as TODAY is actually yesterday.
  2894. - When a date is read from the user and it is still before the time given
  2895. here, the current date and time will be assumed to be yesterday, 23:59.
  2896. Also, timestamps inserted in capture templates follow this rule.
  2897. IMPORTANT: This is a feature whose implementation is and likely will
  2898. remain incomplete. Really, it is only here because past midnight seems to
  2899. be the favorite working time of John Wiegley :-)"
  2900. :group 'org-time
  2901. :type 'integer)
  2902. (defcustom org-use-effective-time nil
  2903. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2904. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2905. \"effective time\" of any timestamps between midnight and 8am will be
  2906. 23:59 of the previous day."
  2907. :group 'org-time
  2908. :version "24.1"
  2909. :type 'boolean)
  2910. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2911. "When non-nil, use the last clock out time for `org-todo'.
  2912. Note that this option has precedence over the combined use of
  2913. `org-use-effective-time' and `org-extend-today-until'."
  2914. :group 'org-time
  2915. :version "24.4"
  2916. :package-version '(Org . "8.0")
  2917. :type 'boolean)
  2918. (defcustom org-edit-timestamp-down-means-later nil
  2919. "Non-nil means S-down will increase the time in a time stamp.
  2920. When nil, S-up will increase."
  2921. :group 'org-time
  2922. :type 'boolean)
  2923. (defcustom org-calendar-follow-timestamp-change t
  2924. "Non-nil means make the calendar window follow timestamp changes.
  2925. When a timestamp is modified and the calendar window is visible, it will be
  2926. moved to the new date."
  2927. :group 'org-time
  2928. :type 'boolean)
  2929. (defgroup org-tags nil
  2930. "Options concerning tags in Org mode."
  2931. :tag "Org Tags"
  2932. :group 'org)
  2933. (defcustom org-tag-alist nil
  2934. "Default tags available in Org files.
  2935. The value of this variable is an alist. Associations either:
  2936. (TAG)
  2937. (TAG . SELECT)
  2938. (SPECIAL)
  2939. where TAG is a tag as a string, SELECT is character, used to
  2940. select that tag through the fast tag selection interface, and
  2941. SPECIAL is one of the following keywords: `:startgroup',
  2942. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2943. `:newline'. These keywords are used to define a hierarchy of
  2944. tags. See manual for details.
  2945. When this variable is nil, Org mode bases tag input on what is
  2946. already in the buffer. The value can be overridden locally by
  2947. using a TAGS keyword, e.g.,
  2948. #+TAGS: tag1 tag2
  2949. See also `org-tag-persistent-alist' to sidestep this behavior."
  2950. :group 'org-tags
  2951. :type '(repeat
  2952. (choice
  2953. (cons :tag "Tag with key"
  2954. (string :tag "Tag name")
  2955. (character :tag "Access char"))
  2956. (list :tag "Tag" (string :tag "Tag name"))
  2957. (const :tag "Start radio group" (:startgroup))
  2958. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2959. (const :tag "Group tags delimiter" (:grouptags))
  2960. (const :tag "End radio group" (:endgroup))
  2961. (const :tag "End tag group, non distinct" (:endgrouptag))
  2962. (const :tag "New line" (:newline)))))
  2963. (defcustom org-tag-persistent-alist nil
  2964. "Tags always available in Org files.
  2965. The value of this variable is an alist. Associations either:
  2966. (TAG)
  2967. (TAG . SELECT)
  2968. (SPECIAL)
  2969. where TAG is a tag as a string, SELECT is a character, used to
  2970. select that tag through the fast tag selection interface, and
  2971. SPECIAL is one of the following keywords: `:startgroup',
  2972. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2973. `:newline'. These keywords are used to define a hierarchy of
  2974. tags. See manual for details.
  2975. Unlike to `org-tag-alist', tags defined in this variable do not
  2976. depend on a local TAGS keyword. Instead, to disable these tags
  2977. on a per-file basis, insert anywhere in the file:
  2978. #+STARTUP: noptag"
  2979. :group 'org-tags
  2980. :type '(repeat
  2981. (choice
  2982. (cons :tag "Tag with key"
  2983. (string :tag "Tag name")
  2984. (character :tag "Access char"))
  2985. (list :tag "Tag" (string :tag "Tag name"))
  2986. (const :tag "Start radio group" (:startgroup))
  2987. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2988. (const :tag "Group tags delimiter" (:grouptags))
  2989. (const :tag "End radio group" (:endgroup))
  2990. (const :tag "End tag group, non distinct" (:endgrouptag))
  2991. (const :tag "New line" (:newline)))))
  2992. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2993. "If non-nil, always offer completion for all tags of all agenda files.
  2994. Instead of customizing this variable directly, you might want to
  2995. set it locally for capture buffers, because there no list of
  2996. tags in that file can be created dynamically (there are none).
  2997. (add-hook \\='org-capture-mode-hook
  2998. (lambda ()
  2999. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  3000. :group 'org-tags
  3001. :version "24.1"
  3002. :type 'boolean)
  3003. (defvar org-file-tags nil
  3004. "List of tags that can be inherited by all entries in the file.
  3005. The tags will be inherited if the variable `org-use-tag-inheritance'
  3006. says they should be.
  3007. This variable is populated from #+FILETAGS lines.")
  3008. (defcustom org-use-fast-tag-selection 'auto
  3009. "Non-nil means use fast tag selection scheme.
  3010. This is a special interface to select and deselect tags with single keys.
  3011. When nil, fast selection is never used.
  3012. When the symbol `auto', fast selection is used if and only if selection
  3013. characters for tags have been configured, either through the variable
  3014. `org-tag-alist' or through a #+TAGS line in the buffer.
  3015. When t, fast selection is always used and selection keys are assigned
  3016. automatically if necessary."
  3017. :group 'org-tags
  3018. :type '(choice
  3019. (const :tag "Always" t)
  3020. (const :tag "Never" nil)
  3021. (const :tag "When selection characters are configured" auto)))
  3022. (defcustom org-fast-tag-selection-single-key nil
  3023. "Non-nil means fast tag selection exits after first change.
  3024. When nil, you have to press RET to exit it.
  3025. During fast tag selection, you can toggle this flag with `C-c'.
  3026. This variable can also have the value `expert'. In this case, the window
  3027. displaying the tags menu is not even shown, until you press C-c again."
  3028. :group 'org-tags
  3029. :type '(choice
  3030. (const :tag "No" nil)
  3031. (const :tag "Yes" t)
  3032. (const :tag "Expert" expert)))
  3033. (defvar org-fast-tag-selection-include-todo nil
  3034. "Non-nil means fast tags selection interface will also offer TODO states.
  3035. This is an undocumented feature, you should not rely on it.")
  3036. (defcustom org-tags-column -77
  3037. "The column to which tags should be indented in a headline.
  3038. If this number is positive, it specifies the column. If it is negative,
  3039. it means that the tags should be flushright to that column. For example,
  3040. -80 works well for a normal 80 character screen.
  3041. When 0, place tags directly after headline text, with only one space in
  3042. between."
  3043. :group 'org-tags
  3044. :type 'integer)
  3045. (defcustom org-auto-align-tags t
  3046. "Non-nil keeps tags aligned when modifying headlines.
  3047. Some operations (i.e. demoting) change the length of a headline and
  3048. therefore shift the tags around. With this option turned on, after
  3049. each such operation the tags are again aligned to `org-tags-column'."
  3050. :group 'org-tags
  3051. :type 'boolean)
  3052. (defcustom org-use-tag-inheritance t
  3053. "Non-nil means tags in levels apply also for sublevels.
  3054. When nil, only the tags directly given in a specific line apply there.
  3055. This may also be a list of tags that should be inherited, or a regexp that
  3056. matches tags that should be inherited. Additional control is possible
  3057. with the variable `org-tags-exclude-from-inheritance' which gives an
  3058. explicit list of tags to be excluded from inheritance, even if the value of
  3059. `org-use-tag-inheritance' would select it for inheritance.
  3060. If this option is t, a match early-on in a tree can lead to a large
  3061. number of matches in the subtree when constructing the agenda or creating
  3062. a sparse tree. If you only want to see the first match in a tree during
  3063. a search, check out the variable `org-tags-match-list-sublevels'."
  3064. :group 'org-tags
  3065. :type '(choice
  3066. (const :tag "Not" nil)
  3067. (const :tag "Always" t)
  3068. (repeat :tag "Specific tags" (string :tag "Tag"))
  3069. (regexp :tag "Tags matched by regexp")))
  3070. (defcustom org-tags-exclude-from-inheritance nil
  3071. "List of tags that should never be inherited.
  3072. This is a way to exclude a few tags from inheritance. For way to do
  3073. the opposite, to actively allow inheritance for selected tags,
  3074. see the variable `org-use-tag-inheritance'."
  3075. :group 'org-tags
  3076. :type '(repeat (string :tag "Tag")))
  3077. (defun org-tag-inherit-p (tag)
  3078. "Check if TAG is one that should be inherited."
  3079. (cond
  3080. ((member tag org-tags-exclude-from-inheritance) nil)
  3081. ((eq org-use-tag-inheritance t) t)
  3082. ((not org-use-tag-inheritance) nil)
  3083. ((stringp org-use-tag-inheritance)
  3084. (string-match org-use-tag-inheritance tag))
  3085. ((listp org-use-tag-inheritance)
  3086. (member tag org-use-tag-inheritance))
  3087. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3088. (defcustom org-tags-match-list-sublevels t
  3089. "Non-nil means list also sublevels of headlines matching a search.
  3090. This variable applies to tags/property searches, and also to stuck
  3091. projects because this search is based on a tags match as well.
  3092. When set to the symbol `indented', sublevels are indented with
  3093. leading dots.
  3094. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3095. the sublevels of a headline matching a tag search often also match
  3096. the same search. Listing all of them can create very long lists.
  3097. Setting this variable to nil causes subtrees of a match to be skipped.
  3098. This variable is semi-obsolete and probably should always be true. It
  3099. is better to limit inheritance to certain tags using the variables
  3100. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3101. :group 'org-tags
  3102. :type '(choice
  3103. (const :tag "No, don't list them" nil)
  3104. (const :tag "Yes, do list them" t)
  3105. (const :tag "List them, indented with leading dots" indented)))
  3106. (defcustom org-tags-sort-function nil
  3107. "When set, tags are sorted using this function as a comparator."
  3108. :group 'org-tags
  3109. :type '(choice
  3110. (const :tag "No sorting" nil)
  3111. (const :tag "Alphabetical" org-string-collate-lessp)
  3112. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  3113. (function :tag "Custom function" nil)))
  3114. (defvar org-tags-history nil
  3115. "History of minibuffer reads for tags.")
  3116. (defvar org-last-tags-completion-table nil
  3117. "The last used completion table for tags.")
  3118. (defvar org-after-tags-change-hook nil
  3119. "Hook that is run after the tags in a line have changed.")
  3120. (defgroup org-properties nil
  3121. "Options concerning properties in Org mode."
  3122. :tag "Org Properties"
  3123. :group 'org)
  3124. (defcustom org-property-format "%-10s %s"
  3125. "How property key/value pairs should be formatted by `indent-line'.
  3126. When `indent-line' hits a property definition, it will format the line
  3127. according to this format, mainly to make sure that the values are
  3128. lined-up with respect to each other."
  3129. :group 'org-properties
  3130. :type 'string)
  3131. (defcustom org-properties-postprocess-alist nil
  3132. "Alist of properties and functions to adjust inserted values.
  3133. Elements of this alist must be of the form
  3134. ([string] [function])
  3135. where [string] must be a property name and [function] must be a
  3136. lambda expression: this lambda expression must take one argument,
  3137. the value to adjust, and return the new value as a string.
  3138. For example, this element will allow the property \"Remaining\"
  3139. to be updated wrt the relation between the \"Effort\" property
  3140. and the clock summary:
  3141. ((\"Remaining\" (lambda(value)
  3142. (let ((clocksum (org-clock-sum-current-item))
  3143. (effort (org-duration-to-minutes
  3144. (org-entry-get (point) \"Effort\"))))
  3145. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3146. :group 'org-properties
  3147. :version "24.1"
  3148. :type '(alist :key-type (string :tag "Property")
  3149. :value-type (function :tag "Function")))
  3150. (defcustom org-use-property-inheritance nil
  3151. "Non-nil means properties apply also for sublevels.
  3152. This setting is chiefly used during property searches. Turning it on can
  3153. cause significant overhead when doing a search, which is why it is not
  3154. on by default.
  3155. When nil, only the properties directly given in the current entry count.
  3156. When t, every property is inherited. The value may also be a list of
  3157. properties that should have inheritance, or a regular expression matching
  3158. properties that should be inherited.
  3159. However, note that some special properties use inheritance under special
  3160. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3161. and the properties ending in \"_ALL\" when they are used as descriptor
  3162. for valid values of a property.
  3163. Note for programmers:
  3164. When querying an entry with `org-entry-get', you can control if inheritance
  3165. should be used. By default, `org-entry-get' looks only at the local
  3166. properties. You can request inheritance by setting the inherit argument
  3167. to t (to force inheritance) or to `selective' (to respect the setting
  3168. in this variable)."
  3169. :group 'org-properties
  3170. :type '(choice
  3171. (const :tag "Not" nil)
  3172. (const :tag "Always" t)
  3173. (repeat :tag "Specific properties" (string :tag "Property"))
  3174. (regexp :tag "Properties matched by regexp")))
  3175. (defun org-property-inherit-p (property)
  3176. "Return a non-nil value if PROPERTY should be inherited."
  3177. (cond
  3178. ((eq org-use-property-inheritance t) t)
  3179. ((not org-use-property-inheritance) nil)
  3180. ((stringp org-use-property-inheritance)
  3181. (string-match org-use-property-inheritance property))
  3182. ((listp org-use-property-inheritance)
  3183. (member-ignore-case property org-use-property-inheritance))
  3184. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3185. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3186. "The default column format, if no other format has been defined.
  3187. This variable can be set on the per-file basis by inserting a line
  3188. #+COLUMNS: %25ITEM ....."
  3189. :group 'org-properties
  3190. :type 'string)
  3191. (defcustom org-columns-ellipses ".."
  3192. "The ellipses to be used when a field in column view is truncated.
  3193. When this is the empty string, as many characters as possible are shown,
  3194. but then there will be no visual indication that the field has been truncated.
  3195. When this is a string of length N, the last N characters of a truncated
  3196. field are replaced by this string. If the column is narrower than the
  3197. ellipses string, only part of the ellipses string will be shown."
  3198. :group 'org-properties
  3199. :type 'string)
  3200. (defconst org-global-properties-fixed
  3201. '(("VISIBILITY_ALL" . "folded children content all")
  3202. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3203. "List of property/value pairs that can be inherited by any entry.
  3204. These are fixed values, for the preset properties. The user variable
  3205. that can be used to add to this list is `org-global-properties'.
  3206. The entries in this list are cons cells where the car is a property
  3207. name and cdr is a string with the value. If the value represents
  3208. multiple items like an \"_ALL\" property, separate the items by
  3209. spaces.")
  3210. (defcustom org-global-properties nil
  3211. "List of property/value pairs that can be inherited by any entry.
  3212. This list will be combined with the constant `org-global-properties-fixed'.
  3213. The entries in this list are cons cells where the car is a property
  3214. name and cdr is a string with the value.
  3215. You can set buffer-local values for the same purpose in the variable
  3216. `org-file-properties' this by adding lines like
  3217. #+PROPERTY: NAME VALUE"
  3218. :group 'org-properties
  3219. :type '(repeat
  3220. (cons (string :tag "Property")
  3221. (string :tag "Value"))))
  3222. (defvar-local org-file-properties nil
  3223. "List of property/value pairs that can be inherited by any entry.
  3224. Valid for the current buffer.
  3225. This variable is populated from #+PROPERTY lines.")
  3226. (defgroup org-agenda nil
  3227. "Options concerning agenda views in Org mode."
  3228. :tag "Org Agenda"
  3229. :group 'org)
  3230. (defvar-local org-category nil
  3231. "Variable used by Org files to set a category for agenda display.
  3232. Such files should use a file variable to set it, for example
  3233. # -*- mode: org; org-category: \"ELisp\"
  3234. or contain a special line
  3235. #+CATEGORY: ELisp
  3236. If the file does not specify a category, then file's base name
  3237. is used instead.")
  3238. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3239. (defcustom org-agenda-files nil
  3240. "The files to be used for agenda display.
  3241. If an entry is a directory, all files in that directory that are matched
  3242. by `org-agenda-file-regexp' will be part of the file list.
  3243. If the value of the variable is not a list but a single file name, then
  3244. the list of agenda files is actually stored and maintained in that file,
  3245. one agenda file per line. In this file paths can be given relative to
  3246. `org-directory'. Tilde expansion and environment variable substitution
  3247. are also made.
  3248. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3249. and removed with `\\[org-remove-file]'."
  3250. :group 'org-agenda
  3251. :type '(choice
  3252. (repeat :tag "List of files and directories" file)
  3253. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3254. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3255. "Regular expression to match files for `org-agenda-files'.
  3256. If any element in the list in that variable contains a directory instead
  3257. of a normal file, all files in that directory that are matched by this
  3258. regular expression will be included."
  3259. :group 'org-agenda
  3260. :type 'regexp)
  3261. (defcustom org-agenda-text-search-extra-files nil
  3262. "List of extra files to be searched by text search commands.
  3263. These files will be searched in addition to the agenda files by the
  3264. commands `org-search-view' (`\\[org-agenda] s') \
  3265. and `org-occur-in-agenda-files'.
  3266. Note that these files will only be searched for text search commands,
  3267. not for the other agenda views like todo lists, tag searches or the weekly
  3268. agenda. This variable is intended to list notes and possibly archive files
  3269. that should also be searched by these two commands.
  3270. In fact, if the first element in the list is the symbol `agenda-archives',
  3271. then all archive files of all agenda files will be added to the search
  3272. scope."
  3273. :group 'org-agenda
  3274. :type '(set :greedy t
  3275. (const :tag "Agenda Archives" agenda-archives)
  3276. (repeat :inline t (file))))
  3277. (defvaralias 'org-agenda-multi-occur-extra-files
  3278. 'org-agenda-text-search-extra-files)
  3279. (defcustom org-agenda-skip-unavailable-files nil
  3280. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3281. A nil value means to remove them, after a query, from the list."
  3282. :group 'org-agenda
  3283. :type 'boolean)
  3284. (defcustom org-agenda-diary-file 'diary-file
  3285. "File to which to add new entries with the `i' key in agenda and calendar.
  3286. When this is the symbol `diary-file', the functionality in the Emacs
  3287. calendar will be used to add entries to the `diary-file'. But when this
  3288. points to a file, `org-agenda-diary-entry' will be used instead."
  3289. :group 'org-agenda
  3290. :type '(choice
  3291. (const :tag "The standard Emacs diary file" diary-file)
  3292. (file :tag "Special Org file diary entries")))
  3293. (defgroup org-latex nil
  3294. "Options for embedding LaTeX code into Org mode."
  3295. :tag "Org LaTeX"
  3296. :group 'org)
  3297. (defcustom org-format-latex-options
  3298. '(:foreground default :background default :scale 1.0
  3299. :html-foreground "Black" :html-background "Transparent"
  3300. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3301. "Options for creating images from LaTeX fragments.
  3302. This is a property list with the following properties:
  3303. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3304. `default' means use the foreground of the default face.
  3305. `auto' means use the foreground from the text face.
  3306. :background the background color, or \"Transparent\".
  3307. `default' means use the background of the default face.
  3308. `auto' means use the background from the text face.
  3309. :scale a scaling factor for the size of the images, to get more pixels
  3310. :html-foreground, :html-background, :html-scale
  3311. the same numbers for HTML export.
  3312. :matchers a list indicating which matchers should be used to
  3313. find LaTeX fragments. Valid members of this list are:
  3314. \"begin\" find environments
  3315. \"$1\" find single characters surrounded by $.$
  3316. \"$\" find math expressions surrounded by $...$
  3317. \"$$\" find math expressions surrounded by $$....$$
  3318. \"\\(\" find math expressions surrounded by \\(...\\)
  3319. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3320. :group 'org-latex
  3321. :type 'plist)
  3322. (defcustom org-format-latex-signal-error t
  3323. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3324. When nil, just push out a message."
  3325. :group 'org-latex
  3326. :version "24.1"
  3327. :type 'boolean)
  3328. (defcustom org-latex-to-mathml-jar-file nil
  3329. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3330. Use this to specify additional executable file say a jar file.
  3331. When using MathToWeb as the converter, specify the full-path to
  3332. your mathtoweb.jar file."
  3333. :group 'org-latex
  3334. :version "24.1"
  3335. :type '(choice
  3336. (const :tag "None" nil)
  3337. (file :tag "JAR file" :must-match t)))
  3338. (defcustom org-latex-to-mathml-convert-command nil
  3339. "Command to convert LaTeX fragments to MathML.
  3340. Replace format-specifiers in the command as noted below and use
  3341. `shell-command' to convert LaTeX to MathML.
  3342. %j: Executable file in fully expanded form as specified by
  3343. `org-latex-to-mathml-jar-file'.
  3344. %I: Input LaTeX file in fully expanded form.
  3345. %i: The latex fragment to be converted.
  3346. %o: Output MathML file.
  3347. This command is used by `org-create-math-formula'.
  3348. When using MathToWeb as the converter, set this option to
  3349. \"java -jar %j -unicode -force -df %o %I\".
  3350. When using LaTeXML set this option to
  3351. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3352. :group 'org-latex
  3353. :version "24.1"
  3354. :type '(choice
  3355. (const :tag "None" nil)
  3356. (string :tag "\nShell command")))
  3357. (defcustom org-preview-latex-default-process 'dvipng
  3358. "The default process to convert LaTeX fragments to image files.
  3359. All available processes and theirs documents can be found in
  3360. `org-preview-latex-process-alist', which see."
  3361. :group 'org-latex
  3362. :version "26.1"
  3363. :package-version '(Org . "9.0")
  3364. :type 'symbol)
  3365. (defcustom org-preview-latex-process-alist
  3366. '((dvipng
  3367. :programs ("latex" "dvipng")
  3368. :description "dvi > png"
  3369. :message "you need to install the programs: latex and dvipng."
  3370. :image-input-type "dvi"
  3371. :image-output-type "png"
  3372. :image-size-adjust (1.0 . 1.0)
  3373. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3374. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3375. (dvisvgm
  3376. :programs ("latex" "dvisvgm")
  3377. :description "dvi > svg"
  3378. :message "you need to install the programs: latex and dvisvgm."
  3379. :use-xcolor t
  3380. :image-input-type "dvi"
  3381. :image-output-type "svg"
  3382. :image-size-adjust (1.7 . 1.5)
  3383. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3384. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3385. (imagemagick
  3386. :programs ("latex" "convert")
  3387. :description "pdf > png"
  3388. :message "you need to install the programs: latex and imagemagick."
  3389. :use-xcolor t
  3390. :image-input-type "pdf"
  3391. :image-output-type "png"
  3392. :image-size-adjust (1.0 . 1.0)
  3393. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3394. :image-converter
  3395. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3396. "Definitions of external processes for LaTeX previewing.
  3397. Org mode can use some external commands to generate TeX snippet's images for
  3398. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3399. `org-create-formula-image' how to call them.
  3400. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3401. PROPERTIES accepts the following attributes:
  3402. :programs list of strings, required programs.
  3403. :description string, describe the process.
  3404. :message string, message it when required programs cannot be found.
  3405. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3406. :image-output-type string, output file type of image converter (e.g., \"png\").
  3407. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3408. deal with background and foreground color of image.
  3409. Otherwise, dvipng style background and foreground color
  3410. format are generated. You may then refer to them in
  3411. command options with \"%F\" and \"%B\".
  3412. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3413. image size showed in buffer and the cdr element is for
  3414. HTML file. This option is only useful for process
  3415. developers, users should use variable
  3416. `org-format-latex-options' instead.
  3417. :post-clean list of strings, files matched are to be cleaned up once
  3418. the image is generated. When nil, the files with \".dvi\",
  3419. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3420. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3421. be cleaned up.
  3422. :latex-header list of strings, the LaTeX header of the snippet file.
  3423. When nil, the fallback value is used instead, which is
  3424. controlled by `org-format-latex-header',
  3425. `org-latex-default-packages-alist' and
  3426. `org-latex-packages-alist', which see.
  3427. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3428. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3429. replaced with values defined below.
  3430. :image-converter list of image converter commands strings. Each of them is
  3431. given to the shell and supports any of the following
  3432. place-holders defined below.
  3433. Place-holders used by `:image-converter' and `:latex-compiler':
  3434. %f input file name
  3435. %b base name of input file
  3436. %o base directory of input file
  3437. %O absolute output file name
  3438. Place-holders only used by `:image-converter':
  3439. %F foreground of image
  3440. %B background of image
  3441. %D dpi, which is used to adjust image size by some processing commands.
  3442. %S the image size scale ratio, which is used to adjust image size by some
  3443. processing commands."
  3444. :group 'org-latex
  3445. :version "26.1"
  3446. :package-version '(Org . "9.0")
  3447. :type '(alist :tag "LaTeX to image backends"
  3448. :value-type (plist)))
  3449. (defcustom org-preview-latex-image-directory "ltximg/"
  3450. "Path to store latex preview images.
  3451. A relative path here creates many directories relative to the
  3452. processed Org files paths. An absolute path puts all preview
  3453. images at the same place."
  3454. :group 'org-latex
  3455. :version "26.1"
  3456. :package-version '(Org . "9.0")
  3457. :type 'string)
  3458. (defun org-format-latex-mathml-available-p ()
  3459. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3460. (save-match-data
  3461. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3462. org-latex-to-mathml-convert-command)
  3463. (let ((executable (car (split-string
  3464. org-latex-to-mathml-convert-command))))
  3465. (when (executable-find executable)
  3466. (if (string-match
  3467. "%j" org-latex-to-mathml-convert-command)
  3468. (file-readable-p org-latex-to-mathml-jar-file)
  3469. t))))))
  3470. (defcustom org-format-latex-header "\\documentclass{article}
  3471. \\usepackage[usenames]{color}
  3472. \[PACKAGES]
  3473. \[DEFAULT-PACKAGES]
  3474. \\pagestyle{empty} % do not remove
  3475. % The settings below are copied from fullpage.sty
  3476. \\setlength{\\textwidth}{\\paperwidth}
  3477. \\addtolength{\\textwidth}{-3cm}
  3478. \\setlength{\\oddsidemargin}{1.5cm}
  3479. \\addtolength{\\oddsidemargin}{-2.54cm}
  3480. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3481. \\setlength{\\textheight}{\\paperheight}
  3482. \\addtolength{\\textheight}{-\\headheight}
  3483. \\addtolength{\\textheight}{-\\headsep}
  3484. \\addtolength{\\textheight}{-\\footskip}
  3485. \\addtolength{\\textheight}{-3cm}
  3486. \\setlength{\\topmargin}{1.5cm}
  3487. \\addtolength{\\topmargin}{-2.54cm}"
  3488. "The document header used for processing LaTeX fragments.
  3489. It is imperative that this header make sure that no page number
  3490. appears on the page. The package defined in the variables
  3491. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3492. will either replace the placeholder \"[PACKAGES]\" in this
  3493. header, or they will be appended."
  3494. :group 'org-latex
  3495. :type 'string)
  3496. (defun org-set-packages-alist (var val)
  3497. "Set the packages alist and make sure it has 3 elements per entry."
  3498. (set var (mapcar (lambda (x)
  3499. (if (and (consp x) (= (length x) 2))
  3500. (list (car x) (nth 1 x) t)
  3501. x))
  3502. val)))
  3503. (defun org-get-packages-alist (var)
  3504. "Get the packages alist and make sure it has 3 elements per entry."
  3505. (mapcar (lambda (x)
  3506. (if (and (consp x) (= (length x) 2))
  3507. (list (car x) (nth 1 x) t)
  3508. x))
  3509. (default-value var)))
  3510. (defcustom org-latex-default-packages-alist
  3511. '(("AUTO" "inputenc" t ("pdflatex"))
  3512. ("T1" "fontenc" t ("pdflatex"))
  3513. ("" "graphicx" t)
  3514. ("" "grffile" t)
  3515. ("" "longtable" nil)
  3516. ("" "wrapfig" nil)
  3517. ("" "rotating" nil)
  3518. ("normalem" "ulem" t)
  3519. ("" "amsmath" t)
  3520. ("" "textcomp" t)
  3521. ("" "amssymb" t)
  3522. ("" "capt-of" nil)
  3523. ("" "hyperref" nil))
  3524. "Alist of default packages to be inserted in the header.
  3525. Change this only if one of the packages here causes an
  3526. incompatibility with another package you are using.
  3527. The packages in this list are needed by one part or another of
  3528. Org mode to function properly:
  3529. - inputenc, fontenc: for basic font and character selection
  3530. - graphicx: for including images
  3531. - grffile: allow periods and spaces in graphics file names
  3532. - longtable: For multipage tables
  3533. - wrapfig: for figure placement
  3534. - rotating: for sideways figures and tables
  3535. - ulem: for underline and strike-through
  3536. - amsmath: for subscript and superscript and math environments
  3537. - textcomp, amssymb: for various symbols used
  3538. for interpreting the entities in `org-entities'. You can skip
  3539. some of these packages if you don't use any of their symbols.
  3540. - capt-of: for captions outside of floats
  3541. - hyperref: for cross references
  3542. Therefore you should not modify this variable unless you know
  3543. what you are doing. The one reason to change it anyway is that
  3544. you might be loading some other package that conflicts with one
  3545. of the default packages. Each element is either a cell or
  3546. a string.
  3547. A cell is of the format
  3548. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3549. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3550. when compiling LaTeX snippets into images for inclusion into
  3551. non-LaTeX output. COMPILERS is a list of compilers that should
  3552. include the package, see `org-latex-compiler'. If the document
  3553. compiler is not in the list, and the list is non-nil, the package
  3554. will not be inserted in the final document.
  3555. A string will be inserted as-is in the header of the document."
  3556. :group 'org-latex
  3557. :group 'org-export-latex
  3558. :set 'org-set-packages-alist
  3559. :get 'org-get-packages-alist
  3560. :version "26.1"
  3561. :package-version '(Org . "8.3")
  3562. :type '(repeat
  3563. (choice
  3564. (list :tag "options/package pair"
  3565. (string :tag "options")
  3566. (string :tag "package")
  3567. (boolean :tag "Snippet")
  3568. (choice
  3569. (const :tag "For all compilers" nil)
  3570. (repeat :tag "Allowed compiler" string)))
  3571. (string :tag "A line of LaTeX"))))
  3572. (defcustom org-latex-packages-alist nil
  3573. "Alist of packages to be inserted in every LaTeX header.
  3574. These will be inserted after `org-latex-default-packages-alist'.
  3575. Each element is either a cell or a string.
  3576. A cell is of the format:
  3577. (\"options\" \"package\" SNIPPET-FLAG)
  3578. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3579. needed when turning LaTeX snippets into images for inclusion into
  3580. non-LaTeX output.
  3581. A string will be inserted as-is in the header of the document.
  3582. Make sure that you only list packages here which:
  3583. - you want in every file;
  3584. - do not conflict with the setup in `org-format-latex-header';
  3585. - do not conflict with the default packages in
  3586. `org-latex-default-packages-alist'."
  3587. :group 'org-latex
  3588. :group 'org-export-latex
  3589. :set 'org-set-packages-alist
  3590. :get 'org-get-packages-alist
  3591. :type '(repeat
  3592. (choice
  3593. (list :tag "options/package pair"
  3594. (string :tag "options")
  3595. (string :tag "package")
  3596. (boolean :tag "Snippet"))
  3597. (string :tag "A line of LaTeX"))))
  3598. (defgroup org-appearance nil
  3599. "Settings for Org mode appearance."
  3600. :tag "Org Appearance"
  3601. :group 'org)
  3602. (defcustom org-level-color-stars-only nil
  3603. "Non-nil means fontify only the stars in each headline.
  3604. When nil, the entire headline is fontified.
  3605. Changing it requires restart of `font-lock-mode' to become effective
  3606. also in regions already fontified."
  3607. :group 'org-appearance
  3608. :type 'boolean)
  3609. (defcustom org-hide-leading-stars nil
  3610. "Non-nil means hide the first N-1 stars in a headline.
  3611. This works by using the face `org-hide' for these stars. This
  3612. face is white for a light background, and black for a dark
  3613. background. You may have to customize the face `org-hide' to
  3614. make this work.
  3615. Changing it requires restart of `font-lock-mode' to become effective
  3616. also in regions already fontified.
  3617. You may also set this on a per-file basis by adding one of the following
  3618. lines to the buffer:
  3619. #+STARTUP: hidestars
  3620. #+STARTUP: showstars"
  3621. :group 'org-appearance
  3622. :type 'boolean)
  3623. (defcustom org-hidden-keywords nil
  3624. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3625. For example, a value \\='(title) for this list makes the document's title
  3626. appear in the buffer without the initial \"#+TITLE:\" part."
  3627. :group 'org-appearance
  3628. :version "24.1"
  3629. :type '(set (const :tag "#+AUTHOR" author)
  3630. (const :tag "#+DATE" date)
  3631. (const :tag "#+EMAIL" email)
  3632. (const :tag "#+TITLE" title)))
  3633. (defcustom org-custom-properties nil
  3634. "List of properties (as strings) with a special meaning.
  3635. The default use of these custom properties is to let the user
  3636. hide them with `org-toggle-custom-properties-visibility'."
  3637. :group 'org-properties
  3638. :group 'org-appearance
  3639. :version "24.3"
  3640. :type '(repeat (string :tag "Property Name")))
  3641. (defcustom org-fontify-done-headline nil
  3642. "Non-nil means change the face of a headline if it is marked DONE.
  3643. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3644. When this is non-nil, the headline after the keyword is set to the
  3645. `org-headline-done' as an additional indication."
  3646. :group 'org-appearance
  3647. :type 'boolean)
  3648. (defcustom org-fontify-emphasized-text t
  3649. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3650. Changing this variable requires a restart of Emacs to take effect."
  3651. :group 'org-appearance
  3652. :type 'boolean)
  3653. (defcustom org-fontify-whole-heading-line nil
  3654. "Non-nil means fontify the whole line for headings.
  3655. This is useful when setting a background color for the
  3656. org-level-* faces."
  3657. :group 'org-appearance
  3658. :type 'boolean)
  3659. (defcustom org-highlight-latex-and-related nil
  3660. "Non-nil means highlight LaTeX related syntax in the buffer.
  3661. When non nil, the value should be a list containing any of the
  3662. following symbols:
  3663. `latex' Highlight LaTeX snippets and environments.
  3664. `script' Highlight subscript and superscript.
  3665. `entities' Highlight entities."
  3666. :group 'org-appearance
  3667. :version "24.4"
  3668. :package-version '(Org . "8.0")
  3669. :type '(choice
  3670. (const :tag "No highlighting" nil)
  3671. (set :greedy t :tag "Highlight"
  3672. (const :tag "LaTeX snippets and environments" latex)
  3673. (const :tag "Subscript and superscript" script)
  3674. (const :tag "Entities" entities))))
  3675. (defcustom org-hide-emphasis-markers nil
  3676. "Non-nil mean font-lock should hide the emphasis marker characters."
  3677. :group 'org-appearance
  3678. :type 'boolean
  3679. :safe #'booleanp)
  3680. (defcustom org-hide-macro-markers nil
  3681. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3682. :group 'org-appearance
  3683. :type 'boolean)
  3684. (defcustom org-pretty-entities nil
  3685. "Non-nil means show entities as UTF8 characters.
  3686. When nil, the \\name form remains in the buffer."
  3687. :group 'org-appearance
  3688. :version "24.1"
  3689. :type 'boolean)
  3690. (defcustom org-pretty-entities-include-sub-superscripts t
  3691. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3692. :group 'org-appearance
  3693. :version "24.1"
  3694. :type 'boolean)
  3695. (defvar org-emph-re nil
  3696. "Regular expression for matching emphasis.
  3697. After a match, the match groups contain these elements:
  3698. 0 The match of the full regular expression, including the characters
  3699. before and after the proper match
  3700. 1 The character before the proper match, or empty at beginning of line
  3701. 2 The proper match, including the leading and trailing markers
  3702. 3 The leading marker like * or /, indicating the type of highlighting
  3703. 4 The text between the emphasis markers, not including the markers
  3704. 5 The character after the match, empty at the end of a line")
  3705. (defvar org-verbatim-re nil
  3706. "Regular expression for matching verbatim text.")
  3707. (defvar org-emphasis-regexp-components) ; defined just below
  3708. (defvar org-emphasis-alist) ; defined just below
  3709. (defun org-set-emph-re (var val)
  3710. "Set variable and compute the emphasis regular expression."
  3711. (set var val)
  3712. (when (and (boundp 'org-emphasis-alist)
  3713. (boundp 'org-emphasis-regexp-components)
  3714. org-emphasis-alist org-emphasis-regexp-components)
  3715. (pcase-let*
  3716. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3717. (body (if (<= nl 0) body
  3718. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3719. (template
  3720. (format (concat "\\([%s]\\|^\\)" ;before markers
  3721. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3722. "\\([%s]\\|$\\)") ;after markers
  3723. pre border border body border post)))
  3724. (setq org-emph-re (format template "*/_+"))
  3725. (setq org-verbatim-re (format template "=~")))))
  3726. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3727. ;; set this option proved cumbersome. See this message/thread:
  3728. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3729. (defvar org-emphasis-regexp-components
  3730. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3731. "Components used to build the regular expression for emphasis.
  3732. This is a list with five entries. Terminology: In an emphasis string
  3733. like \" *strong word* \", we call the initial space PREMATCH, the final
  3734. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3735. and \"trong wor\" is the body. The different components in this variable
  3736. specify what is allowed/forbidden in each part:
  3737. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3738. post Chars allowed as postmatch. End of line will be allowed too.
  3739. border The chars *forbidden* as border characters.
  3740. body-regexp A regexp like \".\" to match a body character. Don't use
  3741. non-shy groups here, and don't allow newline here.
  3742. newline The maximum number of newlines allowed in an emphasis exp.
  3743. You need to reload Org or to restart Emacs after setting this.")
  3744. (defcustom org-emphasis-alist
  3745. '(("*" bold)
  3746. ("/" italic)
  3747. ("_" underline)
  3748. ("=" org-verbatim verbatim)
  3749. ("~" org-code verbatim)
  3750. ("+" (:strike-through t)))
  3751. "Alist of characters and faces to emphasize text.
  3752. Text starting and ending with a special character will be emphasized,
  3753. for example *bold*, _underlined_ and /italic/. This variable sets the
  3754. marker characters and the face to be used by font-lock for highlighting
  3755. in Org buffers.
  3756. You need to reload Org or to restart Emacs after customizing this."
  3757. :group 'org-appearance
  3758. :set 'org-set-emph-re
  3759. :version "24.4"
  3760. :package-version '(Org . "8.0")
  3761. :type '(repeat
  3762. (list
  3763. (string :tag "Marker character")
  3764. (choice
  3765. (face :tag "Font-lock-face")
  3766. (plist :tag "Face property list"))
  3767. (option (const verbatim)))))
  3768. (defvar org-protecting-blocks '("src" "example" "export")
  3769. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3770. This is needed for font-lock setup.")
  3771. ;;; Functions and variables from their packages
  3772. ;; Declared here to avoid compiler warnings
  3773. (defvar mark-active)
  3774. ;; Various packages
  3775. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3776. (declare-function calendar-forward-day "cal-move" (arg))
  3777. (declare-function calendar-goto-date "cal-move" (date))
  3778. (declare-function calendar-goto-today "cal-move" ())
  3779. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3780. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3781. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3782. (declare-function cdlatex-tab "ext:cdlatex" ())
  3783. (declare-function dired-get-filename
  3784. "dired"
  3785. (&optional localp no-error-if-not-filep))
  3786. (declare-function iswitchb-read-buffer
  3787. "iswitchb"
  3788. (prompt &optional
  3789. default require-match _predicate start matches-set))
  3790. (declare-function org-agenda-change-all-lines
  3791. "org-agenda"
  3792. (newhead hdmarker &optional fixface just-this))
  3793. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3794. "org-agenda"
  3795. (&optional end))
  3796. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3797. (declare-function org-agenda-format-item
  3798. "org-agenda"
  3799. (extra txt &optional level category tags dotime
  3800. remove-re habitp))
  3801. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3802. (declare-function org-agenda-save-markers-for-cut-and-paste
  3803. "org-agenda"
  3804. (beg end))
  3805. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3806. (declare-function org-agenda-skip "org-agenda" ())
  3807. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3808. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3809. (declare-function org-indent-mode "org-indent" (&optional arg))
  3810. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3811. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3812. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3813. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3814. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3815. (declare-function parse-time-string "parse-time" (string))
  3816. (defvar align-mode-rules-list)
  3817. (defvar calc-embedded-close-formula)
  3818. (defvar calc-embedded-open-formula)
  3819. (defvar calc-embedded-open-mode)
  3820. (defvar font-lock-unfontify-region-function)
  3821. (defvar iswitchb-temp-buflist)
  3822. (defvar org-agenda-tags-todo-honor-ignore-options)
  3823. (defvar remember-data-file)
  3824. (defvar texmathp-why)
  3825. ;;;###autoload
  3826. (defun turn-on-orgtbl ()
  3827. "Unconditionally turn on `orgtbl-mode'."
  3828. (require 'org-table)
  3829. (orgtbl-mode 1))
  3830. (defun org-at-table-p (&optional table-type)
  3831. "Non-nil if the cursor is inside an Org table.
  3832. If TABLE-TYPE is non-nil, also check for table.el-type tables."
  3833. (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
  3834. (or (not (derived-mode-p 'org-mode))
  3835. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3836. (and e (or table-type
  3837. (eq 'org (org-element-property :type e))))))))
  3838. (defun org-at-table.el-p ()
  3839. "Non-nil when point is at a table.el table."
  3840. (and (org-match-line "[ \t]*[|+]")
  3841. (let ((element (org-element-at-point)))
  3842. (and (eq (org-element-type element) 'table)
  3843. (eq (org-element-property :type element) 'table.el)))))
  3844. (defun org-at-table-hline-p ()
  3845. "Non-nil when point is inside a hline in a table.
  3846. Assume point is already in a table."
  3847. (org-match-line org-table-hline-regexp))
  3848. (defun org-table-map-tables (function &optional quietly)
  3849. "Apply FUNCTION to the start of all tables in the buffer."
  3850. (org-with-wide-buffer
  3851. (goto-char (point-min))
  3852. (while (re-search-forward org-table-any-line-regexp nil t)
  3853. (unless quietly
  3854. (message "Mapping tables: %d%%"
  3855. (floor (* 100.0 (point)) (buffer-size))))
  3856. (beginning-of-line 1)
  3857. (when (and (looking-at org-table-line-regexp)
  3858. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3859. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3860. (save-excursion (funcall function))
  3861. (or (looking-at org-table-line-regexp)
  3862. (forward-char 1)))
  3863. (re-search-forward org-table-any-border-regexp nil 1)))
  3864. (unless quietly (message "Mapping tables: done")))
  3865. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3866. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3867. (declare-function org-resolve-clocks "org-clock"
  3868. (&optional also-non-dangling-p prompt last-valid))
  3869. (defun org-at-TBLFM-p (&optional pos)
  3870. "Non-nil when point (or POS) is in #+TBLFM line."
  3871. (save-excursion
  3872. (goto-char (or pos (point)))
  3873. (beginning-of-line)
  3874. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3875. (eq (org-element-type (org-element-at-point)) 'table))))
  3876. (defvar org-clock-start-time)
  3877. (defvar org-clock-marker (make-marker)
  3878. "Marker recording the last clock-in.")
  3879. (defvar org-clock-hd-marker (make-marker)
  3880. "Marker recording the last clock-in, but the headline position.")
  3881. (defvar org-clock-heading ""
  3882. "The heading of the current clock entry.")
  3883. (defun org-clock-is-active ()
  3884. "Return the buffer where the clock is currently running.
  3885. Return nil if no clock is running."
  3886. (marker-buffer org-clock-marker))
  3887. (defun org-check-running-clock ()
  3888. "Check if the current buffer contains the running clock.
  3889. If yes, offer to stop it and to save the buffer with the changes."
  3890. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3891. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3892. (buffer-name))))
  3893. (org-clock-out)
  3894. (when (y-or-n-p "Save changed buffer?")
  3895. (save-buffer))))
  3896. (defun org-clocktable-try-shift (dir n)
  3897. "Check if this line starts a clock table, if yes, shift the time block."
  3898. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3899. (org-clocktable-shift dir n)))
  3900. ;;;###autoload
  3901. (defun org-clock-persistence-insinuate ()
  3902. "Set up hooks for clock persistence."
  3903. (require 'org-clock)
  3904. (add-hook 'org-mode-hook 'org-clock-load)
  3905. (add-hook 'kill-emacs-hook 'org-clock-save))
  3906. (defgroup org-archive nil
  3907. "Options concerning archiving in Org mode."
  3908. :tag "Org Archive"
  3909. :group 'org-structure)
  3910. (defcustom org-archive-location "%s_archive::"
  3911. "The location where subtrees should be archived.
  3912. The value of this variable is a string, consisting of two parts,
  3913. separated by a double-colon. The first part is a filename and
  3914. the second part is a headline.
  3915. When the filename is omitted, archiving happens in the same file.
  3916. %s in the filename will be replaced by the current file
  3917. name (without the directory part). Archiving to a different file
  3918. is useful to keep archived entries from contributing to the
  3919. Org Agenda.
  3920. The archived entries will be filed as subtrees of the specified
  3921. headline. When the headline is omitted, the subtrees are simply
  3922. filed away at the end of the file, as top-level entries. Also in
  3923. the heading you can use %s to represent the file name, this can be
  3924. useful when using the same archive for a number of different files.
  3925. Here are a few examples:
  3926. \"%s_archive::\"
  3927. If the current file is Projects.org, archive in file
  3928. Projects.org_archive, as top-level trees. This is the default.
  3929. \"::* Archived Tasks\"
  3930. Archive in the current file, under the top-level headline
  3931. \"* Archived Tasks\".
  3932. \"~/org/archive.org::\"
  3933. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3934. \"~/org/archive.org::* From %s\"
  3935. Archive in file ~/org/archive.org (absolute path), under headlines
  3936. \"From FILENAME\" where file name is the current file name.
  3937. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3938. The \"datetree/\" string is special, signifying to archive
  3939. items to the datetree. Items are placed in either the CLOSED
  3940. date of the item, or the current date if there is no CLOSED date.
  3941. The heading will be a subentry to the current date. There doesn't
  3942. need to be a heading, but there always needs to be a slash after
  3943. datetree. For example, to store archived items directly in the
  3944. datetree, use \"~/org/datetree.org::datetree/\".
  3945. \"basement::** Finished Tasks\"
  3946. Archive in file ./basement (relative path), as level 3 trees
  3947. below the level 2 heading \"** Finished Tasks\".
  3948. You may set this option on a per-file basis by adding to the buffer a
  3949. line like
  3950. #+ARCHIVE: basement::** Finished Tasks
  3951. You may also define it locally for a subtree by setting an ARCHIVE property
  3952. in the entry. If such a property is found in an entry, or anywhere up
  3953. the hierarchy, it will be used."
  3954. :group 'org-archive
  3955. :type 'string)
  3956. (defcustom org-agenda-skip-archived-trees t
  3957. "Non-nil means the agenda will skip any items located in archived trees.
  3958. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3959. variable is no longer recommended, you should leave it at the value t.
  3960. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3961. :group 'org-archive
  3962. :group 'org-agenda-skip
  3963. :type 'boolean)
  3964. (defcustom org-columns-skip-archived-trees t
  3965. "Non-nil means ignore archived trees when creating column view."
  3966. :group 'org-archive
  3967. :group 'org-properties
  3968. :type 'boolean)
  3969. (defcustom org-cycle-open-archived-trees nil
  3970. "Non-nil means `org-cycle' will open archived trees.
  3971. An archived tree is a tree marked with the tag ARCHIVE.
  3972. When nil, archived trees will stay folded. You can still open them with
  3973. normal outline commands like `show-all', but not with the cycling commands."
  3974. :group 'org-archive
  3975. :group 'org-cycle
  3976. :type 'boolean)
  3977. (defcustom org-sparse-tree-open-archived-trees nil
  3978. "Non-nil means sparse tree construction shows matches in archived trees.
  3979. When nil, matches in these trees are highlighted, but the trees are kept in
  3980. collapsed state."
  3981. :group 'org-archive
  3982. :group 'org-sparse-trees
  3983. :type 'boolean)
  3984. (defcustom org-sparse-tree-default-date-type nil
  3985. "The default date type when building a sparse tree.
  3986. When this is nil, a date is a scheduled or a deadline timestamp.
  3987. Otherwise, these types are allowed:
  3988. all: all timestamps
  3989. active: only active timestamps (<...>)
  3990. inactive: only inactive timestamps ([...])
  3991. scheduled: only scheduled timestamps
  3992. deadline: only deadline timestamps"
  3993. :type '(choice (const :tag "Scheduled or deadline" nil)
  3994. (const :tag "All timestamps" all)
  3995. (const :tag "Only active timestamps" active)
  3996. (const :tag "Only inactive timestamps" inactive)
  3997. (const :tag "Only scheduled timestamps" scheduled)
  3998. (const :tag "Only deadline timestamps" deadline)
  3999. (const :tag "Only closed timestamps" closed))
  4000. :version "26.1"
  4001. :package-version '(Org . "8.3")
  4002. :group 'org-sparse-trees)
  4003. (defun org-cycle-hide-archived-subtrees (state)
  4004. "Re-hide all archived subtrees after a visibility state change.
  4005. STATE should be one of the symbols listed in the docstring of
  4006. `org-cycle-hook'."
  4007. (when (and (not org-cycle-open-archived-trees)
  4008. (not (memq state '(overview folded))))
  4009. (save-excursion
  4010. (let* ((globalp (memq state '(contents all)))
  4011. (beg (if globalp (point-min) (point)))
  4012. (end (if globalp (point-max) (org-end-of-subtree t))))
  4013. (org-hide-archived-subtrees beg end)
  4014. (goto-char beg)
  4015. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4016. (message "%s" (substitute-command-keys
  4017. "Subtree is archived and stays closed. Use \
  4018. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  4019. (defun org-force-cycle-archived ()
  4020. "Cycle subtree even if it is archived."
  4021. (interactive)
  4022. (setq this-command 'org-cycle)
  4023. (let ((org-cycle-open-archived-trees t))
  4024. (call-interactively 'org-cycle)))
  4025. (defun org-hide-archived-subtrees (beg end)
  4026. "Re-hide all archived subtrees after a visibility state change."
  4027. (org-with-wide-buffer
  4028. (let ((case-fold-search nil)
  4029. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4030. (goto-char beg)
  4031. ;; Include headline point is currently on.
  4032. (beginning-of-line)
  4033. (while (and (< (point) end) (re-search-forward re end t))
  4034. (when (member org-archive-tag (org-get-tags nil t))
  4035. (org-flag-subtree t)
  4036. (org-end-of-subtree t))))))
  4037. (defun org-flag-subtree (flag)
  4038. (save-excursion
  4039. (org-back-to-heading t)
  4040. (org-flag-region (line-end-position)
  4041. (progn (org-end-of-subtree t) (point))
  4042. flag
  4043. 'outline)))
  4044. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4045. ;; Declare Column View Code
  4046. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4047. (declare-function org-columns-compute "org-colview" (property))
  4048. ;; Declare ID code
  4049. (declare-function org-id-store-link "org-id")
  4050. (declare-function org-id-locations-load "org-id")
  4051. (declare-function org-id-locations-save "org-id")
  4052. (defvar org-id-track-globally)
  4053. ;;; Variables for pre-computed regular expressions, all buffer local
  4054. (defvar-local org-todo-regexp nil
  4055. "Matches any of the TODO state keywords.
  4056. Since TODO keywords are case-sensitive, `case-fold-search' is
  4057. expected to be bound to nil when matching against this regexp.")
  4058. (defvar-local org-not-done-regexp nil
  4059. "Matches any of the TODO state keywords except the last one.
  4060. Since TODO keywords are case-sensitive, `case-fold-search' is
  4061. expected to be bound to nil when matching against this regexp.")
  4062. (defvar-local org-not-done-heading-regexp nil
  4063. "Matches a TODO headline that is not done.
  4064. Since TODO keywords are case-sensitive, `case-fold-search' is
  4065. expected to be bound to nil when matching against this regexp.")
  4066. (defvar-local org-todo-line-regexp nil
  4067. "Matches a headline and puts TODO state into group 2 if present.
  4068. Since TODO keywords are case-sensitive, `case-fold-search' is
  4069. expected to be bound to nil when matching against this regexp.")
  4070. (defvar-local org-complex-heading-regexp nil
  4071. "Matches a headline and puts everything into groups:
  4072. group 1: Stars
  4073. group 2: The TODO keyword, maybe
  4074. group 3: Priority cookie
  4075. group 4: True headline
  4076. group 5: Tags
  4077. Since TODO keywords are case-sensitive, `case-fold-search' is
  4078. expected to be bound to nil when matching against this regexp.")
  4079. (defvar-local org-complex-heading-regexp-format nil
  4080. "Printf format to make regexp to match an exact headline.
  4081. This regexp will match the headline of any node which has the
  4082. exact headline text that is put into the format, but may have any
  4083. TODO state, priority and tags.")
  4084. (defvar-local org-todo-line-tags-regexp nil
  4085. "Matches a headline and puts TODO state into group 2 if present.
  4086. Also put tags into group 4 if tags are present.")
  4087. (defconst org-plain-time-of-day-regexp
  4088. (concat
  4089. "\\(\\<[012]?[0-9]"
  4090. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4091. "\\(--?"
  4092. "\\(\\<[012]?[0-9]"
  4093. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4094. "\\)?")
  4095. "Regular expression to match a plain time or time range.
  4096. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4097. groups carry important information:
  4098. 0 the full match
  4099. 1 the first time, range or not
  4100. 8 the second time, if it is a range.")
  4101. (defconst org-plain-time-extension-regexp
  4102. (concat
  4103. "\\(\\<[012]?[0-9]"
  4104. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4105. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4106. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4107. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4108. groups carry important information:
  4109. 0 the full match
  4110. 7 hours of duration
  4111. 9 minutes of duration")
  4112. (defconst org-stamp-time-of-day-regexp
  4113. (concat
  4114. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4115. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4116. "\\(--?"
  4117. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4118. "Regular expression to match a timestamp time or time range.
  4119. After a match, the following groups carry important information:
  4120. 0 the full match
  4121. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4122. 2 the first time, range or not
  4123. 4 the second time, if it is a range.")
  4124. (defconst org-startup-options
  4125. '(("fold" org-startup-folded t)
  4126. ("overview" org-startup-folded t)
  4127. ("nofold" org-startup-folded nil)
  4128. ("showall" org-startup-folded nil)
  4129. ("showeverything" org-startup-folded showeverything)
  4130. ("content" org-startup-folded content)
  4131. ("indent" org-startup-indented t)
  4132. ("noindent" org-startup-indented nil)
  4133. ("hidestars" org-hide-leading-stars t)
  4134. ("showstars" org-hide-leading-stars nil)
  4135. ("odd" org-odd-levels-only t)
  4136. ("oddeven" org-odd-levels-only nil)
  4137. ("align" org-startup-align-all-tables t)
  4138. ("noalign" org-startup-align-all-tables nil)
  4139. ("shrink" org-startup-shrink-all-tables t)
  4140. ("inlineimages" org-startup-with-inline-images t)
  4141. ("noinlineimages" org-startup-with-inline-images nil)
  4142. ("latexpreview" org-startup-with-latex-preview t)
  4143. ("nolatexpreview" org-startup-with-latex-preview nil)
  4144. ("customtime" org-display-custom-times t)
  4145. ("logdone" org-log-done time)
  4146. ("lognotedone" org-log-done note)
  4147. ("nologdone" org-log-done nil)
  4148. ("lognoteclock-out" org-log-note-clock-out t)
  4149. ("nolognoteclock-out" org-log-note-clock-out nil)
  4150. ("logrepeat" org-log-repeat state)
  4151. ("lognoterepeat" org-log-repeat note)
  4152. ("logdrawer" org-log-into-drawer t)
  4153. ("nologdrawer" org-log-into-drawer nil)
  4154. ("logstatesreversed" org-log-states-order-reversed t)
  4155. ("nologstatesreversed" org-log-states-order-reversed nil)
  4156. ("nologrepeat" org-log-repeat nil)
  4157. ("logreschedule" org-log-reschedule time)
  4158. ("lognotereschedule" org-log-reschedule note)
  4159. ("nologreschedule" org-log-reschedule nil)
  4160. ("logredeadline" org-log-redeadline time)
  4161. ("lognoteredeadline" org-log-redeadline note)
  4162. ("nologredeadline" org-log-redeadline nil)
  4163. ("logrefile" org-log-refile time)
  4164. ("lognoterefile" org-log-refile note)
  4165. ("nologrefile" org-log-refile nil)
  4166. ("fninline" org-footnote-define-inline t)
  4167. ("nofninline" org-footnote-define-inline nil)
  4168. ("fnlocal" org-footnote-section nil)
  4169. ("fnauto" org-footnote-auto-label t)
  4170. ("fnprompt" org-footnote-auto-label nil)
  4171. ("fnconfirm" org-footnote-auto-label confirm)
  4172. ("fnplain" org-footnote-auto-label plain)
  4173. ("fnadjust" org-footnote-auto-adjust t)
  4174. ("nofnadjust" org-footnote-auto-adjust nil)
  4175. ("constcgs" constants-unit-system cgs)
  4176. ("constSI" constants-unit-system SI)
  4177. ("noptag" org-tag-persistent-alist nil)
  4178. ("hideblocks" org-hide-block-startup t)
  4179. ("nohideblocks" org-hide-block-startup nil)
  4180. ("beamer" org-startup-with-beamer-mode t)
  4181. ("entitiespretty" org-pretty-entities t)
  4182. ("entitiesplain" org-pretty-entities nil))
  4183. "Variable associated with STARTUP options for Org.
  4184. Each element is a list of three items: the startup options (as written
  4185. in the #+STARTUP line), the corresponding variable, and the value to set
  4186. this variable to if the option is found. An optional forth element PUSH
  4187. means to push this value onto the list in the variable.")
  4188. (defcustom org-group-tags t
  4189. "When non-nil (the default), use group tags.
  4190. This can be turned on/off through `org-toggle-tags-groups'."
  4191. :group 'org-tags
  4192. :group 'org-startup
  4193. :type 'boolean)
  4194. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4195. (defun org-toggle-tags-groups ()
  4196. "Toggle support for group tags.
  4197. Support for group tags is controlled by the option
  4198. `org-group-tags', which is non-nil by default."
  4199. (interactive)
  4200. (setq org-group-tags (not org-group-tags))
  4201. (cond ((and (derived-mode-p 'org-agenda-mode)
  4202. org-group-tags)
  4203. (org-agenda-redo))
  4204. ((derived-mode-p 'org-mode)
  4205. (let ((org-inhibit-startup t)) (org-mode))))
  4206. (message "Groups tags support has been turned %s"
  4207. (if org-group-tags "on" "off")))
  4208. (defun org--tag-add-to-alist (alist1 alist2)
  4209. "Merge tags from ALIST1 into ALIST2.
  4210. Duplicates tags outside a group are removed. Keywords and order
  4211. are preserved.
  4212. The function assumes ALIST1 and ALIST2 are proper tag alists.
  4213. See `org-tag-alist' for their structure."
  4214. (cond
  4215. ((null alist2) alist1)
  4216. ((null alist1) alist2)
  4217. (t
  4218. (let ((to-add nil)
  4219. (group-flag nil))
  4220. (dolist (tag-pair alist1)
  4221. (pcase tag-pair
  4222. (`(,(or :startgrouptag :startgroup))
  4223. (setq group-flag t)
  4224. (push tag-pair to-add))
  4225. (`(,(or :endgrouptag :endgroup))
  4226. (setq group-flag nil)
  4227. (push tag-pair to-add))
  4228. (`(,(or :grouptags :newline))
  4229. (push tag-pair to-add))
  4230. (`(,tag . ,_)
  4231. ;; Remove duplicates from ALIST1, unless they are in
  4232. ;; a group. Indeed, it makes sense to have a tag appear in
  4233. ;; multiple groups.
  4234. (when (or group-flag (not (assoc tag alist2)))
  4235. (push tag-pair to-add)))
  4236. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  4237. ;; Preserve order of ALIST1.
  4238. (append (nreverse to-add) alist2)))))
  4239. (defun org-set-regexps-and-options (&optional tags-only)
  4240. "Precompute regular expressions used in the current buffer.
  4241. When optional argument TAGS-ONLY is non-nil, only compute tags
  4242. related expressions."
  4243. (when (derived-mode-p 'org-mode)
  4244. (let ((alist (org--setup-collect-keywords
  4245. (org-make-options-regexp
  4246. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4247. (and (not tags-only)
  4248. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4249. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4250. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4251. ;; Startup options. Get this early since it does change
  4252. ;; behavior for other options (e.g., tags).
  4253. (let ((startup (cdr (assq 'startup alist))))
  4254. (dolist (option startup)
  4255. (let ((entry (assoc-string option org-startup-options t)))
  4256. (when entry
  4257. (let ((var (nth 1 entry))
  4258. (val (nth 2 entry)))
  4259. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4260. (unless (listp (symbol-value var))
  4261. (set (make-local-variable var) nil))
  4262. (add-to-list var val)))))))
  4263. (setq-local org-file-tags
  4264. (mapcar #'org-add-prop-inherited
  4265. (cdr (assq 'filetags alist))))
  4266. (setq org-current-tag-alist
  4267. (org--tag-add-to-alist
  4268. org-tag-persistent-alist
  4269. (let ((tags (cdr (assq 'tags alist))))
  4270. (if tags (org-tag-string-to-alist tags)
  4271. org-tag-alist))))
  4272. (setq org-tag-groups-alist
  4273. (org-tag-alist-to-groups org-current-tag-alist))
  4274. (unless tags-only
  4275. ;; File properties.
  4276. (setq-local org-file-properties (cdr (assq 'property alist)))
  4277. ;; Archive location.
  4278. (let ((archive (cdr (assq 'archive alist))))
  4279. (when archive (setq-local org-archive-location archive)))
  4280. ;; Category.
  4281. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4282. (when cat
  4283. (setq-local org-category (intern cat))
  4284. (setq-local org-file-properties
  4285. (org--update-property-plist
  4286. "CATEGORY" cat org-file-properties))))
  4287. ;; Columns.
  4288. (let ((column (cdr (assq 'columns alist))))
  4289. (when column (setq-local org-columns-default-format column)))
  4290. ;; Constants.
  4291. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4292. ;; Link abbreviations.
  4293. (let ((links (cdr (assq 'link alist))))
  4294. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4295. ;; Priorities.
  4296. (let ((priorities (cdr (assq 'priorities alist))))
  4297. (when priorities
  4298. (setq-local org-highest-priority (nth 0 priorities))
  4299. (setq-local org-lowest-priority (nth 1 priorities))
  4300. (setq-local org-default-priority (nth 2 priorities))))
  4301. ;; Scripts.
  4302. (let ((scripts (assq 'scripts alist)))
  4303. (when scripts
  4304. (setq-local org-use-sub-superscripts (cdr scripts))))
  4305. ;; TODO keywords.
  4306. (setq-local org-todo-kwd-alist nil)
  4307. (setq-local org-todo-key-alist nil)
  4308. (setq-local org-todo-key-trigger nil)
  4309. (setq-local org-todo-keywords-1 nil)
  4310. (setq-local org-done-keywords nil)
  4311. (setq-local org-todo-heads nil)
  4312. (setq-local org-todo-sets nil)
  4313. (setq-local org-todo-log-states nil)
  4314. (let ((todo-sequences
  4315. (or (nreverse (cdr (assq 'todo alist)))
  4316. (let ((d (default-value 'org-todo-keywords)))
  4317. (if (not (stringp (car d))) d
  4318. ;; XXX: Backward compatibility code.
  4319. (list (cons org-todo-interpretation d)))))))
  4320. (dolist (sequence todo-sequences)
  4321. (let* ((sequence (or (run-hook-with-args-until-success
  4322. 'org-todo-setup-filter-hook sequence)
  4323. sequence))
  4324. (sequence-type (car sequence))
  4325. (keywords (cdr sequence))
  4326. (sep (member "|" keywords))
  4327. names alist)
  4328. (dolist (k (remove "|" keywords))
  4329. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4330. k)
  4331. (error "Invalid TODO keyword %s" k))
  4332. (let ((name (match-string 1 k))
  4333. (key (match-string 2 k))
  4334. (log (org-extract-log-state-settings k)))
  4335. (push name names)
  4336. (push (cons name (and key (string-to-char key))) alist)
  4337. (when log (push log org-todo-log-states))))
  4338. (let* ((names (nreverse names))
  4339. (done (if sep (org-remove-keyword-keys (cdr sep))
  4340. (last names)))
  4341. (head (car names))
  4342. (tail (list sequence-type head (car done) (org-last done))))
  4343. (add-to-list 'org-todo-heads head 'append)
  4344. (push names org-todo-sets)
  4345. (setq org-done-keywords (append org-done-keywords done nil))
  4346. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4347. (setq org-todo-key-alist
  4348. (append org-todo-key-alist
  4349. (and alist
  4350. (append '((:startgroup))
  4351. (nreverse alist)
  4352. '((:endgroup))))))
  4353. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4354. (setq org-todo-sets (nreverse org-todo-sets)
  4355. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4356. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4357. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4358. ;; Compute the regular expressions and other local variables.
  4359. ;; Using `org-outline-regexp-bol' would complicate them much,
  4360. ;; because of the fixed white space at the end of that string.
  4361. (unless org-done-keywords
  4362. (setq org-done-keywords
  4363. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4364. (setq org-not-done-keywords
  4365. (org-delete-all org-done-keywords
  4366. (copy-sequence org-todo-keywords-1))
  4367. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4368. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4369. org-not-done-heading-regexp
  4370. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4371. org-todo-line-regexp
  4372. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4373. org-complex-heading-regexp
  4374. (concat "^\\(\\*+\\)"
  4375. "\\(?: +" org-todo-regexp "\\)?"
  4376. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4377. "\\(?: +\\(.*?\\)\\)??"
  4378. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4379. "[ \t]*$")
  4380. org-complex-heading-regexp-format
  4381. (concat "^\\(\\*+\\)"
  4382. "\\(?: +" org-todo-regexp "\\)?"
  4383. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4384. "\\(?: +"
  4385. ;; Stats cookies can be stuck to body.
  4386. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4387. "\\(%s\\)"
  4388. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4389. "\\)"
  4390. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4391. "[ \t]*$")
  4392. org-todo-line-tags-regexp
  4393. (concat "^\\(\\*+\\)"
  4394. "\\(?: +" org-todo-regexp "\\)?"
  4395. "\\(?: +\\(.*?\\)\\)??"
  4396. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4397. "[ \t]*$"))
  4398. (org-compute-latex-and-related-regexp)))))
  4399. (defun org--setup-collect-keywords (regexp &optional files alist)
  4400. "Return setup keywords values as an alist.
  4401. REGEXP matches a subset of setup keywords. FILES is a list of
  4402. file names already visited. It is used to avoid circular setup
  4403. files. ALIST, when non-nil, is the alist computed so far.
  4404. Return value contains the following keys: `archive', `category',
  4405. `columns', `constants', `filetags', `link', `priorities',
  4406. `property', `scripts', `startup', `tags' and `todo'."
  4407. (org-with-wide-buffer
  4408. (goto-char (point-min))
  4409. (let ((case-fold-search t))
  4410. (while (re-search-forward regexp nil t)
  4411. (let ((element (org-element-at-point)))
  4412. (when (eq (org-element-type element) 'keyword)
  4413. (let ((key (org-element-property :key element))
  4414. (value (org-element-property :value element)))
  4415. (cond
  4416. ((equal key "ARCHIVE")
  4417. (when (org-string-nw-p value)
  4418. (push (cons 'archive value) alist)))
  4419. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4420. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4421. ((equal key "CONSTANTS")
  4422. (let* ((constants (assq 'constants alist))
  4423. (store (cdr constants)))
  4424. (dolist (pair (split-string value))
  4425. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4426. pair)
  4427. (let* ((name (match-string 1 pair))
  4428. (value (match-string 2 pair))
  4429. (old (assoc name store)))
  4430. (if old (setcdr old value)
  4431. (push (cons name value) store)))))
  4432. (if constants (setcdr constants store)
  4433. (push (cons 'constants store) alist))))
  4434. ((equal key "FILETAGS")
  4435. (when (org-string-nw-p value)
  4436. (let ((old (assq 'filetags alist))
  4437. (new (apply #'nconc
  4438. (mapcar (lambda (x) (org-split-string x ":"))
  4439. (split-string value)))))
  4440. (if old (setcdr old (append new (cdr old)))
  4441. (push (cons 'filetags new) alist)))))
  4442. ((equal key "LINK")
  4443. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4444. (let ((links (assq 'link alist))
  4445. (pair (cons (match-string-no-properties 1 value)
  4446. (match-string-no-properties 2 value))))
  4447. (if links (push pair (cdr links))
  4448. (push (list 'link pair) alist)))))
  4449. ((equal key "OPTIONS")
  4450. (when (and (org-string-nw-p value)
  4451. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4452. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4453. ((equal key "PRIORITIES")
  4454. (push (cons 'priorities
  4455. (let ((prio (split-string value)))
  4456. (if (< (length prio) 3) '(?A ?C ?B)
  4457. (mapcar #'string-to-char prio))))
  4458. alist))
  4459. ((equal key "PROPERTY")
  4460. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4461. (let* ((property (assq 'property alist))
  4462. (value (org--update-property-plist
  4463. (match-string-no-properties 1 value)
  4464. (match-string-no-properties 2 value)
  4465. (cdr property))))
  4466. (if property (setcdr property value)
  4467. (push (cons 'property value) alist)))))
  4468. ((equal key "STARTUP")
  4469. (let ((startup (assq 'startup alist)))
  4470. (if startup
  4471. (setcdr startup
  4472. (append (cdr startup) (split-string value)))
  4473. (push (cons 'startup (split-string value)) alist))))
  4474. ((equal key "TAGS")
  4475. (let ((tag-cell (assq 'tags alist)))
  4476. (if tag-cell
  4477. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4478. (push (cons 'tags value) alist))))
  4479. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4480. (let ((todo (assq 'todo alist))
  4481. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4482. (split-string value))))
  4483. (if todo (push value (cdr todo))
  4484. (push (list 'todo value) alist))))
  4485. ((equal key "SETUPFILE")
  4486. (unless buffer-read-only ; Do not check in Gnus messages.
  4487. (let ((f (and (org-string-nw-p value)
  4488. (expand-file-name
  4489. (org-unbracket-string "\"" "\"" value)))))
  4490. (when (and f (file-readable-p f) (not (member f files)))
  4491. (with-temp-buffer
  4492. (setq default-directory (file-name-directory f))
  4493. (insert-file-contents f)
  4494. (setq alist
  4495. ;; Fake Org mode to benefit from cache
  4496. ;; without recurring needlessly.
  4497. (let ((major-mode 'org-mode))
  4498. (org--setup-collect-keywords
  4499. regexp (cons f files) alist)))))))))))))))
  4500. alist)
  4501. (defun org-tag-string-to-alist (s)
  4502. "Return tag alist associated to string S.
  4503. S is a value for TAGS keyword or produced with
  4504. `org-tag-alist-to-string'. Return value is an alist suitable for
  4505. `org-tag-alist' or `org-tag-persistent-alist'."
  4506. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4507. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  4508. "\\(?:(\\(.\\))\\)?\\'"))
  4509. alist group-flag)
  4510. (dolist (tokens lines (cdr (nreverse alist)))
  4511. (push '(:newline) alist)
  4512. (while tokens
  4513. (let ((token (pop tokens)))
  4514. (pcase token
  4515. ("{"
  4516. (push '(:startgroup) alist)
  4517. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4518. ("}"
  4519. (push '(:endgroup) alist)
  4520. (setq group-flag nil))
  4521. ("["
  4522. (push '(:startgrouptag) alist)
  4523. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4524. ("]"
  4525. (push '(:endgrouptag) alist)
  4526. (setq group-flag nil))
  4527. (":"
  4528. (push '(:grouptags) alist))
  4529. ((guard (string-match tag-re token))
  4530. (let ((tag (match-string 1 token))
  4531. (key (and (match-beginning 2)
  4532. (string-to-char (match-string 2 token)))))
  4533. ;; Push all tags in groups, no matter if they already
  4534. ;; appear somewhere else in the list.
  4535. (when (or group-flag (not (assoc tag alist)))
  4536. (push (cons tag key) alist))))))))))
  4537. (defun org-tag-alist-to-string (alist &optional skip-key)
  4538. "Return tag string associated to ALIST.
  4539. ALIST is an alist, as defined in `org-tag-alist' or
  4540. `org-tag-persistent-alist', or produced with
  4541. `org-tag-string-to-alist'.
  4542. Return value is a string suitable as a value for \"TAGS\"
  4543. keyword.
  4544. When optional argument SKIP-KEY is non-nil, skip selection keys
  4545. next to tags."
  4546. (mapconcat (lambda (token)
  4547. (pcase token
  4548. (`(:startgroup) "{")
  4549. (`(:endgroup) "}")
  4550. (`(:startgrouptag) "[")
  4551. (`(:endgrouptag) "]")
  4552. (`(:grouptags) ":")
  4553. (`(:newline) "\\n")
  4554. ((and
  4555. (guard (not skip-key))
  4556. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4557. (format "%s(%c)" tag key))
  4558. (`(,(and tag (pred stringp)) . ,_) tag)
  4559. (_ (user-error "Invalid tag token: %S" token))))
  4560. alist
  4561. " "))
  4562. (defun org-tag-alist-to-groups (alist)
  4563. "Return group alist from tag ALIST.
  4564. ALIST is an alist, as defined in `org-tag-alist' or
  4565. `org-tag-persistent-alist', or produced with
  4566. `org-tag-string-to-alist'. Return value is an alist following
  4567. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4568. a string, summarizing TAGS, as a list of strings."
  4569. (let (groups group-status current-group)
  4570. (dolist (token alist (nreverse groups))
  4571. (pcase token
  4572. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4573. (`(,(or :endgroup :endgrouptag))
  4574. (when (eq group-status 'append)
  4575. (push (nreverse current-group) groups))
  4576. (setq group-status nil current-group nil))
  4577. (`(:grouptags) (setq group-status 'append))
  4578. ((and `(,tag . ,_) (guard group-status))
  4579. (if (eq group-status 'append) (push tag current-group)
  4580. (setq current-group (list tag))))
  4581. (_ nil)))))
  4582. (defvar org--file-cache (make-hash-table :test #'equal)
  4583. "Hash table to store contents of files referenced via a URL.
  4584. This is the cache of file URLs read using `org-file-contents'.")
  4585. (defun org-reset-file-cache ()
  4586. "Reset the cache of files downloaded by `org-file-contents'."
  4587. (clrhash org--file-cache))
  4588. (defun org-file-url-p (file)
  4589. "Non-nil if FILE is a URL."
  4590. (require 'ffap)
  4591. (string-match-p ffap-url-regexp file))
  4592. (defun org-file-contents (file &optional noerror nocache)
  4593. "Return the contents of FILE, as a string.
  4594. FILE can be a file name or URL.
  4595. If FILE is a URL, download the contents. If the URL contents are
  4596. already cached in the `org--file-cache' hash table, the download step
  4597. is skipped.
  4598. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4599. from file or URL.
  4600. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4601. is available. This option applies only if FILE is a URL."
  4602. (let* ((is-url (org-file-url-p file))
  4603. (cache (and is-url
  4604. (not nocache)
  4605. (gethash file org--file-cache))))
  4606. (cond
  4607. (cache)
  4608. (is-url
  4609. (with-current-buffer (url-retrieve-synchronously file)
  4610. (goto-char (point-min))
  4611. ;; Move point to after the url-retrieve header.
  4612. (search-forward "\n\n" nil :move)
  4613. ;; Search for the success code only in the url-retrieve header.
  4614. (if (save-excursion
  4615. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4616. ;; Update the cache `org--file-cache' and return contents.
  4617. (puthash file
  4618. (buffer-substring-no-properties (point) (point-max))
  4619. org--file-cache)
  4620. (funcall (if noerror #'message #'user-error)
  4621. "Unable to fetch file from %S"
  4622. file))))
  4623. (t
  4624. (with-temp-buffer
  4625. (condition-case nil
  4626. (progn
  4627. (insert-file-contents file)
  4628. (buffer-string))
  4629. (file-error
  4630. (funcall (if noerror #'message #'user-error)
  4631. "Unable to read file %S"
  4632. file))))))))
  4633. (defun org-extract-log-state-settings (x)
  4634. "Extract the log state setting from a TODO keyword string.
  4635. This will extract info from a string like \"WAIT(w@/!)\"."
  4636. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4637. (let ((kw (match-string 1 x))
  4638. (log1 (and (match-end 3) (match-string 3 x)))
  4639. (log2 (and (match-end 4) (match-string 4 x))))
  4640. (and (or log1 log2)
  4641. (list kw
  4642. (and log1 (if (equal log1 "!") 'time 'note))
  4643. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4644. (defun org-remove-keyword-keys (list)
  4645. "Remove a pair of parenthesis at the end of each string in LIST."
  4646. (mapcar (lambda (x)
  4647. (if (string-match "(.*)$" x)
  4648. (substring x 0 (match-beginning 0))
  4649. x))
  4650. list))
  4651. (defun org-assign-fast-keys (alist)
  4652. "Assign fast keys to a keyword-key alist.
  4653. Respect keys that are already there."
  4654. (let (new e (alt ?0))
  4655. (while (setq e (pop alist))
  4656. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4657. (cdr e)) ;; Key already assigned.
  4658. (push e new)
  4659. (let ((clist (string-to-list (downcase (car e))))
  4660. (used (append new alist)))
  4661. (when (= (car clist) ?@)
  4662. (pop clist))
  4663. (while (and clist (rassoc (car clist) used))
  4664. (pop clist))
  4665. (unless clist
  4666. (while (rassoc alt used)
  4667. (cl-incf alt)))
  4668. (push (cons (car e) (or (car clist) alt)) new))))
  4669. (nreverse new)))
  4670. ;;; Some variables used in various places
  4671. (defvar org-window-configuration nil
  4672. "Used in various places to store a window configuration.")
  4673. (defvar org-selected-window nil
  4674. "Used in various places to store a window configuration.")
  4675. (defvar org-finish-function nil
  4676. "Function to be called when `C-c C-c' is used.
  4677. This is for getting out of special buffers like capture.")
  4678. (defvar org-last-state)
  4679. ;; Defined somewhere in this file, but used before definition.
  4680. (defvar org-entities) ;; defined in org-entities.el
  4681. (defvar org-struct-menu)
  4682. (defvar org-org-menu)
  4683. (defvar org-tbl-menu)
  4684. ;;;; Define the Org mode
  4685. ;; We use a before-change function to check if a table might need
  4686. ;; an update.
  4687. (defvar org-table-may-need-update t
  4688. "Indicates that a table might need an update.
  4689. This variable is set by `org-before-change-function'.
  4690. `org-table-align' sets it back to nil.")
  4691. (defun org-before-change-function (_beg _end)
  4692. "Every change indicates that a table might need an update."
  4693. (setq org-table-may-need-update t))
  4694. (defvar org-mode-map)
  4695. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4696. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4697. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4698. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4699. (defvar org-table-buffer-is-an nil)
  4700. (defvar bidi-paragraph-direction)
  4701. (defvar buffer-face-mode-face)
  4702. (require 'outline)
  4703. ;; Other stuff we need.
  4704. (require 'time-date)
  4705. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4706. (require 'easymenu)
  4707. (autoload 'easy-menu-add "easymenu")
  4708. (require 'overlay)
  4709. ;; (require 'org-macs) moved higher up in the file before it is first used
  4710. (require 'org-entities)
  4711. ;; (require 'org-compat) moved higher up in the file before it is first used
  4712. (require 'org-faces)
  4713. (require 'org-list)
  4714. (require 'org-pcomplete)
  4715. (require 'org-src)
  4716. (require 'org-footnote)
  4717. (require 'org-macro)
  4718. ;; babel
  4719. (require 'ob)
  4720. ;;;###autoload
  4721. (define-derived-mode org-mode outline-mode "Org"
  4722. "Outline-based notes management and organizer, alias
  4723. \"Carsten's outline-mode for keeping track of everything.\"
  4724. Org mode develops organizational tasks around a NOTES file which
  4725. contains information about projects as plain text. Org mode is
  4726. implemented on top of Outline mode, which is ideal to keep the content
  4727. of large files well structured. It supports ToDo items, deadlines and
  4728. time stamps, which magically appear in the diary listing of the Emacs
  4729. calendar. Tables are easily created with a built-in table editor.
  4730. Plain text URL-like links connect to websites, emails (VM), Usenet
  4731. messages (Gnus), BBDB entries, and any files related to the project.
  4732. For printing and sharing of notes, an Org file (or a part of it)
  4733. can be exported as a structured ASCII or HTML file.
  4734. The following commands are available:
  4735. \\{org-mode-map}"
  4736. ;; Get rid of Outline menus, they are not needed
  4737. ;; Need to do this here because define-derived-mode sets up
  4738. ;; the keymap so late. Still, it is a waste to call this each time
  4739. ;; we switch another buffer into Org mode.
  4740. (define-key org-mode-map [menu-bar headings] 'undefined)
  4741. (define-key org-mode-map [menu-bar hide] 'undefined)
  4742. (define-key org-mode-map [menu-bar show] 'undefined)
  4743. (org-load-modules-maybe)
  4744. (org-install-agenda-files-menu)
  4745. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4746. (add-to-invisibility-spec '(org-hide-block . t))
  4747. (add-to-invisibility-spec '(org-hide-drawer . t))
  4748. (setq-local outline-regexp org-outline-regexp)
  4749. (setq-local outline-level 'org-outline-level)
  4750. (setq bidi-paragraph-direction 'left-to-right)
  4751. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4752. (unless org-display-table
  4753. (setq org-display-table (make-display-table)))
  4754. (set-display-table-slot
  4755. org-display-table 4
  4756. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4757. org-ellipsis)))
  4758. (setq buffer-display-table org-display-table))
  4759. (org-set-regexps-and-options)
  4760. (org-set-font-lock-defaults)
  4761. (when (and org-tag-faces (not org-tags-special-faces-re))
  4762. ;; tag faces set outside customize.... force initialization.
  4763. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4764. ;; Calc embedded
  4765. (setq-local calc-embedded-open-mode "# ")
  4766. ;; Modify a few syntax entries
  4767. (modify-syntax-entry ?\" "\"")
  4768. (modify-syntax-entry ?\\ "_")
  4769. (modify-syntax-entry ?~ "_")
  4770. (modify-syntax-entry ?< "(>")
  4771. (modify-syntax-entry ?> ")<")
  4772. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4773. ;; Activate before-change-function
  4774. (setq-local org-table-may-need-update t)
  4775. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4776. ;; Check for running clock before killing a buffer
  4777. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4778. ;; Initialize macros templates.
  4779. (org-macro-initialize-templates)
  4780. ;; Initialize radio targets.
  4781. (org-update-radio-target-regexp)
  4782. ;; Indentation.
  4783. (setq-local indent-line-function 'org-indent-line)
  4784. (setq-local indent-region-function 'org-indent-region)
  4785. ;; Filling and auto-filling.
  4786. (org-setup-filling)
  4787. ;; Comments.
  4788. (org-setup-comments-handling)
  4789. ;; Initialize cache.
  4790. (org-element-cache-reset)
  4791. ;; Beginning/end of defun
  4792. (setq-local beginning-of-defun-function 'org-backward-element)
  4793. (setq-local end-of-defun-function
  4794. (lambda ()
  4795. (if (not (org-at-heading-p))
  4796. (org-forward-element)
  4797. (org-forward-element)
  4798. (forward-char -1))))
  4799. ;; Next error for sparse trees
  4800. (setq-local next-error-function 'org-occur-next-match)
  4801. ;; Make commit log messages from Org documents easier.
  4802. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4803. ;; Make sure dependence stuff works reliably, even for users who set it
  4804. ;; too late :-(
  4805. (if org-enforce-todo-dependencies
  4806. (add-hook 'org-blocker-hook
  4807. 'org-block-todo-from-children-or-siblings-or-parent)
  4808. (remove-hook 'org-blocker-hook
  4809. 'org-block-todo-from-children-or-siblings-or-parent))
  4810. (if org-enforce-todo-checkbox-dependencies
  4811. (add-hook 'org-blocker-hook
  4812. 'org-block-todo-from-checkboxes)
  4813. (remove-hook 'org-blocker-hook
  4814. 'org-block-todo-from-checkboxes))
  4815. ;; Align options lines
  4816. (setq-local
  4817. align-mode-rules-list
  4818. '((org-in-buffer-settings
  4819. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4820. (modes . '(org-mode)))))
  4821. ;; Make isearch reveal context
  4822. (setq-local outline-isearch-open-invisible-function
  4823. (lambda (&rest _) (org-show-context 'isearch)))
  4824. ;; Setup the pcomplete hooks
  4825. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4826. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4827. (setq-local pcomplete-default-completion-function 'ignore)
  4828. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4829. (setq-local pcomplete-termination-string "")
  4830. (setq-local buffer-face-mode-face 'org-default)
  4831. ;; If empty file that did not turn on Org mode automatically, make
  4832. ;; it to.
  4833. (when (and org-insert-mode-line-in-empty-file
  4834. (called-interactively-p 'any)
  4835. (= (point-min) (point-max)))
  4836. (insert "# -*- mode: org -*-\n\n"))
  4837. (unless org-inhibit-startup
  4838. (org-unmodified
  4839. (when org-startup-with-beamer-mode (org-beamer-mode))
  4840. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4841. (org-table-map-tables
  4842. (cond ((and org-startup-align-all-tables
  4843. org-startup-shrink-all-tables)
  4844. (lambda () (org-table-align) (org-table-shrink)))
  4845. (org-startup-align-all-tables #'org-table-align)
  4846. (t #'org-table-shrink))
  4847. t))
  4848. (when org-startup-with-inline-images (org-display-inline-images))
  4849. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4850. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4851. (when org-startup-truncated (setq truncate-lines t))
  4852. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4853. (org-refresh-effort-properties)))
  4854. ;; Try to set `org-hide' face correctly.
  4855. (let ((foreground (org-find-invisible-foreground)))
  4856. (when foreground
  4857. (set-face-foreground 'org-hide foreground))))
  4858. ;; Update `customize-package-emacs-version-alist'
  4859. (add-to-list 'customize-package-emacs-version-alist
  4860. '(Org ("8.0" . "24.4")
  4861. ("8.1" . "24.4")
  4862. ("8.2" . "24.4")
  4863. ("8.2.7" . "24.4")
  4864. ("8.3" . "26.1")
  4865. ("9.0" . "26.1")
  4866. ("9.1" . "26.1")
  4867. ("9.2" . "27.1")))
  4868. (defvar org-mode-transpose-word-syntax-table
  4869. (let ((st (make-syntax-table text-mode-syntax-table)))
  4870. (dolist (c org-emphasis-alist st)
  4871. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4872. (when (fboundp 'abbrev-table-put)
  4873. (abbrev-table-put org-mode-abbrev-table
  4874. :parents (list text-mode-abbrev-table)))
  4875. (defun org-find-invisible-foreground ()
  4876. (let ((candidates (remove
  4877. "unspecified-bg"
  4878. (nconc
  4879. (list (face-background 'default)
  4880. (face-background 'org-default))
  4881. (mapcar
  4882. (lambda (alist)
  4883. (when (boundp alist)
  4884. (cdr (assq 'background-color (symbol-value alist)))))
  4885. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4886. (list (face-foreground 'org-hide))))))
  4887. (car (remove nil candidates))))
  4888. (defun org-current-time (&optional rounding-minutes past)
  4889. "Current time, possibly rounded to ROUNDING-MINUTES.
  4890. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4891. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4892. the rounding returns a past time."
  4893. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4894. (car org-time-stamp-rounding-minutes)))
  4895. (time (decode-time)) res)
  4896. (if (< r 1)
  4897. (current-time)
  4898. (setq res
  4899. (apply 'encode-time
  4900. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4901. (nthcdr 2 time))))
  4902. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4903. (seconds-to-time (- (float-time res) (* r 60)))
  4904. res))))
  4905. (defun org-today ()
  4906. "Return today date, considering `org-extend-today-until'."
  4907. (time-to-days
  4908. (time-subtract (current-time)
  4909. (list 0 (* 3600 org-extend-today-until) 0))))
  4910. ;;;; Font-Lock stuff, including the activators
  4911. (defvar org-mouse-map (make-sparse-keymap))
  4912. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4913. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4914. (when org-mouse-1-follows-link
  4915. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4916. (when org-tab-follows-link
  4917. (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
  4918. (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
  4919. (require 'font-lock)
  4920. (defconst org-non-link-chars "]\t\n\r<>")
  4921. (defvar org-link-types-re nil
  4922. "Matches a link that has a url-like prefix like \"http:\"")
  4923. (defvar org-link-re-with-space nil
  4924. "Matches a link with spaces, optional angular brackets around it.")
  4925. (defvar org-link-re-with-space2 nil
  4926. "Matches a link with spaces, optional angular brackets around it.")
  4927. (defvar org-link-re-with-space3 nil
  4928. "Matches a link with spaces, only for internal part in bracket links.")
  4929. (defvar org-angle-link-re nil
  4930. "Matches link with angular brackets, spaces are allowed.")
  4931. (defvar org-plain-link-re nil
  4932. "Matches plain link, without spaces.")
  4933. (defvar org-bracket-link-regexp nil
  4934. "Matches a link in double brackets.")
  4935. (defvar org-bracket-link-analytic-regexp nil
  4936. "Regular expression used to analyze links.
  4937. Here is what the match groups contain after a match:
  4938. 1: http:
  4939. 2: http
  4940. 3: path
  4941. 4: [desc]
  4942. 5: desc")
  4943. (defvar org-bracket-link-analytic-regexp++ nil
  4944. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4945. (defvar org-any-link-re nil
  4946. "Regular expression matching any link.")
  4947. (defconst org-match-sexp-depth 3
  4948. "Number of stacked braces for sub/superscript matching.")
  4949. (defun org-create-multibrace-regexp (left right n)
  4950. "Create a regular expression which will match a balanced sexp.
  4951. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4952. as single character strings.
  4953. The regexp returned will match the entire expression including the
  4954. delimiters. It will also define a single group which contains the
  4955. match except for the outermost delimiters. The maximum depth of
  4956. stacked delimiters is N. Escaping delimiters is not possible."
  4957. (let* ((nothing (concat "[^" left right "]*?"))
  4958. (or "\\|")
  4959. (re nothing)
  4960. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4961. (while (> n 1)
  4962. (setq n (1- n)
  4963. re (concat re or next)
  4964. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4965. (concat left "\\(" re "\\)" right)))
  4966. (defconst org-match-substring-regexp
  4967. (concat
  4968. "\\(\\S-\\)\\([_^]\\)\\("
  4969. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4970. "\\|"
  4971. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4972. "\\|"
  4973. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4974. "The regular expression matching a sub- or superscript.")
  4975. (defconst org-match-substring-with-braces-regexp
  4976. (concat
  4977. "\\(\\S-\\)\\([_^]\\)"
  4978. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4979. "The regular expression matching a sub- or superscript, forcing braces.")
  4980. (defun org-make-link-regexps ()
  4981. "Update the link regular expressions.
  4982. This should be called after the variable `org-link-parameters' has changed."
  4983. (let ((types-re (regexp-opt (org-link-types) t)))
  4984. (setq org-link-types-re
  4985. (concat "\\`" types-re ":")
  4986. org-link-re-with-space
  4987. (concat "<?" types-re ":"
  4988. "\\([^" org-non-link-chars " ]"
  4989. "[^" org-non-link-chars "]*"
  4990. "[^" org-non-link-chars " ]\\)>?")
  4991. org-link-re-with-space2
  4992. (concat "<?" types-re ":"
  4993. "\\([^" org-non-link-chars " ]"
  4994. "[^\t\n\r]*"
  4995. "[^" org-non-link-chars " ]\\)>?")
  4996. org-link-re-with-space3
  4997. (concat "<?" types-re ":"
  4998. "\\([^" org-non-link-chars " ]"
  4999. "[^\t\n\r]*\\)")
  5000. org-angle-link-re
  5001. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  5002. types-re)
  5003. org-plain-link-re
  5004. (concat
  5005. "\\<" types-re ":"
  5006. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  5007. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  5008. org-bracket-link-regexp
  5009. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  5010. org-bracket-link-analytic-regexp
  5011. (concat
  5012. "\\[\\["
  5013. "\\(" types-re ":\\)?"
  5014. "\\([^]]+\\)"
  5015. "\\]"
  5016. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5017. "\\]")
  5018. org-bracket-link-analytic-regexp++
  5019. (concat
  5020. "\\[\\["
  5021. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  5022. "\\([^]]+\\)"
  5023. "\\]"
  5024. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5025. "\\]")
  5026. org-any-link-re
  5027. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  5028. org-angle-link-re "\\)\\|\\("
  5029. org-plain-link-re "\\)"))))
  5030. (org-make-link-regexps)
  5031. (defvar org-emph-face nil)
  5032. (defun org-do-emphasis-faces (limit)
  5033. "Run through the buffer and emphasize strings."
  5034. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  5035. (car org-emphasis-regexp-components))))
  5036. (catch :exit
  5037. (while (re-search-forward quick-re limit t)
  5038. (let* ((marker (match-string 2))
  5039. (verbatim? (member marker '("~" "="))))
  5040. (when (save-excursion
  5041. (goto-char (match-beginning 0))
  5042. (and
  5043. ;; Do not match table hlines.
  5044. (not (and (equal marker "+")
  5045. (org-match-line
  5046. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  5047. ;; Do not match headline stars. Do not consider
  5048. ;; stars of a headline as closing marker for bold
  5049. ;; markup either.
  5050. (not (and (equal marker "*")
  5051. (save-excursion
  5052. (forward-char)
  5053. (skip-chars-backward "*")
  5054. (looking-at-p org-outline-regexp-bol))))
  5055. ;; Match full emphasis markup regexp.
  5056. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  5057. ;; Do not span over paragraph boundaries.
  5058. (not (string-match-p org-element-paragraph-separate
  5059. (match-string 2)))
  5060. ;; Do not span over cells in table rows.
  5061. (not (and (save-match-data (org-match-line "[ \t]*|"))
  5062. (string-match-p "|" (match-string 4))))))
  5063. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  5064. (font-lock-prepend-text-property
  5065. (match-beginning 2) (match-end 2) 'face face)
  5066. (when verbatim?
  5067. (org-remove-flyspell-overlays-in
  5068. (match-beginning 0) (match-end 0)))
  5069. (add-text-properties (match-beginning 2) (match-end 2)
  5070. '(font-lock-multiline t org-emphasis t))
  5071. (when org-hide-emphasis-markers
  5072. (add-text-properties (match-end 4) (match-beginning 5)
  5073. '(invisible org-link))
  5074. (add-text-properties (match-beginning 3) (match-end 3)
  5075. '(invisible org-link)))
  5076. (throw :exit t))))))))
  5077. (defun org-emphasize (&optional char)
  5078. "Insert or change an emphasis, i.e. a font like bold or italic.
  5079. If there is an active region, change that region to a new emphasis.
  5080. If there is no region, just insert the marker characters and position
  5081. the cursor between them.
  5082. CHAR should be the marker character. If it is a space, it means to
  5083. remove the emphasis of the selected region.
  5084. If CHAR is not given (for example in an interactive call) it will be
  5085. prompted for."
  5086. (interactive)
  5087. (let ((erc org-emphasis-regexp-components)
  5088. (string "") beg end move s)
  5089. (if (org-region-active-p)
  5090. (setq beg (region-beginning)
  5091. end (region-end)
  5092. string (buffer-substring beg end))
  5093. (setq move t))
  5094. (unless char
  5095. (message "Emphasis marker or tag: [%s]"
  5096. (mapconcat #'car org-emphasis-alist ""))
  5097. (setq char (read-char-exclusive)))
  5098. (if (equal char ?\s)
  5099. (setq s ""
  5100. move nil)
  5101. (unless (assoc (char-to-string char) org-emphasis-alist)
  5102. (user-error "No such emphasis marker: \"%c\"" char))
  5103. (setq s (char-to-string char)))
  5104. (while (and (> (length string) 1)
  5105. (equal (substring string 0 1) (substring string -1))
  5106. (assoc (substring string 0 1) org-emphasis-alist))
  5107. (setq string (substring string 1 -1)))
  5108. (setq string (concat s string s))
  5109. (when beg (delete-region beg end))
  5110. (unless (or (bolp)
  5111. (string-match (concat "[" (nth 0 erc) "\n]")
  5112. (char-to-string (char-before (point)))))
  5113. (insert " "))
  5114. (unless (or (eobp)
  5115. (string-match (concat "[" (nth 1 erc) "\n]")
  5116. (char-to-string (char-after (point)))))
  5117. (insert " ") (backward-char 1))
  5118. (insert string)
  5119. (and move (backward-char 1))))
  5120. (defconst org-nonsticky-props
  5121. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5122. (defsubst org-rear-nonsticky-at (pos)
  5123. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5124. (defun org-activate-links (limit)
  5125. "Add link properties to links.
  5126. This includes angle, plain, and bracket links."
  5127. (catch :exit
  5128. (while (re-search-forward org-any-link-re limit t)
  5129. (let* ((start (match-beginning 0))
  5130. (end (match-end 0))
  5131. (style (cond ((eq ?< (char-after start)) 'angle)
  5132. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5133. (t 'plain))))
  5134. (when (and (memq style org-highlight-links)
  5135. ;; Do not confuse plain links with tags.
  5136. (not (and (eq style 'plain)
  5137. (let ((face (get-text-property
  5138. (max (1- start) (point-min)) 'face)))
  5139. (if (consp face) (memq 'org-tag face)
  5140. (eq 'org-tag face))))))
  5141. (let* ((link-object (save-excursion
  5142. (goto-char start)
  5143. (save-match-data (org-element-link-parser))))
  5144. (link (org-element-property :raw-link link-object))
  5145. (type (org-element-property :type link-object))
  5146. (path (org-element-property :path link-object))
  5147. (properties ;for link's visible part
  5148. (list
  5149. 'face (pcase (org-link-get-parameter type :face)
  5150. ((and (pred functionp) face) (funcall face path))
  5151. ((and (pred facep) face) face)
  5152. ((and (pred consp) face) face) ;anonymous
  5153. (_ 'org-link))
  5154. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5155. 'highlight)
  5156. 'keymap (or (org-link-get-parameter type :keymap)
  5157. org-mouse-map)
  5158. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5159. ((and (pred stringp) echo) echo)
  5160. ((and (pred functionp) echo) echo)
  5161. (_ (concat "LINK: " link)))
  5162. 'htmlize-link (pcase (org-link-get-parameter type
  5163. :htmlize-link)
  5164. ((and (pred functionp) f) (funcall f))
  5165. (_ `(:uri ,link)))
  5166. 'font-lock-multiline t)))
  5167. (org-remove-flyspell-overlays-in start end)
  5168. (org-rear-nonsticky-at end)
  5169. (if (not (eq 'bracket style))
  5170. (add-text-properties start end properties)
  5171. ;; Handle invisible parts in bracket links.
  5172. (remove-text-properties start end '(invisible nil))
  5173. (let ((hidden
  5174. (append `(invisible
  5175. ,(or (org-link-get-parameter type :display)
  5176. 'org-link))
  5177. properties))
  5178. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5179. (visible-end (or (match-end 4) (match-end 2))))
  5180. (add-text-properties start visible-start hidden)
  5181. (add-text-properties visible-start visible-end properties)
  5182. (add-text-properties visible-end end hidden)
  5183. (org-rear-nonsticky-at visible-start)
  5184. (org-rear-nonsticky-at visible-end)))
  5185. (let ((f (org-link-get-parameter type :activate-func)))
  5186. (when (functionp f)
  5187. (funcall f start end path (eq style 'bracket))))
  5188. (throw :exit t))))) ;signal success
  5189. nil))
  5190. (defun org-activate-code (limit)
  5191. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5192. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5193. (remove-text-properties (match-beginning 0) (match-end 0)
  5194. '(display t invisible t intangible t))
  5195. t))
  5196. (defcustom org-src-fontify-natively t
  5197. "When non-nil, fontify code in code blocks.
  5198. See also the `org-block' face."
  5199. :type 'boolean
  5200. :version "26.1"
  5201. :package-version '(Org . "8.3")
  5202. :group 'org-appearance
  5203. :group 'org-babel)
  5204. (defcustom org-allow-promoting-top-level-subtree nil
  5205. "When non-nil, allow promoting a top level subtree.
  5206. The leading star of the top level headline will be replaced
  5207. by a #."
  5208. :type 'boolean
  5209. :version "24.1"
  5210. :group 'org-appearance)
  5211. (defun org-fontify-meta-lines-and-blocks (limit)
  5212. (condition-case nil
  5213. (org-fontify-meta-lines-and-blocks-1 limit)
  5214. (error (message "Org mode fontification error in %S at %d"
  5215. (current-buffer)
  5216. (line-number-at-pos)))))
  5217. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5218. "Fontify #+ lines and blocks."
  5219. (let ((case-fold-search t))
  5220. (when (re-search-forward
  5221. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5222. limit t)
  5223. (let ((beg (match-beginning 0))
  5224. (block-start (match-end 0))
  5225. (block-end nil)
  5226. (lang (match-string 7))
  5227. (beg1 (line-beginning-position 2))
  5228. (dc1 (downcase (match-string 2)))
  5229. (dc3 (downcase (match-string 3)))
  5230. end end1 quoting block-type)
  5231. (cond
  5232. ((and (match-end 4) (equal dc3 "+begin"))
  5233. ;; Truly a block
  5234. (setq block-type (downcase (match-string 5))
  5235. quoting (member block-type org-protecting-blocks))
  5236. (when (re-search-forward
  5237. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5238. nil t) ;; on purpose, we look further than LIMIT
  5239. (setq end (min (point-max) (match-end 0))
  5240. end1 (min (point-max) (1- (match-beginning 0))))
  5241. (setq block-end (match-beginning 0))
  5242. (when quoting
  5243. (org-remove-flyspell-overlays-in beg1 end1)
  5244. (remove-text-properties beg end
  5245. '(display t invisible t intangible t)))
  5246. (add-text-properties
  5247. beg end '(font-lock-fontified t font-lock-multiline t))
  5248. (add-text-properties beg beg1 '(face org-meta-line))
  5249. (org-remove-flyspell-overlays-in beg beg1)
  5250. (add-text-properties ; For end_src
  5251. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5252. (org-remove-flyspell-overlays-in end1 end)
  5253. (cond
  5254. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5255. (org-src-font-lock-fontify-block lang block-start block-end)
  5256. (add-text-properties beg1 block-end '(src-block t)))
  5257. (quoting
  5258. (add-text-properties beg1 (min (point-max) (1+ end1))
  5259. (list 'face
  5260. (list :inherit
  5261. (let ((face-name
  5262. (intern (format "org-block-%s" lang))))
  5263. (append (and (facep face-name) (list face-name))
  5264. '(org-block))))))) ; end of source block
  5265. ((not org-fontify-quote-and-verse-blocks))
  5266. ((string= block-type "quote")
  5267. (add-face-text-property
  5268. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5269. ((string= block-type "verse")
  5270. (add-face-text-property
  5271. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5272. (add-text-properties beg beg1 '(face org-block-begin-line))
  5273. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5274. '(face org-block-end-line))
  5275. t))
  5276. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5277. (org-remove-flyspell-overlays-in
  5278. (match-beginning 0)
  5279. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5280. (add-text-properties
  5281. beg (match-end 3)
  5282. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5283. '(font-lock-fontified t invisible t)
  5284. '(font-lock-fontified t face org-document-info-keyword)))
  5285. (add-text-properties
  5286. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5287. (if (string-equal dc1 "+title:")
  5288. '(font-lock-fontified t face org-document-title)
  5289. '(font-lock-fontified t face org-document-info))))
  5290. ((string-prefix-p "+caption" dc1)
  5291. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5292. (remove-text-properties (match-beginning 0) (match-end 0)
  5293. '(display t invisible t intangible t))
  5294. ;; Handle short captions.
  5295. (save-excursion
  5296. (beginning-of-line)
  5297. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5298. (add-text-properties (line-beginning-position) (match-end 1)
  5299. '(font-lock-fontified t face org-meta-line))
  5300. (add-text-properties (match-end 0) (line-end-position)
  5301. '(font-lock-fontified t face org-block))
  5302. t)
  5303. ((member dc3 '(" " ""))
  5304. (org-remove-flyspell-overlays-in beg (match-end 0))
  5305. (add-text-properties
  5306. beg (match-end 0)
  5307. '(font-lock-fontified t face font-lock-comment-face)))
  5308. (t ;; just any other in-buffer setting, but not indented
  5309. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5310. (remove-text-properties (match-beginning 0) (match-end 0)
  5311. '(display t invisible t intangible t))
  5312. (add-text-properties beg (match-end 0)
  5313. '(font-lock-fontified t face org-meta-line))
  5314. t))))))
  5315. (defun org-fontify-drawers (limit)
  5316. "Fontify drawers."
  5317. (when (re-search-forward org-drawer-regexp limit t)
  5318. (add-text-properties
  5319. (match-beginning 0) (match-end 0)
  5320. '(font-lock-fontified t face org-special-keyword))
  5321. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5322. t))
  5323. (defun org-fontify-macros (limit)
  5324. "Fontify macros."
  5325. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  5326. (let ((begin (match-beginning 0))
  5327. (opening-end (match-beginning 1)))
  5328. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  5329. (match-string 1))
  5330. (let ((end (match-end 1))
  5331. (closing-start (match-beginning 1)))
  5332. (add-text-properties
  5333. begin end
  5334. '(font-lock-multiline t font-lock-fontified t face org-macro))
  5335. (org-remove-flyspell-overlays-in begin end)
  5336. (when org-hide-macro-markers
  5337. (add-text-properties begin opening-end '(invisible t))
  5338. (add-text-properties closing-start end '(invisible t)))
  5339. t)))))
  5340. (defun org-activate-footnote-links (limit)
  5341. "Add text properties for footnotes."
  5342. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5343. (when fn
  5344. (let* ((beg (nth 1 fn))
  5345. (end (nth 2 fn))
  5346. (label (car fn))
  5347. (referencep (/= (line-beginning-position) beg)))
  5348. (when (and referencep (nth 3 fn))
  5349. (save-excursion
  5350. (goto-char beg)
  5351. (search-forward (or label "fn:"))
  5352. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5353. (add-text-properties beg end
  5354. (list 'mouse-face 'highlight
  5355. 'keymap org-mouse-map
  5356. 'help-echo
  5357. (if referencep "Footnote reference"
  5358. "Footnote definition")
  5359. 'font-lock-fontified t
  5360. 'font-lock-multiline t
  5361. 'face 'org-footnote))))))
  5362. (defun org-activate-dates (limit)
  5363. "Add text properties for dates."
  5364. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5365. (not (equal (char-before (match-beginning 0)) 91)))
  5366. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5367. (add-text-properties (match-beginning 0) (match-end 0)
  5368. (list 'mouse-face 'highlight
  5369. 'keymap org-mouse-map))
  5370. (org-rear-nonsticky-at (match-end 0))
  5371. (when org-display-custom-times
  5372. ;; If it's a date range, activate custom time for second date.
  5373. (when (match-end 3)
  5374. (org-display-custom-time (match-beginning 3) (match-end 3)))
  5375. (org-display-custom-time (match-beginning 1) (match-end 1)))
  5376. t))
  5377. (defvar-local org-target-link-regexp nil
  5378. "Regular expression matching radio targets in plain text.")
  5379. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5380. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5381. border border border))
  5382. "Regular expression matching a link target.")
  5383. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5384. "Regular expression matching a radio target.")
  5385. (defconst org-any-target-regexp
  5386. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5387. "Regular expression matching any target.")
  5388. (defun org-activate-target-links (limit)
  5389. "Add text properties for target matches."
  5390. (when org-target-link-regexp
  5391. (let ((case-fold-search t))
  5392. (when (re-search-forward org-target-link-regexp limit t)
  5393. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5394. (add-text-properties (match-beginning 1) (match-end 1)
  5395. (list 'mouse-face 'highlight
  5396. 'keymap org-mouse-map
  5397. 'help-echo "Radio target link"
  5398. 'org-linked-text t))
  5399. (org-rear-nonsticky-at (match-end 1))
  5400. t))))
  5401. (defun org-update-radio-target-regexp ()
  5402. "Find all radio targets in this file and update the regular expression.
  5403. Also refresh fontification if needed."
  5404. (interactive)
  5405. (let ((old-regexp org-target-link-regexp)
  5406. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5407. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5408. (targets
  5409. (org-with-wide-buffer
  5410. (goto-char (point-min))
  5411. (let (rtn)
  5412. (while (re-search-forward org-radio-target-regexp nil t)
  5413. ;; Make sure point is really within the object.
  5414. (backward-char)
  5415. (let ((obj (org-element-context)))
  5416. (when (eq (org-element-type obj) 'radio-target)
  5417. (cl-pushnew (org-element-property :value obj) rtn
  5418. :test #'equal))))
  5419. rtn))))
  5420. (setq org-target-link-regexp
  5421. (and targets
  5422. (concat before-re
  5423. (mapconcat
  5424. (lambda (x)
  5425. (replace-regexp-in-string
  5426. " +" "\\s-+" (regexp-quote x) t t))
  5427. targets
  5428. "\\|")
  5429. after-re)))
  5430. (unless (equal old-regexp org-target-link-regexp)
  5431. ;; Clean-up cache.
  5432. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5433. ((not org-target-link-regexp) old-regexp)
  5434. (t
  5435. (concat before-re
  5436. (mapconcat
  5437. (lambda (re)
  5438. (substring re (length before-re)
  5439. (- (length after-re))))
  5440. (list old-regexp org-target-link-regexp)
  5441. "\\|")
  5442. after-re)))))
  5443. (org-with-wide-buffer
  5444. (goto-char (point-min))
  5445. (while (re-search-forward regexp nil t)
  5446. (org-element-cache-refresh (match-beginning 1)))))
  5447. ;; Re fontify buffer.
  5448. (when (memq 'radio org-highlight-links)
  5449. (org-restart-font-lock)))))
  5450. (defvar org-latex-and-related-regexp nil
  5451. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5452. (defun org-compute-latex-and-related-regexp ()
  5453. "Compute regular expression for LaTeX, entities and sub/superscript.
  5454. Result depends on variable `org-highlight-latex-and-related'."
  5455. (setq-local
  5456. org-latex-and-related-regexp
  5457. (let* ((re-sub
  5458. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5459. ((eq org-use-sub-superscripts '{})
  5460. (list org-match-substring-with-braces-regexp))
  5461. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5462. (re-latex
  5463. (when (memq 'latex org-highlight-latex-and-related)
  5464. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5465. (delq nil
  5466. (mapcar (lambda (x)
  5467. (and (member (car x) matchers) (nth 1 x)))
  5468. org-latex-regexps)))))
  5469. (re-entities
  5470. (when (memq 'entities org-highlight-latex-and-related)
  5471. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5472. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5473. (defun org-do-latex-and-related (limit)
  5474. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5475. LIMIT bounds the search for syntax to highlight. Stop at first
  5476. highlighted object, if any. Return t if some highlighting was
  5477. done, nil otherwise."
  5478. (when (org-string-nw-p org-latex-and-related-regexp)
  5479. (catch 'found
  5480. (while (re-search-forward org-latex-and-related-regexp limit t)
  5481. (unless
  5482. (cl-some
  5483. (lambda (f)
  5484. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5485. (save-excursion
  5486. (goto-char (1+ (match-beginning 0)))
  5487. (face-at-point nil t)))
  5488. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5489. '(?_ ?^))
  5490. 1
  5491. 0)))
  5492. (font-lock-prepend-text-property
  5493. (+ offset (match-beginning 0)) (match-end 0)
  5494. 'face 'org-latex-and-related)
  5495. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5496. '(font-lock-multiline t)))
  5497. (throw 'found t)))
  5498. nil)))
  5499. (defun org-restart-font-lock ()
  5500. "Restart `font-lock-mode', to force refontification."
  5501. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5502. (font-lock-mode -1)
  5503. (font-lock-mode 1)))
  5504. (defun org-activate-tags (limit)
  5505. (when (re-search-forward org-tag-line-re limit t)
  5506. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5507. (add-text-properties (match-beginning 1) (match-end 1)
  5508. (list 'mouse-face 'highlight
  5509. 'keymap org-mouse-map))
  5510. (org-rear-nonsticky-at (match-end 1))
  5511. t))
  5512. (defun org-outline-level ()
  5513. "Compute the outline level of the heading at point.
  5514. If this is called at a normal headline, the level is the number
  5515. of stars. Use `org-reduced-level' to remove the effect of
  5516. `org-odd-levels'. Unlike to `org-current-level', this function
  5517. takes into consideration inlinetasks."
  5518. (org-with-wide-buffer
  5519. (end-of-line)
  5520. (if (re-search-backward org-outline-regexp-bol nil t)
  5521. (1- (- (match-end 0) (match-beginning 0)))
  5522. 0)))
  5523. (defvar org-font-lock-keywords nil)
  5524. (defsubst org-re-property (property &optional literal allow-null value)
  5525. "Return a regexp matching a PROPERTY line.
  5526. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5527. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5528. non-nil, match properties even without a value.
  5529. Match group 3 is set to the value when it exists. If there is no
  5530. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5531. With optional argument VALUE, match only property lines with
  5532. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5533. unless LITERAL is non-nil."
  5534. (concat
  5535. "^\\(?4:[ \t]*\\)"
  5536. (format "\\(?1::\\(?2:%s\\):\\)"
  5537. (if literal property (regexp-quote property)))
  5538. (cond (value
  5539. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5540. (if literal value (regexp-quote value))))
  5541. (allow-null
  5542. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5543. (t
  5544. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5545. (defconst org-property-re
  5546. (org-re-property "\\S-+" 'literal t)
  5547. "Regular expression matching a property line.
  5548. There are four matching groups:
  5549. 1: :PROPKEY: including the leading and trailing colon,
  5550. 2: PROPKEY without the leading and trailing colon,
  5551. 3: PROPVAL without leading or trailing spaces,
  5552. 4: the indentation of the current line,
  5553. 5: trailing whitespace.")
  5554. (defvar org-font-lock-hook nil
  5555. "Functions to be called for special font lock stuff.")
  5556. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5557. (defvar org-font-lock-set-keywords-hook nil
  5558. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5559. This is called after `org-font-lock-extra-keywords' is defined, but before
  5560. it is installed to be used by font lock. This can be useful if something
  5561. needs to be inserted at a specific position in the font-lock sequence.")
  5562. (defun org-font-lock-hook (limit)
  5563. "Run `org-font-lock-hook' within LIMIT."
  5564. (run-hook-with-args 'org-font-lock-hook limit))
  5565. (defun org-set-font-lock-defaults ()
  5566. "Set font lock defaults for the current buffer."
  5567. (let* ((em org-fontify-emphasized-text)
  5568. (lk org-highlight-links)
  5569. (org-font-lock-extra-keywords
  5570. (list
  5571. ;; Call the hook
  5572. '(org-font-lock-hook)
  5573. ;; Headlines
  5574. `(,(if org-fontify-whole-heading-line
  5575. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5576. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5577. (1 (org-get-level-face 1))
  5578. (2 (org-get-level-face 2))
  5579. (3 (org-get-level-face 3)))
  5580. ;; Table lines
  5581. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5582. (1 'org-table t))
  5583. ;; Table internals
  5584. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5585. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5586. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5587. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5588. ;; Drawers
  5589. '(org-fontify-drawers)
  5590. ;; Properties
  5591. (list org-property-re
  5592. '(1 'org-special-keyword t)
  5593. '(3 'org-property-value t))
  5594. ;; Link related fontification.
  5595. '(org-activate-links)
  5596. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5597. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5598. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5599. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5600. ;; Targets.
  5601. (list org-any-target-regexp '(0 'org-target t))
  5602. ;; Diary sexps.
  5603. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5604. ;; Macro
  5605. '(org-fontify-macros)
  5606. ;; TODO keyword
  5607. (list (format org-heading-keyword-regexp-format
  5608. org-todo-regexp)
  5609. '(2 (org-get-todo-face 2) t))
  5610. ;; DONE
  5611. (if org-fontify-done-headline
  5612. (list (format org-heading-keyword-regexp-format
  5613. (concat
  5614. "\\(?:"
  5615. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5616. "\\)"))
  5617. '(2 'org-headline-done t))
  5618. nil)
  5619. ;; Priorities
  5620. '(org-font-lock-add-priority-faces)
  5621. ;; Tags
  5622. '(org-font-lock-add-tag-faces)
  5623. ;; Tags groups
  5624. (when (and org-group-tags org-tag-groups-alist)
  5625. (list (concat org-outline-regexp-bol ".+\\(:"
  5626. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5627. ":\\).*$")
  5628. '(1 'org-tag-group prepend)))
  5629. ;; Special keywords
  5630. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5631. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5632. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5633. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5634. ;; Emphasis
  5635. (when em '(org-do-emphasis-faces))
  5636. ;; Checkboxes
  5637. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5638. 1 'org-checkbox prepend)
  5639. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5640. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5641. (0 (org-get-checkbox-statistics-face) t)))
  5642. ;; Description list items
  5643. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5644. 1 'org-list-dt prepend)
  5645. ;; ARCHIVEd headings
  5646. (list (concat
  5647. org-outline-regexp-bol
  5648. "\\(.*:" org-archive-tag ":.*\\)")
  5649. '(1 'org-archived prepend))
  5650. ;; Specials
  5651. '(org-do-latex-and-related)
  5652. '(org-fontify-entities)
  5653. '(org-raise-scripts)
  5654. ;; Code
  5655. '(org-activate-code (1 'org-code t))
  5656. ;; COMMENT
  5657. (list (format
  5658. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5659. org-todo-regexp
  5660. org-comment-string)
  5661. '(9 'org-special-keyword t))
  5662. ;; Blocks and meta lines
  5663. '(org-fontify-meta-lines-and-blocks))))
  5664. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5665. (run-hooks 'org-font-lock-set-keywords-hook)
  5666. ;; Now set the full font-lock-keywords
  5667. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5668. (setq-local font-lock-defaults
  5669. '(org-font-lock-keywords t nil nil backward-paragraph))
  5670. (kill-local-variable 'font-lock-keywords)
  5671. nil))
  5672. (defun org-toggle-pretty-entities ()
  5673. "Toggle the composition display of entities as UTF8 characters."
  5674. (interactive)
  5675. (setq-local org-pretty-entities (not org-pretty-entities))
  5676. (org-restart-font-lock)
  5677. (if org-pretty-entities
  5678. (message "Entities are now displayed as UTF8 characters")
  5679. (save-restriction
  5680. (widen)
  5681. (decompose-region (point-min) (point-max))
  5682. (message "Entities are now displayed as plain text"))))
  5683. (defvar-local org-custom-properties-overlays nil
  5684. "List of overlays used for custom properties.")
  5685. (defun org-toggle-custom-properties-visibility ()
  5686. "Display or hide properties in `org-custom-properties'."
  5687. (interactive)
  5688. (if org-custom-properties-overlays
  5689. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5690. (setq org-custom-properties-overlays nil))
  5691. (when org-custom-properties
  5692. (org-with-wide-buffer
  5693. (goto-char (point-min))
  5694. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5695. (while (re-search-forward regexp nil t)
  5696. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5697. (when (and end (< (point) end))
  5698. ;; Hide first custom property in current drawer.
  5699. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5700. (overlay-put o 'invisible t)
  5701. (overlay-put o 'org-custom-property t)
  5702. (push o org-custom-properties-overlays))
  5703. ;; Hide additional custom properties in the same drawer.
  5704. (while (re-search-forward regexp end t)
  5705. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5706. (overlay-put o 'invisible t)
  5707. (overlay-put o 'org-custom-property t)
  5708. (push o org-custom-properties-overlays)))))
  5709. ;; Each entry is limited to a single property drawer.
  5710. (outline-next-heading)))))))
  5711. (defun org-fontify-entities (limit)
  5712. "Find an entity to fontify."
  5713. (let (ee)
  5714. (when org-pretty-entities
  5715. (catch 'match
  5716. ;; "\_ "-family is left out on purpose. Only the first one,
  5717. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5718. ;; confusing when adding a second white space character.
  5719. (while (re-search-forward
  5720. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5721. limit t)
  5722. (when (and (not (org-at-comment-p))
  5723. (setq ee (org-entity-get (match-string 1)))
  5724. (= (length (nth 6 ee)) 1))
  5725. (let* ((end (if (equal (match-string 2) "{}")
  5726. (match-end 2)
  5727. (match-end 1))))
  5728. (add-text-properties
  5729. (match-beginning 0) end
  5730. (list 'font-lock-fontified t))
  5731. (compose-region (match-beginning 0) end
  5732. (nth 6 ee) nil)
  5733. (backward-char 1)
  5734. (throw 'match t))))
  5735. nil))))
  5736. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5737. "Fontify string S like in Org mode."
  5738. (with-temp-buffer
  5739. (insert s)
  5740. (let ((org-odd-levels-only odd-levels))
  5741. (org-mode)
  5742. (org-font-lock-ensure)
  5743. (buffer-string))))
  5744. (defvar org-m nil)
  5745. (defvar org-l nil)
  5746. (defvar org-f nil)
  5747. (defun org-get-level-face (n)
  5748. "Get the right face for match N in font-lock matching of headlines."
  5749. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5750. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5751. (if org-cycle-level-faces
  5752. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5753. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5754. (cond
  5755. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5756. ((eq n 2) org-f)
  5757. (t (unless org-level-color-stars-only org-f))))
  5758. (defun org-face-from-face-or-color (context inherit face-or-color)
  5759. "Create a face list that inherits INHERIT, but sets the foreground color.
  5760. When FACE-OR-COLOR is not a string, just return it."
  5761. (if (stringp face-or-color)
  5762. (list :inherit inherit
  5763. (cdr (assoc context org-faces-easy-properties))
  5764. face-or-color)
  5765. face-or-color))
  5766. (defun org-get-todo-face (kwd)
  5767. "Get the right face for a TODO keyword KWD.
  5768. If KWD is a number, get the corresponding match group."
  5769. (when (numberp kwd) (setq kwd (match-string kwd)))
  5770. (or (org-face-from-face-or-color
  5771. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5772. (and (member kwd org-done-keywords) 'org-done)
  5773. 'org-todo))
  5774. (defun org-get-priority-face (priority)
  5775. "Get the right face for PRIORITY.
  5776. PRIORITY is a character."
  5777. (or (org-face-from-face-or-color
  5778. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5779. 'org-priority))
  5780. (defun org-get-tag-face (tag)
  5781. "Get the right face for TAG.
  5782. If TAG is a number, get the corresponding match group."
  5783. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5784. (or (org-face-from-face-or-color
  5785. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5786. 'org-tag)))
  5787. (defun org-font-lock-add-priority-faces (limit)
  5788. "Add the special priority faces."
  5789. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5790. (add-text-properties
  5791. (match-beginning 1) (match-end 1)
  5792. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5793. 'font-lock-fontified t))))
  5794. (defun org-font-lock-add-tag-faces (limit)
  5795. "Add the special tag faces."
  5796. (when (and org-tag-faces org-tags-special-faces-re)
  5797. (while (re-search-forward org-tags-special-faces-re limit t)
  5798. (add-text-properties (match-beginning 1) (match-end 1)
  5799. (list 'face (org-get-tag-face 1)
  5800. 'font-lock-fontified t))
  5801. (backward-char 1))))
  5802. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5803. "Remove fontification and activation overlays from links."
  5804. (font-lock-default-unfontify-region beg end)
  5805. (let* ((buffer-undo-list t)
  5806. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5807. (inhibit-modification-hooks t)
  5808. deactivate-mark buffer-file-name buffer-file-truename)
  5809. (decompose-region beg end)
  5810. (remove-text-properties beg end
  5811. '(mouse-face t keymap t org-linked-text t
  5812. invisible t intangible t
  5813. org-emphasis t))
  5814. (org-remove-font-lock-display-properties beg end)))
  5815. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5816. ((raise 0.3) (height 0.7))
  5817. ((raise -0.5))
  5818. ((raise 0.5)))
  5819. "Display properties for showing superscripts and subscripts.")
  5820. (defun org-remove-font-lock-display-properties (beg end)
  5821. "Remove specific display properties that have been added by font lock.
  5822. The will remove the raise properties that are used to show superscripts
  5823. and subscripts."
  5824. (let (next prop)
  5825. (while (< beg end)
  5826. (setq next (next-single-property-change beg 'display nil end)
  5827. prop (get-text-property beg 'display))
  5828. (when (member prop org-script-display)
  5829. (put-text-property beg next 'display nil))
  5830. (setq beg next))))
  5831. (defun org-raise-scripts (limit)
  5832. "Add raise properties to sub/superscripts."
  5833. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5834. (re-search-forward
  5835. (if (eq org-use-sub-superscripts t)
  5836. org-match-substring-regexp
  5837. org-match-substring-with-braces-regexp)
  5838. limit t))
  5839. (let* ((pos (point)) table-p comment-p
  5840. (mpos (match-beginning 3))
  5841. (emph-p (get-text-property mpos 'org-emphasis))
  5842. (link-p (get-text-property mpos 'mouse-face))
  5843. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5844. (goto-char (point-at-bol))
  5845. (setq table-p (looking-at-p org-table-dataline-regexp)
  5846. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5847. (goto-char pos)
  5848. ;; Handle a_b^c
  5849. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5850. (unless (or comment-p emph-p link-p keyw-p)
  5851. (put-text-property (match-beginning 3) (match-end 0)
  5852. 'display
  5853. (if (equal (char-after (match-beginning 2)) ?^)
  5854. (nth (if table-p 3 1) org-script-display)
  5855. (nth (if table-p 2 0) org-script-display)))
  5856. (add-text-properties (match-beginning 2) (match-end 2)
  5857. (list 'invisible t))
  5858. (when (and (eq (char-after (match-beginning 3)) ?{)
  5859. (eq (char-before (match-end 3)) ?}))
  5860. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5861. (list 'invisible t))
  5862. (add-text-properties (1- (match-end 3)) (match-end 3)
  5863. (list 'invisible t))))
  5864. t)))
  5865. (defun org-remove-empty-overlays-at (pos)
  5866. "Remove outline overlays that do not contain non-white stuff."
  5867. (dolist (o (overlays-at pos))
  5868. (and (eq 'outline (overlay-get o 'invisible))
  5869. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5870. (overlay-end o))))
  5871. (delete-overlay o))))
  5872. (defun org-show-empty-lines-in-parent ()
  5873. "Move to the parent and re-show empty lines before visible headlines."
  5874. (save-excursion
  5875. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5876. (org-cycle-show-empty-lines context))))
  5877. (defun org-files-list ()
  5878. "Return `org-agenda-files' list, plus all open Org files.
  5879. This is useful for operations that need to scan all of a user's
  5880. open and agenda-wise Org files."
  5881. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5882. (dolist (buf (buffer-list))
  5883. (with-current-buffer buf
  5884. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5885. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5886. :test #'equal))))
  5887. files))
  5888. (defsubst org-entry-beginning-position ()
  5889. "Return the beginning position of the current entry."
  5890. (save-excursion (org-back-to-heading t) (point)))
  5891. (defsubst org-entry-end-position ()
  5892. "Return the end position of the current entry."
  5893. (save-excursion (outline-next-heading) (point)))
  5894. (defun org-subtree-end-visible-p ()
  5895. "Is the end of the current subtree visible?"
  5896. (pos-visible-in-window-p
  5897. (save-excursion (org-end-of-subtree t) (point))))
  5898. (defun org-first-headline-recenter ()
  5899. "Move cursor to the first headline and recenter the headline."
  5900. (let ((window (get-buffer-window)))
  5901. (when window
  5902. (goto-char (point-min))
  5903. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5904. (set-window-start window (line-beginning-position))))))
  5905. ;;; Visibility (headlines, blocks, drawers)
  5906. ;;;; Headlines visibility
  5907. (defun org-show-entry ()
  5908. "Show the body directly following this heading.
  5909. Show the heading too, if it is currently invisible."
  5910. (interactive)
  5911. (save-excursion
  5912. (ignore-errors
  5913. (org-back-to-heading t)
  5914. (org-flag-region
  5915. (line-end-position 0)
  5916. (save-excursion
  5917. (if (re-search-forward
  5918. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5919. (match-beginning 1)
  5920. (point-max)))
  5921. nil
  5922. 'outline))))
  5923. (defun org-show-children (&optional level)
  5924. "Show all direct subheadings of this heading.
  5925. Prefix arg LEVEL is how many levels below the current level
  5926. should be shown. Default is enough to cause the following
  5927. heading to appear."
  5928. (interactive "p")
  5929. (save-excursion
  5930. (org-back-to-heading t)
  5931. (let* ((current-level (funcall outline-level))
  5932. (max-level (org-get-valid-level
  5933. current-level
  5934. (if level (prefix-numeric-value level) 1)))
  5935. (end (save-excursion (org-end-of-subtree t t)))
  5936. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5937. (past-first-child nil)
  5938. ;; Make sure to skip inlinetasks.
  5939. (re (format regexp-fmt
  5940. current-level
  5941. (cond
  5942. ((not (featurep 'org-inlinetask)) "")
  5943. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5944. 3))
  5945. (t (1- org-inlinetask-min-level))))))
  5946. ;; Display parent heading.
  5947. (org-flag-heading nil)
  5948. (forward-line)
  5949. ;; Display children. First child may be deeper than expected
  5950. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5951. ;; MAX-LEVEL accordingly.
  5952. (while (re-search-forward re end t)
  5953. (unless past-first-child
  5954. (setq re (format regexp-fmt
  5955. current-level
  5956. (max (funcall outline-level) max-level)))
  5957. (setq past-first-child t))
  5958. (org-flag-heading nil)))))
  5959. (defun org-show-subtree ()
  5960. "Show everything after this heading at deeper levels."
  5961. (interactive)
  5962. (org-flag-region
  5963. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5964. ;;;; Blocks visibility
  5965. (defun org-hide-block-toggle-maybe ()
  5966. "Toggle visibility of block at point.
  5967. Unlike to `org-hide-block-toggle', this function does not throw
  5968. an error. Return a non-nil value when toggling is successful."
  5969. (interactive)
  5970. (ignore-errors (org-hide-block-toggle)))
  5971. (defun org-hide-block-toggle (&optional force)
  5972. "Toggle the visibility of the current block.
  5973. When optional argument FORCE is `off', make block visible. If it
  5974. is non-nil, hide it unconditionally. Throw an error when not at
  5975. a block. Return a non-nil value when toggling is successful."
  5976. (interactive)
  5977. (let ((element (org-element-at-point)))
  5978. (unless (memq (org-element-type element)
  5979. '(center-block comment-block dynamic-block example-block
  5980. export-block quote-block special-block
  5981. src-block verse-block))
  5982. (user-error "Not at a block"))
  5983. (let* ((post (org-element-property :post-affiliated element))
  5984. (start (save-excursion
  5985. (goto-char post)
  5986. (line-end-position)))
  5987. (end (save-excursion
  5988. (goto-char (org-element-property :end element))
  5989. (skip-chars-backward " \t\n")
  5990. (line-end-position))))
  5991. ;; Do nothing when not before or at the block opening line or at
  5992. ;; the block closing line.
  5993. (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
  5994. (cond ((eq force 'off)
  5995. (org-flag-region start end nil 'org-hide-block))
  5996. (force
  5997. (org-flag-region start end t 'org-hide-block))
  5998. ((eq (get-char-property start 'invisible) 'org-hide-block)
  5999. (org-flag-region start end nil 'org-hide-block))
  6000. (t
  6001. (org-flag-region start end t 'org-hide-block)))
  6002. ;; When the block is hidden away, make sure point is left in
  6003. ;; a visible part of the buffer.
  6004. (when (invisible-p (max (1- (point)) (point-min)))
  6005. (goto-char post))
  6006. ;; Signal success.
  6007. t))))
  6008. (defun org-hide-block-toggle-all ()
  6009. "Toggle the visibility of all blocks in the current buffer."
  6010. (org-block-map 'org-hide-block-toggle))
  6011. (defun org-hide-block-all ()
  6012. "Fold all blocks in the current buffer."
  6013. (interactive)
  6014. (org-show-all '(blocks))
  6015. (org-block-map 'org-hide-block-toggle-maybe))
  6016. ;;;; Drawers visibility
  6017. (defun org-cycle-hide-drawers (state &optional exceptions)
  6018. "Re-hide all drawers after a visibility state change.
  6019. STATE should be one of the symbols listed in the docstring of
  6020. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  6021. a list of strings specifying which drawers should not be hidden."
  6022. (when (and (derived-mode-p 'org-mode)
  6023. (not (memq state '(overview folded contents))))
  6024. (save-excursion
  6025. (let* ((globalp (eq state 'all))
  6026. (beg (if globalp (point-min) (point)))
  6027. (end (if globalp (point-max)
  6028. (if (eq state 'children)
  6029. (save-excursion (outline-next-heading) (point))
  6030. (org-end-of-subtree t)))))
  6031. (goto-char beg)
  6032. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6033. (unless (member-ignore-case (match-string 1) exceptions)
  6034. (let ((drawer (org-element-at-point)))
  6035. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6036. (org-flag-drawer t drawer)
  6037. ;; Make sure to skip drawer entirely or we might flag
  6038. ;; it another time when matching its ending line with
  6039. ;; `org-drawer-regexp'.
  6040. (goto-char (org-element-property :end drawer))))))))))
  6041. (defun org-flag-drawer (flag &optional element)
  6042. "When FLAG is non-nil, hide the drawer we are at.
  6043. Otherwise make it visible. When optional argument ELEMENT is
  6044. a parsed drawer, as returned by `org-element-at-point', hide or
  6045. show that drawer instead."
  6046. (let ((drawer (or element
  6047. (and (save-excursion
  6048. (beginning-of-line)
  6049. (looking-at-p org-drawer-regexp))
  6050. (org-element-at-point)))))
  6051. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6052. (let ((post (org-element-property :post-affiliated drawer)))
  6053. (org-flag-region
  6054. (save-excursion (goto-char post) (line-end-position))
  6055. (save-excursion (goto-char (org-element-property :end drawer))
  6056. (skip-chars-backward " \t\n")
  6057. (line-end-position))
  6058. flag 'org-hide-drawer)
  6059. ;; When the drawer is hidden away, make sure point lies in
  6060. ;; a visible part of the buffer.
  6061. (when (invisible-p (max (1- (point)) (point-min)))
  6062. (goto-char post))))))
  6063. ;;;; Visibility cycling
  6064. (defvar-local org-cycle-global-status nil)
  6065. (put 'org-cycle-global-status 'org-state t)
  6066. (defvar-local org-cycle-subtree-status nil)
  6067. (put 'org-cycle-subtree-status 'org-state t)
  6068. (defun org-show-all (&optional types)
  6069. "Show all contents in the visible part of the buffer.
  6070. By default, the function expands headings, blocks and drawers.
  6071. When optional argument TYPE is a list of symbols among `blocks',
  6072. `drawers' and `headings', to only expand one specific type."
  6073. (dolist (type (or types '(blocks drawers headings)))
  6074. (org-flag-region (point-min) (point-max) nil
  6075. (pcase type
  6076. (`blocks 'org-hide-block)
  6077. (`drawers 'org-hide-drawer)
  6078. (`headings 'outline)
  6079. (_ (error "Invalid type: %S" type))))))
  6080. ;;;###autoload
  6081. (defun org-cycle (&optional arg)
  6082. "TAB-action and visibility cycling for Org mode.
  6083. This is the command invoked in Org mode by the `TAB' key. Its main
  6084. purpose is outline visibility cycling, but it also invokes other actions
  6085. in special contexts.
  6086. When this function is called with a `\\[universal-argument]' prefix, rotate \
  6087. the entire
  6088. buffer through 3 states (global cycling)
  6089. 1. OVERVIEW: Show only top-level headlines.
  6090. 2. CONTENTS: Show all headlines of all levels, but no body text.
  6091. 3. SHOW ALL: Show everything.
  6092. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  6093. switch to the startup visibility,
  6094. determined by the variable `org-startup-folded', and by any VISIBILITY
  6095. properties in the buffer.
  6096. With a `\\[universal-argument] \\[universal-argument] \
  6097. \\[universal-argument]' prefix argument, show the entire buffer, including
  6098. any drawers.
  6099. When inside a table, re-align the table and move to the next field.
  6100. When point is at the beginning of a headline, rotate the subtree started
  6101. by this line through 3 different states (local cycling)
  6102. 1. FOLDED: Only the main headline is shown.
  6103. 2. CHILDREN: The main headline and the direct children are shown.
  6104. From this state, you can move to one of the children
  6105. and zoom in further.
  6106. 3. SUBTREE: Show the entire subtree, including body text.
  6107. If there is no subtree, switch directly from CHILDREN to FOLDED.
  6108. When point is at the beginning of an empty headline and the variable
  6109. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  6110. of the headline by demoting and promoting it to likely levels. This
  6111. speeds up creation document structure by pressing `TAB' once or several
  6112. times right after creating a new headline.
  6113. When there is a numeric prefix, go up to a heading with level ARG, do
  6114. a `show-subtree' and return to the previous cursor position. If ARG
  6115. is negative, go up that many levels.
  6116. When point is not at the beginning of a headline, execute the global
  6117. binding for `TAB', which is re-indenting the line. See the option
  6118. `org-cycle-emulate-tab' for details.
  6119. As a special case, if point is at the beginning of the buffer and there is
  6120. no headline in line 1, this function will act as if called with prefix arg
  6121. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  6122. prefix arg, but only
  6123. if the variable `org-cycle-global-at-bob' is t."
  6124. (interactive "P")
  6125. (org-load-modules-maybe)
  6126. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  6127. (and org-cycle-level-after-item/entry-creation
  6128. (or (org-cycle-level)
  6129. (org-cycle-item-indentation))))
  6130. (let* ((limit-level
  6131. (or org-cycle-max-level
  6132. (and (boundp 'org-inlinetask-min-level)
  6133. org-inlinetask-min-level
  6134. (1- org-inlinetask-min-level))))
  6135. (nstars (and limit-level
  6136. (if org-odd-levels-only
  6137. (and limit-level (1- (* limit-level 2)))
  6138. limit-level)))
  6139. (org-outline-regexp
  6140. (if (not (derived-mode-p 'org-mode))
  6141. outline-regexp
  6142. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  6143. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  6144. (not (looking-at org-outline-regexp))))
  6145. (org-cycle-hook
  6146. (if bob-special
  6147. (delq 'org-optimize-window-after-visibility-change
  6148. (copy-sequence org-cycle-hook))
  6149. org-cycle-hook))
  6150. (pos (point)))
  6151. (cond
  6152. ((equal arg '(16))
  6153. (setq last-command 'dummy)
  6154. (org-set-startup-visibility)
  6155. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  6156. ((equal arg '(64))
  6157. (org-show-all)
  6158. (org-unlogged-message "Entire buffer visible, including drawers"))
  6159. ((equal arg '(4)) (org-cycle-internal-global))
  6160. ;; Try hiding block at point.
  6161. ((org-hide-block-toggle-maybe))
  6162. ;; Try cdlatex TAB completion
  6163. ((org-try-cdlatex-tab))
  6164. ;; Table: enter it or move to the next field.
  6165. ((org-at-table-p 'any)
  6166. (if (org-at-table.el-p)
  6167. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6168. Use `\\[org-edit-special]' to edit table.el tables"))
  6169. (if arg (org-table-edit-field t)
  6170. (org-table-justify-field-maybe)
  6171. (call-interactively 'org-table-next-field))))
  6172. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  6173. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6174. (bob-special (org-cycle-internal-global))
  6175. ;; Drawers: delegate to `org-flag-drawer'.
  6176. ((save-excursion
  6177. (beginning-of-line 1)
  6178. (looking-at org-drawer-regexp))
  6179. (org-flag-drawer ; toggle block visibility
  6180. (not (get-char-property (match-end 0) 'invisible))))
  6181. ;; Show-subtree, ARG levels up from here.
  6182. ((integerp arg)
  6183. (save-excursion
  6184. (org-back-to-heading)
  6185. (outline-up-heading (if (< arg 0) (- arg)
  6186. (- (funcall outline-level) arg)))
  6187. (org-show-subtree)))
  6188. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6189. ((and (featurep 'org-inlinetask)
  6190. (org-inlinetask-at-task-p)
  6191. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6192. (org-inlinetask-toggle-visibility))
  6193. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6194. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6195. (save-excursion (move-beginning-of-line 1)
  6196. (looking-at org-outline-regexp)))
  6197. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6198. (org-cycle-internal-local))
  6199. ;; From there: TAB emulation and template completion.
  6200. (buffer-read-only (org-back-to-heading))
  6201. ((run-hook-with-args-until-success
  6202. 'org-tab-after-check-for-cycling-hook))
  6203. ((run-hook-with-args-until-success
  6204. 'org-tab-before-tab-emulation-hook))
  6205. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6206. (or (not (bolp))
  6207. (not (looking-at org-outline-regexp))))
  6208. (call-interactively (global-key-binding "\t")))
  6209. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6210. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6211. (or (and (eq org-cycle-emulate-tab 'white)
  6212. (= (match-end 0) (point-at-eol)))
  6213. (and (eq org-cycle-emulate-tab 'whitestart)
  6214. (>= (match-end 0) pos))))
  6215. t
  6216. (eq org-cycle-emulate-tab t))
  6217. (call-interactively (global-key-binding "\t")))
  6218. (t (save-excursion
  6219. (org-back-to-heading)
  6220. (org-cycle)))))))
  6221. (defun org-cycle-internal-global ()
  6222. "Do the global cycling action."
  6223. ;; Hack to avoid display of messages for .org attachments in Gnus
  6224. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6225. (cond
  6226. ((and (eq last-command this-command)
  6227. (eq org-cycle-global-status 'overview))
  6228. ;; We just created the overview - now do table of contents
  6229. ;; This can be slow in very large buffers, so indicate action
  6230. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6231. (unless ga (org-unlogged-message "CONTENTS..."))
  6232. (org-content)
  6233. (unless ga (org-unlogged-message "CONTENTS...done"))
  6234. (setq org-cycle-global-status 'contents)
  6235. (run-hook-with-args 'org-cycle-hook 'contents))
  6236. ((and (eq last-command this-command)
  6237. (eq org-cycle-global-status 'contents))
  6238. ;; We just showed the table of contents - now show everything
  6239. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6240. (org-show-all '(headings blocks))
  6241. (unless ga (org-unlogged-message "SHOW ALL"))
  6242. (setq org-cycle-global-status 'all)
  6243. (run-hook-with-args 'org-cycle-hook 'all))
  6244. (t
  6245. ;; Default action: go to overview
  6246. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6247. (org-overview)
  6248. (unless ga (org-unlogged-message "OVERVIEW"))
  6249. (setq org-cycle-global-status 'overview)
  6250. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6251. (defvar org-called-with-limited-levels nil
  6252. "Non-nil when `org-with-limited-levels' is currently active.")
  6253. (defun org-cycle-internal-local ()
  6254. "Do the local cycling action."
  6255. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6256. ;; First, determine end of headline (EOH), end of subtree or item
  6257. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6258. (save-excursion
  6259. (if (org-at-item-p)
  6260. (progn
  6261. (beginning-of-line)
  6262. (setq struct (org-list-struct))
  6263. (setq eoh (point-at-eol))
  6264. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6265. (setq has-children (org-list-has-child-p (point) struct)))
  6266. (org-back-to-heading)
  6267. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6268. (setq eos (save-excursion (org-end-of-subtree t t)
  6269. (when (bolp) (backward-char)) (point)))
  6270. (setq has-children
  6271. (or (save-excursion
  6272. (let ((level (funcall outline-level)))
  6273. (outline-next-heading)
  6274. (and (org-at-heading-p t)
  6275. (> (funcall outline-level) level))))
  6276. (save-excursion
  6277. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6278. ;; Determine end invisible part of buffer (EOL)
  6279. (beginning-of-line 2)
  6280. (while (and (not (eobp)) ;This is like `next-line'.
  6281. (get-char-property (1- (point)) 'invisible))
  6282. (goto-char (next-single-char-property-change (point) 'invisible))
  6283. (and (eolp) (beginning-of-line 2)))
  6284. (setq eol (point)))
  6285. ;; Find out what to do next and set `this-command'
  6286. (cond
  6287. ((= eos eoh)
  6288. ;; Nothing is hidden behind this heading
  6289. (unless (org-before-first-heading-p)
  6290. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6291. (org-unlogged-message "EMPTY ENTRY")
  6292. (setq org-cycle-subtree-status nil)
  6293. (save-excursion
  6294. (goto-char eos)
  6295. (outline-next-heading)
  6296. (when (org-invisible-p) (org-flag-heading nil))))
  6297. ((and (or (>= eol eos)
  6298. (not (string-match "\\S-" (buffer-substring eol eos))))
  6299. (or has-children
  6300. (not (setq children-skipped
  6301. org-cycle-skip-children-state-if-no-children))))
  6302. ;; Entire subtree is hidden in one line: children view
  6303. (unless (org-before-first-heading-p)
  6304. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6305. (if (org-at-item-p)
  6306. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6307. (org-show-entry)
  6308. (org-with-limited-levels (org-show-children))
  6309. (org-show-set-visibility 'canonical)
  6310. ;; Fold every list in subtree to top-level items.
  6311. (when (eq org-cycle-include-plain-lists 'integrate)
  6312. (save-excursion
  6313. (org-back-to-heading)
  6314. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6315. (beginning-of-line 1)
  6316. (let* ((struct (org-list-struct))
  6317. (prevs (org-list-prevs-alist struct))
  6318. (end (org-list-get-bottom-point struct)))
  6319. (dolist (e (org-list-get-all-items (point) struct prevs))
  6320. (org-list-set-item-visibility e struct 'folded))
  6321. (goto-char (if (< end eos) end eos)))))))
  6322. (org-unlogged-message "CHILDREN")
  6323. (save-excursion
  6324. (goto-char eos)
  6325. (outline-next-heading)
  6326. (when (org-invisible-p) (org-flag-heading nil)))
  6327. (setq org-cycle-subtree-status 'children)
  6328. (unless (org-before-first-heading-p)
  6329. (run-hook-with-args 'org-cycle-hook 'children)))
  6330. ((or children-skipped
  6331. (and (eq last-command this-command)
  6332. (eq org-cycle-subtree-status 'children)))
  6333. ;; We just showed the children, or no children are there,
  6334. ;; now show everything.
  6335. (unless (org-before-first-heading-p)
  6336. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6337. (org-flag-region eoh eos nil 'outline)
  6338. (org-unlogged-message
  6339. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6340. (setq org-cycle-subtree-status 'subtree)
  6341. (unless (org-before-first-heading-p)
  6342. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6343. (t
  6344. ;; Default action: hide the subtree.
  6345. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6346. (org-flag-region eoh eos t 'outline)
  6347. (org-unlogged-message "FOLDED")
  6348. (setq org-cycle-subtree-status 'folded)
  6349. (unless (org-before-first-heading-p)
  6350. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6351. ;;;###autoload
  6352. (defun org-global-cycle (&optional arg)
  6353. "Cycle the global visibility. For details see `org-cycle'.
  6354. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6355. With a numeric prefix, show all headlines up to that level."
  6356. (interactive "P")
  6357. (let ((org-cycle-include-plain-lists
  6358. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6359. (cond
  6360. ((integerp arg)
  6361. (org-show-all '(headings blocks))
  6362. (outline-hide-sublevels arg)
  6363. (setq org-cycle-global-status 'contents))
  6364. ((equal arg '(4))
  6365. (org-set-startup-visibility)
  6366. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6367. (t
  6368. (org-cycle '(4))))))
  6369. (defun org-set-startup-visibility ()
  6370. "Set the visibility required by startup options and properties."
  6371. (cond
  6372. ((eq org-startup-folded t)
  6373. (org-overview))
  6374. ((eq org-startup-folded 'content)
  6375. (org-content))
  6376. ((or (eq org-startup-folded 'showeverything)
  6377. (eq org-startup-folded nil))
  6378. (org-show-all)))
  6379. (unless (eq org-startup-folded 'showeverything)
  6380. (when org-hide-block-startup (org-hide-block-all))
  6381. (org-set-visibility-according-to-property)
  6382. (org-cycle-hide-archived-subtrees 'all)
  6383. (org-cycle-hide-drawers 'all)
  6384. (org-cycle-show-empty-lines t)))
  6385. (defun org-set-visibility-according-to-property ()
  6386. "Switch subtree visibilities according to :VISIBILITY: property."
  6387. (interactive)
  6388. (org-with-wide-buffer
  6389. (goto-char (point-min))
  6390. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6391. (if (not (org-at-property-p)) (outline-next-heading)
  6392. (let ((state (match-string 3)))
  6393. (save-excursion
  6394. (org-back-to-heading t)
  6395. (outline-hide-subtree)
  6396. (org-reveal)
  6397. (cond
  6398. ((equal state "folded")
  6399. (outline-hide-subtree))
  6400. ((equal state "children")
  6401. (org-show-hidden-entry)
  6402. (org-show-children))
  6403. ((equal state "content")
  6404. (save-excursion
  6405. (save-restriction
  6406. (org-narrow-to-subtree)
  6407. (org-content))))
  6408. ((member state '("all" "showall"))
  6409. (outline-show-subtree)))))))))
  6410. (defun org-overview ()
  6411. "Switch to overview mode, showing only top-level headlines.
  6412. This shows all headlines with a level equal or greater than the level
  6413. of the first headline in the buffer. This is important, because if the
  6414. first headline is not level one, then (hide-sublevels 1) gives confusing
  6415. results."
  6416. (interactive)
  6417. (save-excursion
  6418. (let ((level
  6419. (save-excursion
  6420. (goto-char (point-min))
  6421. (when (re-search-forward org-outline-regexp-bol nil t)
  6422. (goto-char (match-beginning 0))
  6423. (funcall outline-level)))))
  6424. (and level (outline-hide-sublevels level)))))
  6425. (defun org-content (&optional arg)
  6426. "Show all headlines in the buffer, like a table of contents.
  6427. With numerical argument N, show content up to level N."
  6428. (interactive "P")
  6429. (org-overview)
  6430. (save-excursion
  6431. ;; Visit all headings and show their offspring
  6432. (and (integerp arg) (org-overview))
  6433. (goto-char (point-max))
  6434. (catch 'exit
  6435. (while (and (progn (condition-case nil
  6436. (outline-previous-visible-heading 1)
  6437. (error (goto-char (point-min))))
  6438. t)
  6439. (looking-at org-outline-regexp))
  6440. (if (integerp arg)
  6441. (org-show-children (1- arg))
  6442. (outline-show-branches))
  6443. (when (bobp) (throw 'exit nil))))))
  6444. (defun org-optimize-window-after-visibility-change (state)
  6445. "Adjust the window after a change in outline visibility.
  6446. This function is the default value of the hook `org-cycle-hook'."
  6447. (when (get-buffer-window (current-buffer))
  6448. (cond
  6449. ((eq state 'content) nil)
  6450. ((eq state 'all) nil)
  6451. ((eq state 'folded) nil)
  6452. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6453. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6454. (defun org-clean-visibility-after-subtree-move ()
  6455. "Fix visibility issues after moving a subtree."
  6456. ;; First, find a reasonable region to look at:
  6457. ;; Start two siblings above, end three below
  6458. (let* ((beg (save-excursion
  6459. (and (org-get-last-sibling)
  6460. (org-get-last-sibling))
  6461. (point)))
  6462. (end (save-excursion
  6463. (and (org-get-next-sibling)
  6464. (org-get-next-sibling)
  6465. (org-get-next-sibling))
  6466. (if (org-at-heading-p)
  6467. (point-at-eol)
  6468. (point))))
  6469. (level (looking-at "\\*+"))
  6470. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6471. (save-excursion
  6472. (save-restriction
  6473. (narrow-to-region beg end)
  6474. (when re
  6475. ;; Properly fold already folded siblings
  6476. (goto-char (point-min))
  6477. (while (re-search-forward re nil t)
  6478. (when (and (not (org-invisible-p))
  6479. (org-invisible-p (line-end-position)))
  6480. (outline-hide-entry))))
  6481. (org-cycle-hide-drawers 'all)
  6482. (org-cycle-show-empty-lines 'overview)))))
  6483. (defun org-cycle-show-empty-lines (state)
  6484. "Show empty lines above all visible headlines.
  6485. The region to be covered depends on STATE when called through
  6486. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6487. entire buffer covered. Note that an empty line is only shown if there
  6488. are at least `org-cycle-separator-lines' empty lines before the headline."
  6489. (when (/= org-cycle-separator-lines 0)
  6490. (save-excursion
  6491. (let* ((n (abs org-cycle-separator-lines))
  6492. (re (cond
  6493. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6494. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6495. (t (let ((ns (number-to-string (- n 2))))
  6496. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6497. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6498. beg end)
  6499. (cond
  6500. ((memq state '(overview contents t))
  6501. (setq beg (point-min) end (point-max)))
  6502. ((memq state '(children folded))
  6503. (setq beg (point)
  6504. end (progn (org-end-of-subtree t t)
  6505. (line-beginning-position 2)))))
  6506. (when beg
  6507. (goto-char beg)
  6508. (while (re-search-forward re end t)
  6509. (unless (get-char-property (match-end 1) 'invisible)
  6510. (let ((e (match-end 1))
  6511. (b (if (>= org-cycle-separator-lines 0)
  6512. (match-beginning 1)
  6513. (save-excursion
  6514. (goto-char (match-beginning 0))
  6515. (skip-chars-backward " \t\n")
  6516. (line-end-position)))))
  6517. (org-flag-region b e nil 'outline))))))))
  6518. ;; Never hide empty lines at the end of the file.
  6519. (save-excursion
  6520. (goto-char (point-max))
  6521. (outline-previous-heading)
  6522. (outline-end-of-heading)
  6523. (when (and (looking-at "[ \t\n]+")
  6524. (= (match-end 0) (point-max)))
  6525. (org-flag-region (point) (match-end 0) nil 'outline))))
  6526. ;;;; Reveal point location
  6527. (defun org-show-context (&optional key)
  6528. "Make sure point and context are visible.
  6529. Optional argument KEY, when non-nil, is a symbol. See
  6530. `org-show-context-detail' for allowed values and how much is to
  6531. be shown."
  6532. (org-show-set-visibility
  6533. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  6534. ((cdr (assq key org-show-context-detail)))
  6535. (t (cdr (assq 'default org-show-context-detail))))))
  6536. (defun org-show-set-visibility (detail)
  6537. "Set visibility around point according to DETAIL.
  6538. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  6539. `tree', `canonical' or t. See `org-show-context-detail' for more
  6540. information."
  6541. ;; Show current heading and possibly its entry, following headline
  6542. ;; or all children.
  6543. (if (and (org-at-heading-p) (not (eq detail 'local)))
  6544. (org-flag-heading nil)
  6545. (org-show-entry)
  6546. ;; If point is hidden within a drawer or a block, make sure to
  6547. ;; expose it.
  6548. (dolist (o (overlays-at (point)))
  6549. (when (memq (overlay-get o 'invisible)
  6550. '(org-hide-block org-hide-drawer outline))
  6551. (delete-overlay o)))
  6552. (unless (org-before-first-heading-p)
  6553. (org-with-limited-levels
  6554. (cl-case detail
  6555. ((tree canonical t) (org-show-children))
  6556. ((nil minimal ancestors))
  6557. (t (save-excursion
  6558. (outline-next-heading)
  6559. (org-flag-heading nil)))))))
  6560. ;; Show all siblings.
  6561. (when (eq detail 'lineage) (org-show-siblings))
  6562. ;; Show ancestors, possibly with their children.
  6563. (when (memq detail '(ancestors lineage tree canonical t))
  6564. (save-excursion
  6565. (while (org-up-heading-safe)
  6566. (org-flag-heading nil)
  6567. (when (memq detail '(canonical t)) (org-show-entry))
  6568. (when (memq detail '(tree canonical t)) (org-show-children))))))
  6569. (defvar org-reveal-start-hook nil
  6570. "Hook run before revealing a location.")
  6571. (defun org-reveal (&optional siblings)
  6572. "Show current entry, hierarchy above it, and the following headline.
  6573. This can be used to show a consistent set of context around
  6574. locations exposed with `org-show-context'.
  6575. With optional argument SIBLINGS, on each level of the hierarchy all
  6576. siblings are shown. This repairs the tree structure to what it would
  6577. look like when opened with hierarchical calls to `org-cycle'.
  6578. With a \\[universal-argument] \\[universal-argument] prefix, \
  6579. go to the parent and show the entire tree."
  6580. (interactive "P")
  6581. (run-hooks 'org-reveal-start-hook)
  6582. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6583. ((equal siblings '(16))
  6584. (save-excursion
  6585. (when (org-up-heading-safe)
  6586. (org-show-subtree)
  6587. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6588. (t (org-show-set-visibility 'lineage))))
  6589. ;;; Indirect buffer display of subtrees
  6590. (defvar org-indirect-dedicated-frame nil
  6591. "This is the frame being used for indirect tree display.")
  6592. (defvar org-last-indirect-buffer nil)
  6593. (defun org-tree-to-indirect-buffer (&optional arg)
  6594. "Create indirect buffer and narrow it to current subtree.
  6595. With a numerical prefix ARG, go up to this level and then take that tree.
  6596. If ARG is negative, go up that many levels.
  6597. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6598. indirect buffer previously made with this command, to avoid proliferation of
  6599. indirect buffers. However, when you call the command with a \
  6600. `\\[universal-argument]' prefix, or
  6601. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6602. so that you can work with several indirect buffers at the same time. If
  6603. `org-indirect-buffer-display' is `dedicated-frame', the \
  6604. `\\[universal-argument]' prefix also
  6605. requests that a new frame be made for the new buffer, so that the dedicated
  6606. frame is not changed."
  6607. (interactive "P")
  6608. (let ((cbuf (current-buffer))
  6609. (cwin (selected-window))
  6610. (pos (point))
  6611. beg end level heading ibuf)
  6612. (save-excursion
  6613. (org-back-to-heading t)
  6614. (when (numberp arg)
  6615. (setq level (org-outline-level))
  6616. (when (< arg 0) (setq arg (+ level arg)))
  6617. (while (> (setq level (org-outline-level)) arg)
  6618. (org-up-heading-safe)))
  6619. (setq beg (point)
  6620. heading (org-get-heading 'no-tags))
  6621. (org-end-of-subtree t t)
  6622. (when (org-at-heading-p) (backward-char 1))
  6623. (setq end (point)))
  6624. (when (and (buffer-live-p org-last-indirect-buffer)
  6625. (not (eq org-indirect-buffer-display 'new-frame))
  6626. (not arg))
  6627. (kill-buffer org-last-indirect-buffer))
  6628. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6629. org-last-indirect-buffer ibuf)
  6630. (cond
  6631. ((or (eq org-indirect-buffer-display 'new-frame)
  6632. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6633. (select-frame (make-frame))
  6634. (delete-other-windows)
  6635. (pop-to-buffer-same-window ibuf)
  6636. (org-set-frame-title heading))
  6637. ((eq org-indirect-buffer-display 'dedicated-frame)
  6638. (raise-frame
  6639. (select-frame (or (and org-indirect-dedicated-frame
  6640. (frame-live-p org-indirect-dedicated-frame)
  6641. org-indirect-dedicated-frame)
  6642. (setq org-indirect-dedicated-frame (make-frame)))))
  6643. (delete-other-windows)
  6644. (pop-to-buffer-same-window ibuf)
  6645. (org-set-frame-title (concat "Indirect: " heading)))
  6646. ((eq org-indirect-buffer-display 'current-window)
  6647. (pop-to-buffer-same-window ibuf))
  6648. ((eq org-indirect-buffer-display 'other-window)
  6649. (pop-to-buffer ibuf))
  6650. (t (error "Invalid value")))
  6651. (narrow-to-region beg end)
  6652. (org-show-all '(headings blocks))
  6653. (goto-char pos)
  6654. (run-hook-with-args 'org-cycle-hook 'all)
  6655. (and (window-live-p cwin) (select-window cwin))))
  6656. (defun org-get-indirect-buffer (&optional buffer heading)
  6657. (setq buffer (or buffer (current-buffer)))
  6658. (let ((n 1) (base (buffer-name buffer)) bname)
  6659. (while (buffer-live-p
  6660. (get-buffer
  6661. (setq bname
  6662. (concat base "-"
  6663. (if heading (concat heading "-" (number-to-string n))
  6664. (number-to-string n))))))
  6665. (setq n (1+ n)))
  6666. (condition-case nil
  6667. (make-indirect-buffer buffer bname 'clone)
  6668. (error (make-indirect-buffer buffer bname)))))
  6669. (defun org-set-frame-title (title)
  6670. "Set the title of the current frame to the string TITLE."
  6671. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6672. ;;;; Structure editing
  6673. ;;; Inserting headlines
  6674. (defun org--line-empty-p (n)
  6675. "Is the Nth next line empty?
  6676. Counts the current line as N = 1 and the previous line as N = 0;
  6677. see `beginning-of-line'."
  6678. (save-excursion
  6679. (and (not (bobp))
  6680. (or (beginning-of-line n) t)
  6681. (save-match-data
  6682. (looking-at "[ \t]*$")))))
  6683. (defun org-previous-line-empty-p ()
  6684. "Is the previous line a blank line?
  6685. When NEXT is non-nil, check the next line instead."
  6686. (org--line-empty-p 0))
  6687. (defun org-next-line-empty-p ()
  6688. "Is the previous line a blank line?
  6689. When NEXT is non-nil, check the next line instead."
  6690. (org--line-empty-p 2))
  6691. (defun org--blank-before-heading-p (&optional parent)
  6692. "Non-nil when an empty line should precede a new heading here.
  6693. When optional argument PARENT is non-nil, consider parent
  6694. headline instead of current one."
  6695. (pcase (assq 'heading org-blank-before-new-entry)
  6696. (`(heading . auto)
  6697. (save-excursion
  6698. (org-with-limited-levels
  6699. (unless (and (org-before-first-heading-p)
  6700. (not (outline-next-heading)))
  6701. (org-back-to-heading t)
  6702. (when parent (org-up-heading-safe))
  6703. (cond ((not (bobp))
  6704. (org-previous-line-empty-p))
  6705. ((outline-next-heading)
  6706. (org-previous-line-empty-p))
  6707. ;; Ignore trailing spaces on last buffer line.
  6708. ((progn (skip-chars-backward " \t") (bolp))
  6709. (org-previous-line-empty-p))
  6710. (t nil))))))
  6711. (`(heading . ,value) value)
  6712. (_ nil)))
  6713. (defun org-insert-heading (&optional arg invisible-ok top)
  6714. "Insert a new heading or an item with the same depth at point.
  6715. If point is at the beginning of a heading, insert a new heading
  6716. or a new headline above the current one. When at the beginning
  6717. of a regular line of text, turn it into a heading.
  6718. If point is in the middle of a line, split it and create a new
  6719. headline with the text in the current line after point (see
  6720. `org-M-RET-may-split-line' on how to modify this behavior). As
  6721. a special case, on a headline, splitting can only happen on the
  6722. title itself. E.g., this excludes breaking stars or tags.
  6723. With a `\\[universal-argument]' prefix, set \
  6724. `org-insert-heading-respect-content' to
  6725. a non-nil value for the duration of the command. This forces the
  6726. insertion of a heading after the current subtree, independently
  6727. on the location of point.
  6728. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6729. insert the heading at the end of the tree
  6730. above the current heading. For example, if point is within a
  6731. 2nd-level heading, then it will insert a 2nd-level heading at
  6732. the end of the 1st-level parent subtree.
  6733. When INVISIBLE-OK is set, stop at invisible headlines when going
  6734. back. This is important for non-interactive uses of the
  6735. command.
  6736. When optional argument TOP is non-nil, insert a level 1 heading,
  6737. unconditionally."
  6738. (interactive "P")
  6739. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6740. (level (org-current-level))
  6741. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6742. (cond
  6743. ((or org-insert-heading-respect-content
  6744. (member arg '((4) (16)))
  6745. (and (not invisible-ok)
  6746. (invisible-p (max (1- (point)) (point-min)))))
  6747. ;; Position point at the location of insertion.
  6748. (if (not level) ;before first headline
  6749. (org-with-limited-levels (outline-next-heading))
  6750. ;; Make sure we end up on a visible headline if INVISIBLE-OK
  6751. ;; is nil.
  6752. (org-with-limited-levels (org-back-to-heading invisible-ok))
  6753. (cond ((equal arg '(16))
  6754. (org-up-heading-safe)
  6755. (org-end-of-subtree t t))
  6756. (t
  6757. (org-end-of-subtree t t))))
  6758. (unless (bolp) (insert "\n")) ;ensure final newline
  6759. (unless (and blank? (org-previous-line-empty-p))
  6760. (org-N-empty-lines-before-current (if blank? 1 0)))
  6761. (insert stars " \n")
  6762. (forward-char -1))
  6763. ;; At a headline...
  6764. ((org-at-heading-p)
  6765. (cond ((bolp)
  6766. (when blank? (save-excursion (insert "\n")))
  6767. (save-excursion (insert stars " \n"))
  6768. (unless (and blank? (org-previous-line-empty-p))
  6769. (org-N-empty-lines-before-current (if blank? 1 0)))
  6770. (end-of-line))
  6771. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6772. (org-match-line org-complex-heading-regexp)
  6773. (org-pos-in-match-range (point) 4))
  6774. ;; Grab the text that should moved to the new headline.
  6775. ;; Preserve tags.
  6776. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6777. (if (looking-at "[ \t]*$") (replace-match "")
  6778. (org-align-tags))
  6779. (end-of-line)
  6780. (when blank? (insert "\n"))
  6781. (insert "\n" stars " ")
  6782. (when (org-string-nw-p split) (insert split))
  6783. (when (eobp) (save-excursion (insert "\n")))))
  6784. (t
  6785. (end-of-line)
  6786. (when blank? (insert "\n"))
  6787. (insert "\n" stars " ")
  6788. (when (eobp) (save-excursion (insert "\n"))))))
  6789. ;; On regular text, turn line into a headline or split, if
  6790. ;; appropriate.
  6791. ((bolp)
  6792. (insert stars " ")
  6793. (unless (and blank? (org-previous-line-empty-p))
  6794. (org-N-empty-lines-before-current (if blank? 1 0))))
  6795. (t
  6796. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6797. (end-of-line))
  6798. (insert "\n" stars " ")
  6799. (unless (and blank? (org-previous-line-empty-p))
  6800. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6801. (run-hooks 'org-insert-heading-hook))
  6802. (defun org-N-empty-lines-before-current (n)
  6803. "Make the number of empty lines before current exactly N.
  6804. So this will delete or add empty lines."
  6805. (let ((column (current-column)))
  6806. (beginning-of-line)
  6807. (unless (bobp)
  6808. (let ((start (save-excursion
  6809. (skip-chars-backward " \r\t\n")
  6810. (line-end-position))))
  6811. (delete-region start (line-end-position 0))))
  6812. (insert (make-string n ?\n))
  6813. (move-to-column column)))
  6814. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6815. "Return the heading of the current entry, without the stars.
  6816. When NO-TAGS is non-nil, don't include tags.
  6817. When NO-TODO is non-nil, don't include TODO keywords.
  6818. When NO-PRIORITY is non-nil, don't include priority cookie.
  6819. When NO-COMMENT is non-nil, don't include COMMENT string.
  6820. Return nil before first heading."
  6821. (unless (org-before-first-heading-p)
  6822. (save-excursion
  6823. (org-back-to-heading t)
  6824. (let ((case-fold-search nil))
  6825. (looking-at org-complex-heading-regexp)
  6826. (let ((todo (and (not no-todo) (match-string 2)))
  6827. (priority (and (not no-priority) (match-string 3)))
  6828. (headline (pcase (match-string 4)
  6829. (`nil "")
  6830. ((and (guard no-comment) h)
  6831. (replace-regexp-in-string
  6832. (eval-when-compile
  6833. (format "\\`%s[ \t]+" org-comment-string))
  6834. "" h))
  6835. (h h)))
  6836. (tags (and (not no-tags) (match-string 5))))
  6837. (mapconcat #'identity
  6838. (delq nil (list todo priority headline tags))
  6839. " "))))))
  6840. (defun org-heading-components ()
  6841. "Return the components of the current heading.
  6842. This is a list with the following elements:
  6843. - the level as an integer
  6844. - the reduced level, different if `org-odd-levels-only' is set.
  6845. - the TODO keyword, or nil
  6846. - the priority character, like ?A, or nil if no priority is given
  6847. - the headline text itself, or the tags string if no headline text
  6848. - the tags string, or nil."
  6849. (save-excursion
  6850. (org-back-to-heading t)
  6851. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6852. (list (length (match-string 1))
  6853. (org-reduced-level (length (match-string 1)))
  6854. (match-string-no-properties 2)
  6855. (and (match-end 3) (aref (match-string 3) 2))
  6856. (match-string-no-properties 4)
  6857. (match-string-no-properties 5)))))
  6858. (defun org-get-entry ()
  6859. "Get the entry text, after heading, entire subtree."
  6860. (save-excursion
  6861. (org-back-to-heading t)
  6862. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6863. (defun org-edit-headline (&optional heading)
  6864. "Edit the current headline.
  6865. Set it to HEADING when provided."
  6866. (interactive)
  6867. (org-with-wide-buffer
  6868. (org-back-to-heading t)
  6869. (let ((case-fold-search nil))
  6870. (when (looking-at org-complex-heading-regexp)
  6871. (let* ((old (match-string-no-properties 4))
  6872. (new (save-match-data
  6873. (org-trim (or heading (read-string "Edit: " old))))))
  6874. (unless (equal old new)
  6875. (if old (replace-match new t t nil 4)
  6876. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6877. (insert " " new))
  6878. (org-align-tags)
  6879. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6880. (defun org-insert-heading-after-current ()
  6881. "Insert a new heading with same level as current, after current subtree."
  6882. (interactive)
  6883. (org-back-to-heading)
  6884. (org-insert-heading)
  6885. (org-move-subtree-down)
  6886. (end-of-line 1))
  6887. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6888. "Insert heading with `org-insert-heading-respect-content' set to t."
  6889. (interactive)
  6890. (org-insert-heading '(4) invisible-ok))
  6891. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6892. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6893. (interactive)
  6894. (org-insert-todo-heading force-state '(4)))
  6895. (defun org-insert-todo-heading (arg &optional force-heading)
  6896. "Insert a new heading with the same level and TODO state as current heading.
  6897. If the heading has no TODO state, or if the state is DONE, use
  6898. the first state (TODO by default). Also with one prefix arg,
  6899. force first state. With two prefix args, force inserting at the
  6900. end of the parent subtree.
  6901. When called at a plain list item, insert a new item with an
  6902. unchecked check box."
  6903. (interactive "P")
  6904. (when (or force-heading (not (org-insert-item 'checkbox)))
  6905. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6906. force-heading))
  6907. (save-excursion
  6908. (org-forward-heading-same-level -1)
  6909. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6910. (let* ((new-mark-x
  6911. (if (or (equal arg '(4))
  6912. (not (match-beginning 2))
  6913. (member (match-string 2) org-done-keywords))
  6914. (car org-todo-keywords-1)
  6915. (match-string 2)))
  6916. (new-mark
  6917. (or
  6918. (run-hook-with-args-until-success
  6919. 'org-todo-get-default-hook new-mark-x nil)
  6920. new-mark-x)))
  6921. (beginning-of-line 1)
  6922. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6923. (if org-treat-insert-todo-heading-as-state-change
  6924. (org-todo new-mark)
  6925. (insert new-mark " "))))
  6926. (when org-provide-todo-statistics
  6927. (org-update-parent-todo-statistics))))
  6928. (defun org-insert-subheading (arg)
  6929. "Insert a new subheading and demote it.
  6930. Works for outline headings and for plain lists alike."
  6931. (interactive "P")
  6932. (org-insert-heading arg)
  6933. (cond
  6934. ((org-at-heading-p) (org-do-demote))
  6935. ((org-at-item-p) (org-indent-item))))
  6936. (defun org-insert-todo-subheading (arg)
  6937. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6938. Works for outline headings and for plain lists alike."
  6939. (interactive "P")
  6940. (org-insert-todo-heading arg)
  6941. (cond
  6942. ((org-at-heading-p) (org-do-demote))
  6943. ((org-at-item-p) (org-indent-item))))
  6944. ;;; Promotion and Demotion
  6945. (defvar org-after-demote-entry-hook nil
  6946. "Hook run after an entry has been demoted.
  6947. The cursor will be at the beginning of the entry.
  6948. When a subtree is being demoted, the hook will be called for each node.")
  6949. (defvar org-after-promote-entry-hook nil
  6950. "Hook run after an entry has been promoted.
  6951. The cursor will be at the beginning of the entry.
  6952. When a subtree is being promoted, the hook will be called for each node.")
  6953. (defun org-promote-subtree ()
  6954. "Promote the entire subtree.
  6955. See also `org-promote'."
  6956. (interactive)
  6957. (save-excursion
  6958. (org-with-limited-levels (org-map-tree 'org-promote)))
  6959. (org-fix-position-after-promote))
  6960. (defun org-demote-subtree ()
  6961. "Demote the entire subtree.
  6962. See `org-demote' and `org-promote'."
  6963. (interactive)
  6964. (save-excursion
  6965. (org-with-limited-levels (org-map-tree 'org-demote)))
  6966. (org-fix-position-after-promote))
  6967. (defun org-do-promote ()
  6968. "Promote the current heading higher up the tree.
  6969. If the region is active in `transient-mark-mode', promote all
  6970. headings in the region."
  6971. (interactive)
  6972. (save-excursion
  6973. (if (org-region-active-p)
  6974. (org-map-region 'org-promote (region-beginning) (region-end))
  6975. (org-promote)))
  6976. (org-fix-position-after-promote))
  6977. (defun org-do-demote ()
  6978. "Demote the current heading lower down the tree.
  6979. If the region is active in `transient-mark-mode', demote all
  6980. headings in the region."
  6981. (interactive)
  6982. (save-excursion
  6983. (if (org-region-active-p)
  6984. (org-map-region 'org-demote (region-beginning) (region-end))
  6985. (org-demote)))
  6986. (org-fix-position-after-promote))
  6987. (defun org-fix-position-after-promote ()
  6988. "Fix cursor position and indentation after demoting/promoting."
  6989. (let ((pos (point)))
  6990. (when (save-excursion
  6991. (beginning-of-line)
  6992. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6993. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6994. (cond ((eobp) (insert " "))
  6995. ((eolp) (insert " "))
  6996. ((equal (char-after) ?\s) (forward-char 1))))))
  6997. (defun org-current-level ()
  6998. "Return the level of the current entry, or nil if before the first headline.
  6999. The level is the number of stars at the beginning of the
  7000. headline. Use `org-reduced-level' to remove the effect of
  7001. `org-odd-levels'. Unlike to `org-outline-level', this function
  7002. ignores inlinetasks."
  7003. (let ((level (org-with-limited-levels (org-outline-level))))
  7004. (and (> level 0) level)))
  7005. (defun org-get-previous-line-level ()
  7006. "Return the outline depth of the last headline before the current line.
  7007. Returns 0 for the first headline in the buffer, and nil if before the
  7008. first headline."
  7009. (and (org-current-level)
  7010. (or (and (/= (line-beginning-position) (point-min))
  7011. (save-excursion (beginning-of-line 0) (org-current-level)))
  7012. 0)))
  7013. (defun org-reduced-level (l)
  7014. "Compute the effective level of a heading.
  7015. This takes into account the setting of `org-odd-levels-only'."
  7016. (cond
  7017. ((zerop l) 0)
  7018. (org-odd-levels-only (1+ (floor (/ l 2))))
  7019. (t l)))
  7020. (defun org-level-increment ()
  7021. "Return the number of stars that will be added or removed at a
  7022. time to headlines when structure editing, based on the value of
  7023. `org-odd-levels-only'."
  7024. (if org-odd-levels-only 2 1))
  7025. (defun org-get-valid-level (level &optional change)
  7026. "Rectify a level change under the influence of `org-odd-levels-only'.
  7027. LEVEL is a current level, CHANGE is by how much the level should
  7028. be modified. Even if CHANGE is nil, LEVEL may be returned
  7029. modified because even level numbers will become the next higher
  7030. odd number. Returns values greater than 0."
  7031. (if org-odd-levels-only
  7032. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7033. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  7034. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7035. (max 1 (+ level (or change 0)))))
  7036. (defun org-promote ()
  7037. "Promote the current heading higher up the tree."
  7038. (org-with-wide-buffer
  7039. (org-back-to-heading t)
  7040. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7041. after-change-functions))
  7042. (level (save-match-data (funcall outline-level)))
  7043. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7044. (diff (abs (- level (length up-head) -1))))
  7045. (cond
  7046. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7047. (replace-match "# " nil t))
  7048. ((= level 1)
  7049. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7050. (t (replace-match up-head nil t)))
  7051. (unless (= level 1)
  7052. (when org-auto-align-tags (org-align-tags))
  7053. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7054. (run-hooks 'org-after-promote-entry-hook))))
  7055. (defun org-demote ()
  7056. "Demote the current heading lower down the tree."
  7057. (org-with-wide-buffer
  7058. (org-back-to-heading t)
  7059. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7060. after-change-functions))
  7061. (level (save-match-data (funcall outline-level)))
  7062. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7063. (diff (abs (- level (length down-head) -1))))
  7064. (replace-match down-head nil t)
  7065. (when org-auto-align-tags (org-align-tags))
  7066. (when org-adapt-indentation (org-fixup-indentation diff))
  7067. (run-hooks 'org-after-demote-entry-hook))))
  7068. (defun org-cycle-level ()
  7069. "Cycle the level of an empty headline through possible states.
  7070. This goes first to child, then to parent, level, then up the hierarchy.
  7071. After top level, it switches back to sibling level."
  7072. (interactive)
  7073. (let ((org-adapt-indentation nil))
  7074. (when (org-point-at-end-of-empty-headline)
  7075. (setq this-command 'org-cycle-level) ; Only needed for caching
  7076. (let ((cur-level (org-current-level))
  7077. (prev-level (org-get-previous-line-level)))
  7078. (cond
  7079. ;; If first headline in file, promote to top-level.
  7080. ((= prev-level 0)
  7081. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7082. do (org-do-promote)))
  7083. ;; If same level as prev, demote one.
  7084. ((= prev-level cur-level)
  7085. (org-do-demote))
  7086. ;; If parent is top-level, promote to top level if not already.
  7087. ((= prev-level 1)
  7088. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7089. do (org-do-promote)))
  7090. ;; If top-level, return to prev-level.
  7091. ((= cur-level 1)
  7092. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7093. do (org-do-demote)))
  7094. ;; If less than prev-level, promote one.
  7095. ((< cur-level prev-level)
  7096. (org-do-promote))
  7097. ;; If deeper than prev-level, promote until higher than
  7098. ;; prev-level.
  7099. ((> cur-level prev-level)
  7100. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7101. do (org-do-promote))))
  7102. t))))
  7103. (defun org-map-tree (fun)
  7104. "Call FUN for every heading underneath the current one."
  7105. (org-back-to-heading t)
  7106. (let ((level (funcall outline-level)))
  7107. (save-excursion
  7108. (funcall fun)
  7109. (while (and (progn
  7110. (outline-next-heading)
  7111. (> (funcall outline-level) level))
  7112. (not (eobp)))
  7113. (funcall fun)))))
  7114. (defun org-map-region (fun beg end)
  7115. "Call FUN for every heading between BEG and END."
  7116. (let ((org-ignore-region t))
  7117. (save-excursion
  7118. (setq end (copy-marker end))
  7119. (goto-char beg)
  7120. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7121. (< (point) end))
  7122. (funcall fun))
  7123. (while (and (progn
  7124. (outline-next-heading)
  7125. (< (point) end))
  7126. (not (eobp)))
  7127. (funcall fun)))))
  7128. (defun org-fixup-indentation (diff)
  7129. "Change the indentation in the current entry by DIFF.
  7130. DIFF is an integer. Indentation is done according to the
  7131. following rules:
  7132. - Planning information and property drawers are always indented
  7133. according to the new level of the headline;
  7134. - Footnote definitions and their contents are ignored;
  7135. - Inlinetasks' boundaries are not shifted;
  7136. - Empty lines are ignored;
  7137. - Other lines' indentation are shifted by DIFF columns, unless
  7138. it would introduce a structural change in the document, in
  7139. which case no shifting is done at all.
  7140. Assume point is at a heading or an inlinetask beginning."
  7141. (org-with-wide-buffer
  7142. (narrow-to-region (line-beginning-position)
  7143. (save-excursion
  7144. (if (org-with-limited-levels (org-at-heading-p))
  7145. (org-with-limited-levels (outline-next-heading))
  7146. (org-inlinetask-goto-end))
  7147. (point)))
  7148. (forward-line)
  7149. ;; Indent properly planning info and property drawer.
  7150. (when (looking-at-p org-planning-line-re)
  7151. (org-indent-line)
  7152. (forward-line))
  7153. (when (looking-at org-property-drawer-re)
  7154. (goto-char (match-end 0))
  7155. (forward-line)
  7156. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7157. (catch 'no-shift
  7158. (when (zerop diff) (throw 'no-shift nil))
  7159. ;; If DIFF is negative, first check if a shift is possible at all
  7160. ;; (e.g., it doesn't break structure). This can only happen if
  7161. ;; some contents are not properly indented.
  7162. (let ((case-fold-search t))
  7163. (when (< diff 0)
  7164. (let ((diff (- diff))
  7165. (forbidden-re (concat org-outline-regexp
  7166. "\\|"
  7167. (substring org-footnote-definition-re 1))))
  7168. (save-excursion
  7169. (while (not (eobp))
  7170. (cond
  7171. ((looking-at-p "[ \t]*$") (forward-line))
  7172. ((and (looking-at-p org-footnote-definition-re)
  7173. (let ((e (org-element-at-point)))
  7174. (and (eq (org-element-type e) 'footnote-definition)
  7175. (goto-char (org-element-property :end e))))))
  7176. ((looking-at-p org-outline-regexp) (forward-line))
  7177. ;; Give up if shifting would move before column 0 or
  7178. ;; if it would introduce a headline or a footnote
  7179. ;; definition.
  7180. (t
  7181. (skip-chars-forward " \t")
  7182. (let ((ind (current-column)))
  7183. (when (or (< ind diff)
  7184. (and (= ind diff) (looking-at-p forbidden-re)))
  7185. (throw 'no-shift nil)))
  7186. ;; Ignore contents of example blocks and source
  7187. ;; blocks if their indentation is meant to be
  7188. ;; preserved. Jump to block's closing line.
  7189. (beginning-of-line)
  7190. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7191. (let ((e (org-element-at-point)))
  7192. (and (memq (org-element-type e)
  7193. '(example-block src-block))
  7194. (or org-src-preserve-indentation
  7195. (org-element-property :preserve-indent e))
  7196. (goto-char (org-element-property :end e))
  7197. (progn (skip-chars-backward " \r\t\n")
  7198. (beginning-of-line)
  7199. t))))
  7200. (forward-line))))))))
  7201. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7202. ;; by DIFF. Also skip contents of source or example blocks
  7203. ;; when indentation is meant to be preserved.
  7204. (while (not (eobp))
  7205. (cond
  7206. ((and (looking-at-p org-footnote-definition-re)
  7207. (let ((e (org-element-at-point)))
  7208. (and (eq (org-element-type e) 'footnote-definition)
  7209. (goto-char (org-element-property :end e))))))
  7210. ((looking-at-p org-outline-regexp) (forward-line))
  7211. ((looking-at-p "[ \t]*$") (forward-line))
  7212. (t
  7213. (indent-line-to (+ (current-indentation) diff))
  7214. (beginning-of-line)
  7215. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7216. (let ((e (org-element-at-point)))
  7217. (and (memq (org-element-type e)
  7218. '(example-block src-block))
  7219. (or org-src-preserve-indentation
  7220. (org-element-property :preserve-indent e))
  7221. (goto-char (org-element-property :end e))
  7222. (progn (skip-chars-backward " \r\t\n")
  7223. (beginning-of-line)
  7224. t))))
  7225. (forward-line)))))))))
  7226. (defun org-convert-to-odd-levels ()
  7227. "Convert an Org file with all levels allowed to one with odd levels.
  7228. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7229. level 5 etc."
  7230. (interactive)
  7231. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7232. (let ((outline-level 'org-outline-level)
  7233. (org-odd-levels-only nil) n)
  7234. (save-excursion
  7235. (goto-char (point-min))
  7236. (while (re-search-forward "^\\*\\*+ " nil t)
  7237. (setq n (- (length (match-string 0)) 2))
  7238. (while (>= (setq n (1- n)) 0)
  7239. (org-demote))
  7240. (end-of-line 1))))))
  7241. (defun org-convert-to-oddeven-levels ()
  7242. "Convert an Org file with only odd levels to one with odd/even levels.
  7243. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7244. file contains a section with an even level, conversion would
  7245. destroy the structure of the file. An error is signaled in this
  7246. case."
  7247. (interactive)
  7248. (goto-char (point-min))
  7249. ;; First check if there are no even levels
  7250. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7251. (org-show-set-visibility 'canonical)
  7252. (error "Not all levels are odd in this file. Conversion not possible"))
  7253. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7254. (let ((outline-regexp org-outline-regexp)
  7255. (outline-level 'org-outline-level)
  7256. (org-odd-levels-only nil) n)
  7257. (save-excursion
  7258. (goto-char (point-min))
  7259. (while (re-search-forward "^\\*\\*+ " nil t)
  7260. (setq n (/ (1- (length (match-string 0))) 2))
  7261. (while (>= (setq n (1- n)) 0)
  7262. (org-promote))
  7263. (end-of-line 1))))))
  7264. (defun org-tr-level (n)
  7265. "Make N odd if required."
  7266. (if org-odd-levels-only (1+ (/ n 2)) n))
  7267. ;;; Vertical tree motion, cutting and pasting of subtrees
  7268. (defun org-move-subtree-up (&optional arg)
  7269. "Move the current subtree up past ARG headlines of the same level."
  7270. (interactive "p")
  7271. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7272. (defun org-move-subtree-down (&optional arg)
  7273. "Move the current subtree down past ARG headlines of the same level."
  7274. (interactive "p")
  7275. (setq arg (prefix-numeric-value arg))
  7276. (org-preserve-local-variables
  7277. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7278. 'org-get-last-sibling))
  7279. (ins-point (make-marker))
  7280. (cnt (abs arg))
  7281. (col (current-column))
  7282. beg end txt folded)
  7283. ;; Select the tree
  7284. (org-back-to-heading)
  7285. (setq beg (point))
  7286. (save-match-data
  7287. (save-excursion (outline-end-of-heading)
  7288. (setq folded (org-invisible-p)))
  7289. (progn (org-end-of-subtree nil t)
  7290. (unless (eobp) (backward-char))))
  7291. (outline-next-heading)
  7292. (setq end (point))
  7293. (goto-char beg)
  7294. ;; Find insertion point, with error handling
  7295. (while (> cnt 0)
  7296. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  7297. (goto-char beg)
  7298. (user-error "Cannot move past superior level or buffer limit"))
  7299. (setq cnt (1- cnt)))
  7300. (when (> arg 0)
  7301. ;; Moving forward - still need to move over subtree
  7302. (org-end-of-subtree t t)
  7303. (save-excursion
  7304. (org-back-over-empty-lines)
  7305. (or (bolp) (newline))))
  7306. (move-marker ins-point (point))
  7307. (setq txt (buffer-substring beg end))
  7308. (org-save-markers-in-region beg end)
  7309. (delete-region beg end)
  7310. (org-remove-empty-overlays-at beg)
  7311. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  7312. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  7313. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7314. (let ((bbb (point)))
  7315. (insert-before-markers txt)
  7316. (org-reinstall-markers-in-region bbb)
  7317. (move-marker ins-point bbb))
  7318. (or (bolp) (insert "\n"))
  7319. (goto-char ins-point)
  7320. (org-skip-whitespace)
  7321. (move-marker ins-point nil)
  7322. (if folded
  7323. (outline-hide-subtree)
  7324. (org-show-entry)
  7325. (org-show-children))
  7326. (org-clean-visibility-after-subtree-move)
  7327. ;; move back to the initial column we were at
  7328. (move-to-column col))))
  7329. (defvar org-subtree-clip ""
  7330. "Clipboard for cut and paste of subtrees.
  7331. This is actually only a copy of the kill, because we use the normal kill
  7332. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7333. (defvar org-subtree-clip-folded nil
  7334. "Was the last copied subtree folded?
  7335. This is used to fold the tree back after pasting.")
  7336. (defun org-cut-subtree (&optional n)
  7337. "Cut the current subtree into the clipboard.
  7338. With prefix arg N, cut this many sequential subtrees.
  7339. This is a short-hand for marking the subtree and then cutting it."
  7340. (interactive "p")
  7341. (org-copy-subtree n 'cut))
  7342. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7343. "Copy the current subtree into the clipboard.
  7344. With prefix arg N, copy this many sequential subtrees.
  7345. This is a short-hand for marking the subtree and then copying it.
  7346. If CUT is non-nil, actually cut the subtree.
  7347. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7348. of some markers in the region, even if CUT is non-nil. This is
  7349. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7350. (interactive "p")
  7351. (org-preserve-local-variables
  7352. (let (beg end folded (beg0 (point)))
  7353. (if (called-interactively-p 'any)
  7354. (org-back-to-heading nil) ; take what looks like a subtree
  7355. (org-back-to-heading t)) ; take what is really there
  7356. (setq beg (point))
  7357. (skip-chars-forward " \t\r\n")
  7358. (save-match-data
  7359. (if nosubtrees
  7360. (outline-next-heading)
  7361. (save-excursion (outline-end-of-heading)
  7362. (setq folded (org-invisible-p)))
  7363. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7364. (org-end-of-subtree t t)))
  7365. ;; Include the end of an inlinetask
  7366. (when (and (featurep 'org-inlinetask)
  7367. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7368. "END[ \t]*$")))
  7369. (end-of-line))
  7370. (setq end (point))
  7371. (goto-char beg0)
  7372. (when (> end beg)
  7373. (setq org-subtree-clip-folded folded)
  7374. (when (or cut force-store-markers)
  7375. (org-save-markers-in-region beg end))
  7376. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7377. (setq org-subtree-clip (current-kill 0))
  7378. (message "%s: Subtree(s) with %d characters"
  7379. (if cut "Cut" "Copied")
  7380. (length org-subtree-clip))))))
  7381. (defun org-paste-subtree (&optional level tree for-yank remove)
  7382. "Paste the clipboard as a subtree, with modification of headline level.
  7383. The entire subtree is promoted or demoted in order to match a new headline
  7384. level.
  7385. If the cursor is at the beginning of a headline, the same level as
  7386. that headline is used to paste the tree.
  7387. If not, the new level is derived from the *visible* headings
  7388. before and after the insertion point, and taken to be the inferior headline
  7389. level of the two. So if the previous visible heading is level 3 and the
  7390. next is level 4 (or vice versa), level 4 will be used for insertion.
  7391. This makes sure that the subtree remains an independent subtree and does
  7392. not swallow low level entries.
  7393. You can also force a different level, either by using a numeric prefix
  7394. argument, or by inserting the heading marker by hand. For example, if the
  7395. cursor is after \"*****\", then the tree will be shifted to level 5.
  7396. If optional TREE is given, use this text instead of the kill ring.
  7397. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7398. move back over whitespace before inserting, and move point to the end of
  7399. the inserted text when done.
  7400. When REMOVE is non-nil, remove the subtree from the clipboard."
  7401. (interactive "P")
  7402. (setq tree (or tree (and kill-ring (current-kill 0))))
  7403. (unless (org-kill-is-subtree-p tree)
  7404. (user-error
  7405. (substitute-command-keys
  7406. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  7407. (org-with-limited-levels
  7408. (let* ((visp (not (org-invisible-p)))
  7409. (txt tree)
  7410. (old-level (if (string-match org-outline-regexp-bol txt)
  7411. (- (match-end 0) (match-beginning 0) 1)
  7412. -1))
  7413. (force-level
  7414. (cond
  7415. (level (prefix-numeric-value level))
  7416. ;; When point is right after the stars in an otherwise
  7417. ;; empty headline, use stars as the forced level.
  7418. ((and (looking-at-p "[ \t]*$")
  7419. (string-match-p "^\\*+ *"
  7420. (buffer-substring (line-beginning-position)
  7421. (point))))
  7422. (org-outline-level))
  7423. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  7424. (previous-level
  7425. (save-excursion
  7426. (org-previous-visible-heading 1)
  7427. (if (org-at-heading-p) (org-outline-level) 1)))
  7428. (next-level
  7429. (save-excursion
  7430. (if (org-at-heading-p) (org-outline-level)
  7431. (org-next-visible-heading 1)
  7432. (if (org-at-heading-p) (org-outline-level) 1))))
  7433. (new-level (or force-level (max previous-level next-level)))
  7434. (shift (if (or (= old-level -1)
  7435. (= new-level -1)
  7436. (= old-level new-level))
  7437. 0
  7438. (- new-level old-level)))
  7439. (delta (if (> shift 0) -1 1))
  7440. (func (if (> shift 0) #'org-demote #'org-promote))
  7441. (org-odd-levels-only nil)
  7442. beg end newend)
  7443. ;; Remove the forced level indicator.
  7444. (when (and force-level (not level))
  7445. (delete-region (line-beginning-position) (point)))
  7446. ;; Paste before the next visible heading or at end of buffer,
  7447. ;; unless point is at the beginning of a headline.
  7448. (unless (and (bolp) (org-at-heading-p))
  7449. (org-next-visible-heading 1)
  7450. (unless (bolp) (insert "\n")))
  7451. (setq beg (point))
  7452. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7453. (insert-before-markers txt)
  7454. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7455. (setq newend (point))
  7456. (org-reinstall-markers-in-region beg)
  7457. (setq end (point))
  7458. (goto-char beg)
  7459. (skip-chars-forward " \t\n\r")
  7460. (setq beg (point))
  7461. (when (and (org-invisible-p) visp)
  7462. (save-excursion (outline-show-heading)))
  7463. ;; Shift if necessary.
  7464. (unless (= shift 0)
  7465. (save-restriction
  7466. (narrow-to-region beg end)
  7467. (while (not (= shift 0))
  7468. (org-map-region func (point-min) (point-max))
  7469. (setq shift (+ delta shift)))
  7470. (goto-char (point-min))
  7471. (setq newend (point-max))))
  7472. (when (or for-yank (called-interactively-p 'interactive))
  7473. (message "Clipboard pasted as level %d subtree" new-level))
  7474. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7475. kill-ring
  7476. (equal org-subtree-clip (current-kill 0))
  7477. org-subtree-clip-folded)
  7478. ;; The tree was folded before it was killed/copied
  7479. (outline-hide-subtree))
  7480. (when for-yank (goto-char newend))
  7481. (when remove (pop kill-ring)))))
  7482. (defun org-kill-is-subtree-p (&optional txt)
  7483. "Check if the current kill is an outline subtree, or a set of trees.
  7484. Returns nil if kill does not start with a headline, or if the first
  7485. headline level is not the largest headline level in the tree.
  7486. So this will actually accept several entries of equal levels as well,
  7487. which is OK for `org-paste-subtree'.
  7488. If optional TXT is given, check this string instead of the current kill."
  7489. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7490. (re (org-get-limited-outline-regexp))
  7491. (^re (concat "^" re))
  7492. (start-level (and kill
  7493. (string-match
  7494. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7495. kill)
  7496. (- (match-end 2) (match-beginning 2) 1)))
  7497. (start (1+ (or (match-beginning 2) -1))))
  7498. (if (not start-level)
  7499. (progn
  7500. nil) ;; does not even start with a heading
  7501. (catch 'exit
  7502. (while (setq start (string-match ^re kill (1+ start)))
  7503. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7504. (throw 'exit nil)))
  7505. t))))
  7506. (defvar org-markers-to-move nil
  7507. "Markers that should be moved with a cut-and-paste operation.
  7508. Those markers are stored together with their positions relative to
  7509. the start of the region.")
  7510. (defun org-save-markers-in-region (beg end)
  7511. "Check markers in region.
  7512. If these markers are between BEG and END, record their position relative
  7513. to BEG, so that after moving the block of text, we can put the markers back
  7514. into place.
  7515. This function gets called just before an entry or tree gets cut from the
  7516. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7517. called immediately, to move the markers with the entries."
  7518. (setq org-markers-to-move nil)
  7519. (when (featurep 'org-clock)
  7520. (org-clock-save-markers-for-cut-and-paste beg end))
  7521. (when (featurep 'org-agenda)
  7522. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7523. (defun org-check-and-save-marker (marker beg end)
  7524. "Check if MARKER is between BEG and END.
  7525. If yes, remember the marker and the distance to BEG."
  7526. (when (and (marker-buffer marker)
  7527. (equal (marker-buffer marker) (current-buffer))
  7528. (>= marker beg) (< marker end))
  7529. (push (cons marker (- marker beg)) org-markers-to-move)))
  7530. (defun org-reinstall-markers-in-region (beg)
  7531. "Move all remembered markers to their position relative to BEG."
  7532. (dolist (x org-markers-to-move)
  7533. (move-marker (car x) (+ beg (cdr x))))
  7534. (setq org-markers-to-move nil))
  7535. (defun org-narrow-to-subtree ()
  7536. "Narrow buffer to the current subtree."
  7537. (interactive)
  7538. (save-excursion
  7539. (save-match-data
  7540. (org-with-limited-levels
  7541. (narrow-to-region
  7542. (progn (org-back-to-heading t) (point))
  7543. (progn (org-end-of-subtree t t)
  7544. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7545. (point)))))))
  7546. (defun org-toggle-narrow-to-subtree ()
  7547. "Narrow to the subtree at point or widen a narrowed buffer."
  7548. (interactive)
  7549. (if (buffer-narrowed-p)
  7550. (widen)
  7551. (org-narrow-to-subtree)))
  7552. (defun org-narrow-to-block ()
  7553. "Narrow buffer to the current block."
  7554. (interactive)
  7555. (let* ((case-fold-search t)
  7556. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7557. "^[ \t]*#\\+end_.*")))
  7558. (if blockp
  7559. (narrow-to-region (car blockp) (cdr blockp))
  7560. (user-error "Not in a block"))))
  7561. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7562. "Clone the task (subtree) at point N times.
  7563. The clones will be inserted as siblings.
  7564. In interactive use, the user will be prompted for the number of
  7565. clones to be produced. If the entry has a timestamp, the user
  7566. will also be prompted for a time shift, which may be a repeater
  7567. as used in time stamps, for example `+3d'. To disable this,
  7568. you can call the function with a universal prefix argument.
  7569. When a valid repeater is given and the entry contains any time
  7570. stamps, the clones will become a sequence in time, with time
  7571. stamps in the subtree shifted for each clone produced. If SHIFT
  7572. is nil or the empty string, time stamps will be left alone. The
  7573. ID property of the original subtree is removed.
  7574. In each clone, all the CLOCK entries will be removed. This
  7575. prevents Org from considering that the clocked times overlap.
  7576. If the original subtree did contain time stamps with a repeater,
  7577. the following will happen:
  7578. - the repeater will be removed in each clone
  7579. - an additional clone will be produced, with the current, unshifted
  7580. date(s) in the entry.
  7581. - the original entry will be placed *after* all the clones, with
  7582. repeater intact.
  7583. - the start days in the repeater in the original entry will be shifted
  7584. to past the last clone.
  7585. In this way you can spell out a number of instances of a repeating task,
  7586. and still retain the repeater to cover future instances of the task.
  7587. As described above, N+1 clones are produced when the original
  7588. subtree has a repeater. Setting N to 0, then, can be used to
  7589. remove the repeater from a subtree and create a shifted clone
  7590. with the original repeater."
  7591. (interactive "nNumber of clones to produce: ")
  7592. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7593. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7594. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7595. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7596. (shift
  7597. (or shift
  7598. (if (and (not (equal current-prefix-arg '(4)))
  7599. (save-excursion
  7600. (goto-char beg)
  7601. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7602. (read-from-minibuffer
  7603. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7604. ""))) ;No time shift
  7605. (doshift
  7606. (and (org-string-nw-p shift)
  7607. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7608. shift)
  7609. (user-error "Invalid shift specification %s" shift)))))
  7610. (goto-char end-of-tree)
  7611. (unless (bolp) (insert "\n"))
  7612. (let* ((end (point))
  7613. (template (buffer-substring beg end))
  7614. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7615. (shift-what (pcase (and doshift (match-string 2 shift))
  7616. (`nil nil)
  7617. ("d" 'day)
  7618. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7619. ("m" 'month)
  7620. ("y" 'year)
  7621. (_ (error "Unsupported time unit"))))
  7622. (nmin 1)
  7623. (nmax n)
  7624. (n-no-remove -1)
  7625. (idprop (org-entry-get nil "ID")))
  7626. (when (and doshift
  7627. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7628. template))
  7629. (delete-region beg end)
  7630. (setq end beg)
  7631. (setq nmin 0)
  7632. (setq nmax (1+ nmax))
  7633. (setq n-no-remove nmax))
  7634. (goto-char end)
  7635. (cl-loop for n from nmin to nmax do
  7636. (insert
  7637. ;; Prepare clone.
  7638. (with-temp-buffer
  7639. (insert template)
  7640. (org-mode)
  7641. (goto-char (point-min))
  7642. (org-show-subtree)
  7643. (and idprop (if org-clone-delete-id
  7644. (org-entry-delete nil "ID")
  7645. (org-id-get-create t)))
  7646. (unless (= n 0)
  7647. (while (re-search-forward org-clock-line-re nil t)
  7648. (delete-region (line-beginning-position)
  7649. (line-beginning-position 2)))
  7650. (goto-char (point-min))
  7651. (while (re-search-forward org-drawer-regexp nil t)
  7652. (org-remove-empty-drawer-at (point))))
  7653. (goto-char (point-min))
  7654. (when doshift
  7655. (while (re-search-forward org-ts-regexp-both nil t)
  7656. (org-timestamp-change (* n shift-n) shift-what))
  7657. (unless (= n n-no-remove)
  7658. (goto-char (point-min))
  7659. (while (re-search-forward org-ts-regexp nil t)
  7660. (save-excursion
  7661. (goto-char (match-beginning 0))
  7662. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7663. (delete-region (match-beginning 1) (match-end 1)))))))
  7664. (buffer-string)))))
  7665. (goto-char beg)))
  7666. ;;; Outline Sorting
  7667. (defun org-sort (&optional with-case)
  7668. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7669. Optional argument WITH-CASE means sort case-sensitively."
  7670. (interactive "P")
  7671. (org-call-with-arg
  7672. (cond ((org-at-table-p) #'org-table-sort-lines)
  7673. ((org-at-item-p) #'org-sort-list)
  7674. (t #'org-sort-entries))
  7675. with-case))
  7676. (defun org-sort-remove-invisible (s)
  7677. "Remove invisible part of links and emphasis markers from string S."
  7678. (remove-text-properties 0 (length s) org-rm-props s)
  7679. (replace-regexp-in-string
  7680. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7681. (replace-regexp-in-string
  7682. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7683. (org-link-display-format s)
  7684. t t) t t))
  7685. (defvar org-priority-regexp) ; defined later in the file
  7686. (defvar org-after-sorting-entries-or-items-hook nil
  7687. "Hook that is run after a bunch of entries or items have been sorted.
  7688. When children are sorted, the cursor is in the parent line when this
  7689. hook gets called. When a region or a plain list is sorted, the cursor
  7690. will be in the first entry of the sorted region/list.")
  7691. (defun org-sort-entries
  7692. (&optional with-case sorting-type getkey-func compare-func property
  7693. interactive?)
  7694. "Sort entries on a certain level of an outline tree.
  7695. If there is an active region, the entries in the region are sorted.
  7696. Else, if the cursor is before the first entry, sort the top-level items.
  7697. Else, the children of the entry at point are sorted.
  7698. Sorting can be alphabetically, numerically, by date/time as given by
  7699. a time stamp, by a property, by priority order, or by a custom function.
  7700. The command prompts for the sorting type unless it has been given to the
  7701. function through the SORTING-TYPE argument, which needs to be a character,
  7702. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7703. the precise meaning of each character:
  7704. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7705. c By creation time, which is assumed to be the first inactive time stamp
  7706. at the beginning of a line.
  7707. d By deadline date/time.
  7708. k By clocking time.
  7709. n Numerically, by converting the beginning of the entry/item to a number.
  7710. o By order of TODO keywords.
  7711. p By priority according to the cookie.
  7712. r By the value of a property.
  7713. s By scheduled date/time.
  7714. t By date/time, either the first active time stamp in the entry, or, if
  7715. none exist, by the first inactive one.
  7716. Capital letters will reverse the sort order.
  7717. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7718. called with point at the beginning of the record. It must return a
  7719. value that is compatible with COMPARE-FUNC, the function used to
  7720. compare entries.
  7721. Comparing entries ignores case by default. However, with an optional argument
  7722. WITH-CASE, the sorting considers case as well.
  7723. Sorting is done against the visible part of the headlines, it ignores hidden
  7724. links.
  7725. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7726. A non-nil value for INTERACTIVE? is used to signal that this
  7727. function is being called interactively."
  7728. (interactive (list current-prefix-arg nil nil nil nil t))
  7729. (let ((case-func (if with-case 'identity 'downcase))
  7730. start beg end stars re re2
  7731. txt what tmp)
  7732. ;; Find beginning and end of region to sort
  7733. (cond
  7734. ((org-region-active-p)
  7735. ;; we will sort the region
  7736. (setq end (region-end)
  7737. what "region")
  7738. (goto-char (region-beginning))
  7739. (unless (org-at-heading-p) (outline-next-heading))
  7740. (setq start (point)))
  7741. ((or (org-at-heading-p)
  7742. (ignore-errors (progn (org-back-to-heading) t)))
  7743. ;; we will sort the children of the current headline
  7744. (org-back-to-heading)
  7745. (setq start (point)
  7746. end (progn (org-end-of-subtree t t)
  7747. (or (bolp) (insert "\n"))
  7748. (when (>= (org-back-over-empty-lines) 1)
  7749. (forward-line 1))
  7750. (point))
  7751. what "children")
  7752. (goto-char start)
  7753. (outline-show-subtree)
  7754. (outline-next-heading))
  7755. (t
  7756. ;; we will sort the top-level entries in this file
  7757. (goto-char (point-min))
  7758. (or (org-at-heading-p) (outline-next-heading))
  7759. (setq start (point))
  7760. (goto-char (point-max))
  7761. (beginning-of-line 1)
  7762. (when (looking-at ".*?\\S-")
  7763. ;; File ends in a non-white line
  7764. (end-of-line 1)
  7765. (insert "\n"))
  7766. (setq end (point-max))
  7767. (setq what "top-level")
  7768. (goto-char start)
  7769. (org-show-all '(headings blocks))))
  7770. (setq beg (point))
  7771. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7772. (looking-at "\\(\\*+\\)")
  7773. (setq stars (match-string 1)
  7774. re (concat "^" (regexp-quote stars) " +")
  7775. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7776. txt (buffer-substring beg end))
  7777. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7778. (when (and (not (equal stars "*")) (string-match re2 txt))
  7779. (user-error "Region to sort contains a level above the first entry"))
  7780. (unless sorting-type
  7781. (message
  7782. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7783. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7784. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7785. what)
  7786. (setq sorting-type (read-char-exclusive)))
  7787. (unless getkey-func
  7788. (and (= (downcase sorting-type) ?f)
  7789. (setq getkey-func
  7790. (or (and interactive?
  7791. (org-read-function
  7792. "Function for extracting keys: "))
  7793. (error "Missing key extractor")))))
  7794. (and (= (downcase sorting-type) ?r)
  7795. (not property)
  7796. (setq property
  7797. (completing-read "Property: "
  7798. (mapcar #'list (org-buffer-property-keys t))
  7799. nil t)))
  7800. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7801. (message "Sorting entries...")
  7802. (save-restriction
  7803. (narrow-to-region start end)
  7804. (let ((restore-clock?
  7805. ;; The clock marker is lost when using `sort-subr'; mark
  7806. ;; the clock with temporary `:org-clock-marker-backup'
  7807. ;; text property.
  7808. (when (and (eq (org-clock-is-active) (current-buffer))
  7809. (<= start (marker-position org-clock-marker))
  7810. (>= end (marker-position org-clock-marker)))
  7811. (with-silent-modifications
  7812. (put-text-property (1- org-clock-marker) org-clock-marker
  7813. :org-clock-marker-backup t))
  7814. t))
  7815. (dcst (downcase sorting-type))
  7816. (case-fold-search nil)
  7817. (now (current-time)))
  7818. (org-preserve-local-variables
  7819. (sort-subr
  7820. (/= dcst sorting-type)
  7821. ;; This function moves to the beginning character of the
  7822. ;; "record" to be sorted.
  7823. (lambda nil
  7824. (if (re-search-forward re nil t)
  7825. (goto-char (match-beginning 0))
  7826. (goto-char (point-max))))
  7827. ;; This function moves to the last character of the "record" being
  7828. ;; sorted.
  7829. (lambda nil
  7830. (save-match-data
  7831. (condition-case nil
  7832. (outline-forward-same-level 1)
  7833. (error
  7834. (goto-char (point-max))))))
  7835. ;; This function returns the value that gets sorted against.
  7836. (lambda ()
  7837. (cond
  7838. ((= dcst ?n)
  7839. (string-to-number
  7840. (org-sort-remove-invisible (org-get-heading t t t t))))
  7841. ((= dcst ?a)
  7842. (funcall case-func
  7843. (org-sort-remove-invisible (org-get-heading t t t t))))
  7844. ((= dcst ?k)
  7845. (or (get-text-property (point) :org-clock-minutes) 0))
  7846. ((= dcst ?t)
  7847. (let ((end (save-excursion (outline-next-heading) (point))))
  7848. (if (or (re-search-forward org-ts-regexp end t)
  7849. (re-search-forward org-ts-regexp-both end t))
  7850. (org-time-string-to-seconds (match-string 0))
  7851. (float-time now))))
  7852. ((= dcst ?c)
  7853. (let ((end (save-excursion (outline-next-heading) (point))))
  7854. (if (re-search-forward
  7855. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7856. end t)
  7857. (org-time-string-to-seconds (match-string 0))
  7858. (float-time now))))
  7859. ((= dcst ?s)
  7860. (let ((end (save-excursion (outline-next-heading) (point))))
  7861. (if (re-search-forward org-scheduled-time-regexp end t)
  7862. (org-time-string-to-seconds (match-string 1))
  7863. (float-time now))))
  7864. ((= dcst ?d)
  7865. (let ((end (save-excursion (outline-next-heading) (point))))
  7866. (if (re-search-forward org-deadline-time-regexp end t)
  7867. (org-time-string-to-seconds (match-string 1))
  7868. (float-time now))))
  7869. ((= dcst ?p)
  7870. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7871. (string-to-char (match-string 2))
  7872. org-default-priority))
  7873. ((= dcst ?r)
  7874. (or (org-entry-get nil property) ""))
  7875. ((= dcst ?o)
  7876. (when (looking-at org-complex-heading-regexp)
  7877. (let* ((m (match-string 2))
  7878. (s (if (member m org-done-keywords) '- '+)))
  7879. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7880. ((= dcst ?f)
  7881. (if getkey-func
  7882. (progn
  7883. (setq tmp (funcall getkey-func))
  7884. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7885. tmp)
  7886. (error "Invalid key function `%s'" getkey-func)))
  7887. (t (error "Invalid sorting type `%c'" sorting-type))))
  7888. nil
  7889. (cond
  7890. ((= dcst ?a) 'org-string-collate-lessp)
  7891. ((= dcst ?f)
  7892. (or compare-func
  7893. (and interactive?
  7894. (org-read-function
  7895. (concat "Function for comparing keys "
  7896. "(empty for default `sort-subr' predicate): ")
  7897. 'allow-empty))))
  7898. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7899. (when restore-clock?
  7900. (move-marker org-clock-marker
  7901. (1+ (next-single-property-change
  7902. start :org-clock-marker-backup)))
  7903. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7904. '(:org-clock-marker-backup t)))))
  7905. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7906. (message "Sorting entries...done")))
  7907. (defun org-contextualize-keys (alist contexts)
  7908. "Return valid elements in ALIST depending on CONTEXTS.
  7909. `org-agenda-custom-commands' or `org-capture-templates' are the
  7910. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7911. or `org-capture-templates-contexts' are the associated contexts
  7912. definitions."
  7913. (let ((contexts
  7914. ;; normalize contexts
  7915. (mapcar
  7916. (lambda(c) (cond ((listp (cadr c))
  7917. (list (car c) (car c) (nth 1 c)))
  7918. ((string= "" (cadr c))
  7919. (list (car c) (car c) (nth 2 c)))
  7920. (t c)))
  7921. contexts))
  7922. (a alist) r s)
  7923. ;; loop over all commands or templates
  7924. (dolist (c a)
  7925. (let (vrules repl)
  7926. (cond
  7927. ((not (assoc (car c) contexts))
  7928. (push c r))
  7929. ((and (assoc (car c) contexts)
  7930. (setq vrules (org-contextualize-validate-key
  7931. (car c) contexts)))
  7932. (mapc (lambda (vr)
  7933. (unless (equal (car vr) (cadr vr))
  7934. (setq repl vr)))
  7935. vrules)
  7936. (if (not repl) (push c r)
  7937. (push (cadr repl) s)
  7938. (push
  7939. (cons (car c)
  7940. (cdr (or (assoc (cadr repl) alist)
  7941. (error "Undefined key `%s' as contextual replacement for `%s'"
  7942. (cadr repl) (car c)))))
  7943. r))))))
  7944. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7945. (delq
  7946. nil
  7947. (delete-dups
  7948. (mapcar (lambda (x)
  7949. (let ((tpl (car x)))
  7950. (unless (delq
  7951. nil
  7952. (mapcar (lambda (y)
  7953. (equal y tpl))
  7954. s))
  7955. x)))
  7956. (reverse r))))))
  7957. (defun org-contextualize-validate-key (key contexts)
  7958. "Check CONTEXTS for agenda or capture KEY."
  7959. (let (res)
  7960. (dolist (r contexts)
  7961. (dolist (rr (car (last r)))
  7962. (when
  7963. (and (equal key (car r))
  7964. (if (functionp rr) (funcall rr)
  7965. (or (and (eq (car rr) 'in-file)
  7966. (buffer-file-name)
  7967. (string-match (cdr rr) (buffer-file-name)))
  7968. (and (eq (car rr) 'in-mode)
  7969. (string-match (cdr rr) (symbol-name major-mode)))
  7970. (and (eq (car rr) 'in-buffer)
  7971. (string-match (cdr rr) (buffer-name)))
  7972. (when (and (eq (car rr) 'not-in-file)
  7973. (buffer-file-name))
  7974. (not (string-match (cdr rr) (buffer-file-name))))
  7975. (when (eq (car rr) 'not-in-mode)
  7976. (not (string-match (cdr rr) (symbol-name major-mode))))
  7977. (when (eq (car rr) 'not-in-buffer)
  7978. (not (string-match (cdr rr) (buffer-name)))))))
  7979. (push r res))))
  7980. (delete-dups (delq nil res))))
  7981. ;; Defined to provide a value for defcustom, since there is no
  7982. ;; string-collate-greaterp in Emacs.
  7983. (defun org-string-collate-greaterp (s1 s2)
  7984. "Return non-nil if S1 is greater than S2 in collation order."
  7985. (not (org-string-collate-lessp s1 s2)))
  7986. ;;;###autoload
  7987. (defun org-run-like-in-org-mode (cmd)
  7988. "Run a command, pretending that the current buffer is in Org mode.
  7989. This will temporarily bind local variables that are typically bound in
  7990. Org mode to the values they have in Org mode, and then interactively
  7991. call CMD."
  7992. (org-load-modules-maybe)
  7993. (let (binds)
  7994. (dolist (var (org-get-local-variables))
  7995. (when (or (not (boundp (car var)))
  7996. (eq (symbol-value (car var))
  7997. (default-value (car var))))
  7998. (push (list (car var) `(quote ,(cadr var))) binds)))
  7999. (eval `(let ,binds
  8000. (call-interactively (quote ,cmd))))))
  8001. (defun org-get-category (&optional pos force-refresh)
  8002. "Get the category applying to position POS."
  8003. (save-match-data
  8004. (when force-refresh (org-refresh-category-properties))
  8005. (let ((pos (or pos (point))))
  8006. (or (get-text-property pos 'org-category)
  8007. (progn (org-refresh-category-properties)
  8008. (get-text-property pos 'org-category))))))
  8009. ;;; Refresh properties
  8010. (defun org-refresh-properties (dprop tprop)
  8011. "Refresh buffer text properties.
  8012. DPROP is the drawer property and TPROP is either the
  8013. corresponding text property to set, or an alist with each element
  8014. being a text property (as a symbol) and a function to apply to
  8015. the value of the drawer property."
  8016. (let* ((case-fold-search t)
  8017. (inhibit-read-only t)
  8018. (inherit? (org-property-inherit-p dprop))
  8019. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  8020. (global (and inherit? (org--property-global-value dprop nil))))
  8021. (with-silent-modifications
  8022. (org-with-point-at 1
  8023. ;; Set global values (e.g., values defined through
  8024. ;; "#+PROPERTY:" keywords) to the whole buffer.
  8025. (when global (put-text-property (point-min) (point-max) tprop global))
  8026. ;; Set local values.
  8027. (while (re-search-forward property-re nil t)
  8028. (when (org-at-property-p)
  8029. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  8030. (outline-next-heading))))))
  8031. (defun org-refresh-property (tprop p &optional inherit)
  8032. "Refresh the buffer text property TPROP from the drawer property P.
  8033. The refresh happens only for the current headline, or the whole
  8034. sub-tree if optional argument INHERIT is non-nil."
  8035. (unless (org-before-first-heading-p)
  8036. (save-excursion
  8037. (org-back-to-heading t)
  8038. (let ((start (point))
  8039. (end (save-excursion
  8040. (if inherit (org-end-of-subtree t t)
  8041. (or (outline-next-heading) (point-max))))))
  8042. (if (symbolp tprop)
  8043. ;; TPROP is a text property symbol.
  8044. (put-text-property start end tprop p)
  8045. ;; TPROP is an alist with (property . function) elements.
  8046. (pcase-dolist (`(,prop . ,f) tprop)
  8047. (put-text-property start end prop (funcall f p))))))))
  8048. (defun org-refresh-category-properties ()
  8049. "Refresh category text properties in the buffer."
  8050. (let ((case-fold-search t)
  8051. (inhibit-read-only t)
  8052. (default-category
  8053. (cond ((null org-category)
  8054. (if buffer-file-name
  8055. (file-name-sans-extension
  8056. (file-name-nondirectory buffer-file-name))
  8057. "???"))
  8058. ((symbolp org-category) (symbol-name org-category))
  8059. (t org-category))))
  8060. (with-silent-modifications
  8061. (org-with-wide-buffer
  8062. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8063. ;; This is the default category for the buffer. If none is
  8064. ;; found, fall-back to `org-category' or buffer file name.
  8065. (put-text-property
  8066. (point-min) (point-max)
  8067. 'org-category
  8068. (catch 'buffer-category
  8069. (goto-char (point-max))
  8070. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8071. (let ((element (org-element-at-point)))
  8072. (when (eq (org-element-type element) 'keyword)
  8073. (throw 'buffer-category
  8074. (org-element-property :value element)))))
  8075. default-category))
  8076. ;; Set sub-tree specific categories.
  8077. (goto-char (point-min))
  8078. (let ((regexp (org-re-property "CATEGORY")))
  8079. (while (re-search-forward regexp nil t)
  8080. (let ((value (match-string-no-properties 3)))
  8081. (when (org-at-property-p)
  8082. (put-text-property
  8083. (save-excursion (org-back-to-heading t) (point))
  8084. (save-excursion (org-end-of-subtree t t) (point))
  8085. 'org-category
  8086. value)))))))))
  8087. (defun org-refresh-stats-properties ()
  8088. "Refresh stats text properties in the buffer."
  8089. (with-silent-modifications
  8090. (org-with-point-at 1
  8091. (let ((regexp (concat org-outline-regexp-bol
  8092. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8093. (while (re-search-forward regexp nil t)
  8094. (let* ((numerator (string-to-number (match-string 1)))
  8095. (denominator (and (match-end 2)
  8096. (string-to-number (match-string 2))))
  8097. (stats (cond ((not denominator) numerator) ;percent
  8098. ((= denominator 0) 0)
  8099. (t (/ (* numerator 100) denominator)))))
  8100. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8101. 'org-stats stats)))))))
  8102. (defun org-refresh-effort-properties ()
  8103. "Refresh effort properties"
  8104. (org-refresh-properties
  8105. org-effort-property
  8106. '((effort . identity)
  8107. (effort-minutes . org-duration-to-minutes))))
  8108. ;;;; Link Stuff
  8109. ;;; Link abbreviations
  8110. (defun org-link-expand-abbrev (link)
  8111. "Apply replacements as defined in `org-link-abbrev-alist'."
  8112. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8113. (let* ((key (match-string 1 link))
  8114. (as (or (assoc key org-link-abbrev-alist-local)
  8115. (assoc key org-link-abbrev-alist)))
  8116. (tag (and (match-end 2) (match-string 3 link)))
  8117. rpl)
  8118. (if (not as)
  8119. link
  8120. (setq rpl (cdr as))
  8121. (cond
  8122. ((symbolp rpl) (funcall rpl tag))
  8123. ((string-match "%(\\([^)]+\\))" rpl)
  8124. (replace-match
  8125. (save-match-data
  8126. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8127. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8128. ((string-match "%h" rpl)
  8129. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8130. (t (concat rpl tag)))))
  8131. link))
  8132. ;;; Storing and inserting links
  8133. (defvar org-insert-link-history nil
  8134. "Minibuffer history for links inserted with `org-insert-link'.")
  8135. (defvar org-stored-links nil
  8136. "Contains the links stored with `org-store-link'.")
  8137. (defvar org-store-link-plist nil
  8138. "Plist with info about the most recently link created with `org-store-link'.")
  8139. (defun org-store-link-functions ()
  8140. "Return a list of functions that are called to create and store a link.
  8141. The functions defined in the :store property of
  8142. `org-link-parameters'.
  8143. Each function will be called in turn until one returns a non-nil
  8144. value. Each function should check if it is responsible for
  8145. creating this link (for example by looking at the major mode).
  8146. If not, it must exit and return nil. If yes, it should return
  8147. a non-nil value after calling `org-store-link-props' with a list
  8148. of properties and values. Special properties are:
  8149. :type The link prefix, like \"http\". This must be given.
  8150. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8151. This is obligatory as well.
  8152. :description Optional default description for the second pair
  8153. of brackets in an Org mode link. The user can still change
  8154. this when inserting this link into an Org mode buffer.
  8155. In addition to these, any additional properties can be specified
  8156. and then used in capture templates."
  8157. (cl-loop for link in org-link-parameters
  8158. with store-func
  8159. do (setq store-func (org-link-get-parameter (car link) :store))
  8160. if store-func
  8161. collect store-func))
  8162. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8163. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8164. ;;;###autoload
  8165. (defun org-store-link (arg &optional interactive?)
  8166. "Store a link to the current location.
  8167. \\<org-mode-map>
  8168. This link is added to `org-stored-links' and can later be inserted
  8169. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8170. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8171. A single
  8172. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8173. `org-gnus-prefer-web-links' for links to Usenet articles.
  8174. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8175. skipping storing functions that are not
  8176. part of Org core.
  8177. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8178. prefix ARG forces storing a link for each line in the
  8179. active region.
  8180. Assume the function is called interactively if INTERACTIVE? is
  8181. non-nil."
  8182. (interactive "P\np")
  8183. (org-load-modules-maybe)
  8184. (if (and (equal arg '(64)) (org-region-active-p))
  8185. (save-excursion
  8186. (let ((end (region-end)))
  8187. (goto-char (region-beginning))
  8188. (set-mark (point))
  8189. (while (< (point-at-eol) end)
  8190. (move-end-of-line 1) (activate-mark)
  8191. (let (current-prefix-arg)
  8192. (call-interactively 'org-store-link))
  8193. (move-beginning-of-line 2)
  8194. (set-mark (point)))))
  8195. (setq org-store-link-plist nil)
  8196. (let (link cpltxt desc description search txt custom-id agenda-link)
  8197. (cond
  8198. ;; Store a link using an external link type, if any function is
  8199. ;; available. If more than one can generate a link from current
  8200. ;; location, ask which one to use.
  8201. ((and (not (equal arg '(16)))
  8202. (let ((results-alist nil))
  8203. (dolist (f (org-store-link-functions))
  8204. (when (funcall f)
  8205. ;; XXX: return value is not link's plist, so we
  8206. ;; store the new value before it is modified. It
  8207. ;; would be cleaner to ask store link functions to
  8208. ;; return the plist instead.
  8209. (push (cons f (copy-sequence org-store-link-plist))
  8210. results-alist)))
  8211. (pcase results-alist
  8212. (`nil nil)
  8213. (`((,_ . ,_)) t) ;single choice: nothing to do
  8214. (`((,name . ,_) . ,_)
  8215. ;; Reinstate link plist associated to the chosen
  8216. ;; function.
  8217. (apply #'org-store-link-props
  8218. (cdr (assoc-string
  8219. (completing-read
  8220. "Which function for creating the link? "
  8221. (mapcar #'car results-alist)
  8222. nil t (symbol-name name))
  8223. results-alist)))
  8224. t))))
  8225. (setq link (plist-get org-store-link-plist :link))
  8226. (setq desc (or (plist-get org-store-link-plist :description)
  8227. link)))
  8228. ;; Store a link from a source code buffer.
  8229. ((org-src-edit-buffer-p)
  8230. (let ((coderef-format (org-src-coderef-format)))
  8231. (cond ((org-match-line (org-src-coderef-regexp coderef-format))
  8232. (setq link (format "(%s)" (match-string-no-properties 3))))
  8233. (interactive?
  8234. (let ((label (read-string "Code line label: ")))
  8235. (end-of-line)
  8236. (setq link (format coderef-format label))
  8237. (let ((gc (- 79 (length link))))
  8238. (if (< (current-column) gc)
  8239. (org-move-to-column gc t)
  8240. (insert " ")))
  8241. (insert link)
  8242. (setq link (concat "(" label ")"))
  8243. (setq desc nil)))
  8244. (t (setq link nil)))))
  8245. ;; We are in the agenda, link to referenced location
  8246. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8247. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8248. (get-text-property (point) 'org-marker))))
  8249. (when m
  8250. (org-with-point-at m
  8251. (setq agenda-link (org-store-link nil interactive?))))))
  8252. ((eq major-mode 'calendar-mode)
  8253. (let ((cd (calendar-cursor-to-date)))
  8254. (setq link
  8255. (format-time-string
  8256. (car org-time-stamp-formats)
  8257. (apply 'encode-time
  8258. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8259. nil nil nil))))
  8260. (org-store-link-props :type "calendar" :date cd)))
  8261. ((eq major-mode 'help-mode)
  8262. (setq link (concat "help:" (save-excursion
  8263. (goto-char (point-min))
  8264. (looking-at "^[^ ]+")
  8265. (match-string 0))))
  8266. (org-store-link-props :type "help"))
  8267. ((eq major-mode 'w3-mode)
  8268. (setq cpltxt (if (and (buffer-name)
  8269. (not (string-match "Untitled" (buffer-name))))
  8270. (buffer-name)
  8271. (url-view-url t))
  8272. link (url-view-url t))
  8273. (org-store-link-props :type "w3" :url (url-view-url t)))
  8274. ((eq major-mode 'image-mode)
  8275. (setq cpltxt (concat "file:"
  8276. (abbreviate-file-name buffer-file-name))
  8277. link cpltxt)
  8278. (org-store-link-props :type "image" :file buffer-file-name))
  8279. ;; In dired, store a link to the file of the current line
  8280. ((derived-mode-p 'dired-mode)
  8281. (let ((file (dired-get-filename nil t)))
  8282. (setq file (if file
  8283. (abbreviate-file-name
  8284. (expand-file-name (dired-get-filename nil t)))
  8285. ;; otherwise, no file so use current directory.
  8286. default-directory))
  8287. (setq cpltxt (concat "file:" file)
  8288. link cpltxt)))
  8289. ((setq search (run-hook-with-args-until-success
  8290. 'org-create-file-search-functions))
  8291. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8292. "::" search))
  8293. (setq cpltxt (or description link)))
  8294. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8295. (org-with-limited-levels
  8296. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8297. (cond
  8298. ;; Store a link using the target at point
  8299. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8300. (setq cpltxt
  8301. (concat "file:"
  8302. (abbreviate-file-name
  8303. (buffer-file-name (buffer-base-buffer)))
  8304. "::" (match-string 1))
  8305. link cpltxt))
  8306. ((and (featurep 'org-id)
  8307. (or (eq org-id-link-to-org-use-id t)
  8308. (and interactive?
  8309. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8310. (and (eq org-id-link-to-org-use-id
  8311. 'create-if-interactive-and-no-custom-id)
  8312. (not custom-id))))
  8313. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8314. ;; Store a link using the ID at point
  8315. (setq link (condition-case nil
  8316. (prog1 (org-id-store-link)
  8317. (setq desc (or (plist-get org-store-link-plist
  8318. :description)
  8319. "")))
  8320. (error
  8321. ;; Probably before first headline, link only to file
  8322. (concat "file:"
  8323. (abbreviate-file-name
  8324. (buffer-file-name (buffer-base-buffer))))))))
  8325. (t
  8326. ;; Just link to current headline
  8327. (setq cpltxt (concat "file:"
  8328. (abbreviate-file-name
  8329. (buffer-file-name (buffer-base-buffer)))))
  8330. ;; Add a context search string
  8331. (when (org-xor org-context-in-file-links
  8332. (equal arg '(4)))
  8333. (let* ((element (org-element-at-point))
  8334. (name (org-element-property :name element)))
  8335. (setq txt (cond
  8336. ((org-at-heading-p) nil)
  8337. (name)
  8338. ((org-region-active-p)
  8339. (buffer-substring (region-beginning) (region-end)))))
  8340. (when (or (null txt) (string-match "\\S-" txt))
  8341. (setq cpltxt
  8342. (concat cpltxt "::"
  8343. (condition-case nil
  8344. (org-make-org-heading-search-string txt)
  8345. (error "")))
  8346. desc (or name
  8347. (nth 4 (ignore-errors (org-heading-components)))
  8348. "NONE")))))
  8349. (when (string-match "::\\'" cpltxt)
  8350. (setq cpltxt (substring cpltxt 0 -2)))
  8351. (setq link cpltxt)))))
  8352. ((buffer-file-name (buffer-base-buffer))
  8353. ;; Just link to this file here.
  8354. (setq cpltxt (concat "file:"
  8355. (abbreviate-file-name
  8356. (buffer-file-name (buffer-base-buffer)))))
  8357. ;; Add a context string.
  8358. (when (org-xor org-context-in-file-links
  8359. (equal arg '(4)))
  8360. (setq txt (if (org-region-active-p)
  8361. (buffer-substring (region-beginning) (region-end))
  8362. (buffer-substring (point-at-bol) (point-at-eol))))
  8363. ;; Only use search option if there is some text.
  8364. (when (string-match "\\S-" txt)
  8365. (setq cpltxt
  8366. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8367. desc "NONE")))
  8368. (setq link cpltxt))
  8369. (interactive?
  8370. (user-error "No method for storing a link from this buffer"))
  8371. (t (setq link nil)))
  8372. ;; We're done setting link and desc, clean up
  8373. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8374. (setq link (or link cpltxt)
  8375. desc (or desc cpltxt))
  8376. (cond ((not desc))
  8377. ((equal desc "NONE") (setq desc nil))
  8378. (t (setq desc
  8379. (replace-regexp-in-string
  8380. org-bracket-link-analytic-regexp
  8381. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8382. desc))))
  8383. ;; Return the link
  8384. (if (not (and interactive? link))
  8385. (or agenda-link (and link (org-make-link-string link desc)))
  8386. (push (list link desc) org-stored-links)
  8387. (message "Stored: %s" (or desc link))
  8388. (when custom-id
  8389. (setq link (concat "file:" (abbreviate-file-name
  8390. (buffer-file-name)) "::#" custom-id))
  8391. (push (list link desc) org-stored-links))
  8392. (car org-stored-links)))))
  8393. (defun org-store-link-props (&rest plist)
  8394. "Store link properties.
  8395. The properties are pre-processed by extracting names, addresses
  8396. and dates."
  8397. (let ((x (plist-get plist :from)))
  8398. (when x
  8399. (let ((adr (mail-extract-address-components x)))
  8400. (setq plist (plist-put plist :fromname (car adr)))
  8401. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8402. (let ((x (plist-get plist :to)))
  8403. (when x
  8404. (let ((adr (mail-extract-address-components x)))
  8405. (setq plist (plist-put plist :toname (car adr)))
  8406. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8407. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8408. (when x
  8409. (setq plist (plist-put plist :date-timestamp
  8410. (format-time-string
  8411. (org-time-stamp-format t) x)))
  8412. (setq plist (plist-put plist :date-timestamp-inactive
  8413. (format-time-string
  8414. (org-time-stamp-format t t) x)))))
  8415. (let ((from (plist-get plist :from))
  8416. (to (plist-get plist :to)))
  8417. (when (and from to org-from-is-user-regexp)
  8418. (setq plist
  8419. (plist-put plist :fromto
  8420. (if (string-match org-from-is-user-regexp from)
  8421. (concat "to %t")
  8422. (concat "from %f"))))))
  8423. (setq org-store-link-plist plist))
  8424. (defun org-add-link-props (&rest plist)
  8425. "Add these properties to the link property list."
  8426. (let (key value)
  8427. (while plist
  8428. (setq key (pop plist) value (pop plist))
  8429. (setq org-store-link-plist
  8430. (plist-put org-store-link-plist key value)))))
  8431. (defun org-email-link-description (&optional fmt)
  8432. "Return the description part of an email link.
  8433. This takes information from `org-store-link-plist' and formats it
  8434. according to FMT (default from `org-email-link-description-format')."
  8435. (setq fmt (or fmt org-email-link-description-format))
  8436. (let* ((p org-store-link-plist)
  8437. (to (plist-get p :toaddress))
  8438. (from (plist-get p :fromaddress))
  8439. (table
  8440. (list
  8441. (cons "%c" (plist-get p :fromto))
  8442. (cons "%F" (plist-get p :from))
  8443. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8444. (cons "%T" (plist-get p :to))
  8445. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8446. (cons "%s" (plist-get p :subject))
  8447. (cons "%d" (plist-get p :date))
  8448. (cons "%m" (plist-get p :message-id)))))
  8449. (when (string-match "%c" fmt)
  8450. ;; Check if the user wrote this message
  8451. (if (and org-from-is-user-regexp from to
  8452. (save-match-data (string-match org-from-is-user-regexp from)))
  8453. (setq fmt (replace-match "to %t" t t fmt))
  8454. (setq fmt (replace-match "from %f" t t fmt))))
  8455. (org-replace-escapes fmt table)))
  8456. (defun org-make-org-heading-search-string (&optional string)
  8457. "Make search string for the current headline or STRING."
  8458. (let ((s (or string
  8459. (and (derived-mode-p 'org-mode)
  8460. (save-excursion
  8461. (org-back-to-heading t)
  8462. (org-element-property :raw-value (org-element-at-point))))))
  8463. (lines org-context-in-file-links))
  8464. (unless string (setq s (concat "*" s))) ;Add * for headlines
  8465. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8466. (when (and string (integerp lines) (> lines 0))
  8467. (let ((slines (org-split-string s "\n")))
  8468. (when (< lines (length slines))
  8469. (setq s (mapconcat
  8470. 'identity
  8471. (reverse (nthcdr (- (length slines) lines)
  8472. (reverse slines))) "\n")))))
  8473. (mapconcat #'identity (split-string s) " ")))
  8474. (defconst org-link-escape-chars
  8475. ;;%20 %5B %5D %25
  8476. '(?\s ?\[ ?\] ?%)
  8477. "List of characters that should be escaped in a link when stored to Org.
  8478. This is the list that is used for internal purposes.")
  8479. (defun org-make-link-string (link &optional description)
  8480. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8481. (unless (org-string-nw-p link) (error "Empty link"))
  8482. (let ((uri (cond ((string-match org-link-types-re link)
  8483. (concat (match-string 1 link)
  8484. (org-link-escape (substring link (match-end 1)))))
  8485. ((or (file-name-absolute-p link)
  8486. (string-match-p "\\`\\.\\.?/" link))
  8487. (org-link-escape link))
  8488. ;; For readability, do not encode space characters
  8489. ;; in fuzzy links.
  8490. (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
  8491. (description
  8492. (and (org-string-nw-p description)
  8493. ;; Remove brackets from description, as they are fatal.
  8494. (replace-regexp-in-string
  8495. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8496. (org-trim description)))))
  8497. (format "[[%s]%s]"
  8498. uri
  8499. (if description (format "[%s]" description) ""))))
  8500. (defun org-link-escape (text &optional table merge)
  8501. "Return percent escaped representation of TEXT.
  8502. TEXT is a string with the text to escape.
  8503. Optional argument TABLE is a list with characters that should be
  8504. escaped. When nil, `org-link-escape-chars' is used.
  8505. If optional argument MERGE is set, merge TABLE into
  8506. `org-link-escape-chars'."
  8507. (let ((characters-to-encode
  8508. (cond ((null table) org-link-escape-chars)
  8509. (merge (append org-link-escape-chars table))
  8510. (t table))))
  8511. (mapconcat
  8512. (lambda (c)
  8513. (if (or (memq c characters-to-encode)
  8514. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8515. (mapconcat (lambda (e) (format "%%%.2X" e))
  8516. (or (encode-coding-char c 'utf-8)
  8517. (error "Unable to percent escape character: %c" c))
  8518. "")
  8519. (char-to-string c)))
  8520. text "")))
  8521. (defun org-link-unescape (str)
  8522. "Unhex hexified Unicode parts in string STR.
  8523. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  8524. reciprocal of `org-link-escape', which see."
  8525. (if (org-string-nw-p str)
  8526. (replace-regexp-in-string
  8527. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  8528. str))
  8529. (defun org-link-unescape-compound (hex)
  8530. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  8531. Note: this function also decodes single byte encodings like
  8532. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  8533. (save-match-data
  8534. (let* ((bytes (cdr (split-string hex "%")))
  8535. (ret "")
  8536. (eat 0)
  8537. (sum 0))
  8538. (while bytes
  8539. (let* ((val (string-to-number (pop bytes) 16))
  8540. (shift-xor
  8541. (if (= 0 eat)
  8542. (cond
  8543. ((>= val 252) (cons 6 252))
  8544. ((>= val 248) (cons 5 248))
  8545. ((>= val 240) (cons 4 240))
  8546. ((>= val 224) (cons 3 224))
  8547. ((>= val 192) (cons 2 192))
  8548. (t (cons 0 0)))
  8549. (cons 6 128))))
  8550. (when (>= val 192) (setq eat (car shift-xor)))
  8551. (setq val (logxor val (cdr shift-xor)))
  8552. (setq sum (+ (lsh sum (car shift-xor)) val))
  8553. (when (> eat 0) (setq eat (- eat 1)))
  8554. (cond
  8555. ((= 0 eat) ;multi byte
  8556. (setq ret (concat ret (char-to-string sum)))
  8557. (setq sum 0))
  8558. ((not bytes) ; single byte(s)
  8559. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  8560. ret)))
  8561. (defun org-link-unescape-single-byte-sequence (hex)
  8562. "Unhexify hex-encoded single byte character sequences."
  8563. (mapconcat (lambda (byte)
  8564. (char-to-string (string-to-number byte 16)))
  8565. (cdr (split-string hex "%")) ""))
  8566. (defun org-fixup-message-id-for-http (s)
  8567. "Replace special characters in a message id, so it can be used in an http query."
  8568. (when (string-match "%" s)
  8569. (setq s (mapconcat (lambda (c)
  8570. (if (eq c ?%)
  8571. "%25"
  8572. (char-to-string c)))
  8573. s "")))
  8574. (while (string-match "<" s)
  8575. (setq s (replace-match "%3C" t t s)))
  8576. (while (string-match ">" s)
  8577. (setq s (replace-match "%3E" t t s)))
  8578. (while (string-match "@" s)
  8579. (setq s (replace-match "%40" t t s)))
  8580. s)
  8581. (defun org-link-prettify (link)
  8582. "Return a human-readable representation of LINK.
  8583. The car of LINK must be a raw link.
  8584. The cdr of LINK must be either a link description or nil."
  8585. (let ((desc (or (cadr link) "<no description>")))
  8586. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  8587. "<" (car link) ">")))
  8588. ;;;###autoload
  8589. (defun org-insert-link-global ()
  8590. "Insert a link like Org mode does.
  8591. This command can be called in any mode to insert a link in Org syntax."
  8592. (interactive)
  8593. (org-load-modules-maybe)
  8594. (org-run-like-in-org-mode 'org-insert-link))
  8595. (defun org-insert-all-links (arg &optional pre post)
  8596. "Insert all links in `org-stored-links'.
  8597. When a universal prefix, do not delete the links from `org-stored-links'.
  8598. When `ARG' is a number, insert the last N link(s).
  8599. `PRE' and `POST' are optional arguments to define a string to
  8600. prepend or to append."
  8601. (interactive "P")
  8602. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  8603. (links (copy-sequence org-stored-links))
  8604. (pr (or pre "- "))
  8605. (po (or post "\n"))
  8606. (cnt 1) l)
  8607. (if (null org-stored-links)
  8608. (message "No link to insert")
  8609. (while (and (or (listp arg) (>= arg cnt))
  8610. (setq l (if (listp arg)
  8611. (pop links)
  8612. (pop org-stored-links))))
  8613. (setq cnt (1+ cnt))
  8614. (insert pr)
  8615. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  8616. (insert po)))))
  8617. (defun org-insert-last-stored-link (arg)
  8618. "Insert the last link stored in `org-stored-links'."
  8619. (interactive "p")
  8620. (org-insert-all-links arg "" "\n"))
  8621. (defun org-link-fontify-links-to-this-file ()
  8622. "Fontify links to the current file in `org-stored-links'."
  8623. (let ((f (buffer-file-name)) a b)
  8624. (setq a (mapcar (lambda(l)
  8625. (let ((ll (car l)))
  8626. (when (and (string-match "^file:\\(.+\\)::" ll)
  8627. (equal f (expand-file-name (match-string 1 ll))))
  8628. ll)))
  8629. org-stored-links))
  8630. (when (featurep 'org-id)
  8631. (setq b (mapcar (lambda(l)
  8632. (let ((ll (car l)))
  8633. (when (and (string-match "^id:\\(.+\\)$" ll)
  8634. (equal f (expand-file-name
  8635. (or (org-id-find-id-file
  8636. (match-string 1 ll)) ""))))
  8637. ll)))
  8638. org-stored-links)))
  8639. (mapcar (lambda(l)
  8640. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  8641. (delq nil (append a b)))))
  8642. (defvar org--links-history nil)
  8643. (defun org-insert-link (&optional complete-file link-location default-description)
  8644. "Insert a link. At the prompt, enter the link.
  8645. Completion can be used to insert any of the link protocol prefixes in use.
  8646. The history can be used to select a link previously stored with
  8647. `org-store-link'. When the empty string is entered (i.e. if you just
  8648. press `RET' at the prompt), the link defaults to the most recently
  8649. stored link. As `SPC' triggers completion in the minibuffer, you need to
  8650. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  8651. You will also be prompted for a description, and if one is given, it will
  8652. be displayed in the buffer instead of the link.
  8653. If there is already a link at point, this command will allow you to edit
  8654. link and description parts.
  8655. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  8656. file name can be
  8657. selected using completion. The path to the file will be relative to the
  8658. current directory if the file is in the current directory or a subdirectory.
  8659. Otherwise, the link will be the absolute path as completed in the minibuffer
  8660. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  8661. option `org-link-file-path-type'.
  8662. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  8663. absolute path even if the file is in
  8664. the current directory or below.
  8665. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8666. prefix negates `org-keep-stored-link-after-insertion'.
  8667. If the LINK-LOCATION parameter is non-nil, this value will be used as
  8668. the link location instead of reading one interactively.
  8669. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  8670. be used as the default description. Otherwise, if
  8671. `org-make-link-description-function' is non-nil, this function
  8672. will be called with the link target, and the result will be the
  8673. default link description. When called non-interactivily, don't
  8674. allow to edit the default description."
  8675. (interactive "P")
  8676. (let* ((wcf (current-window-configuration))
  8677. (origbuf (current-buffer))
  8678. (region (when (org-region-active-p)
  8679. (buffer-substring (region-beginning) (region-end))))
  8680. (remove (and region (list (region-beginning) (region-end))))
  8681. (desc region)
  8682. (link link-location)
  8683. (abbrevs org-link-abbrev-alist-local)
  8684. entry all-prefixes auto-desc)
  8685. (cond
  8686. (link-location) ; specified by arg, just use it.
  8687. ((org-in-regexp org-bracket-link-regexp 1)
  8688. ;; We do have a link at point, and we are going to edit it.
  8689. (setq remove (list (match-beginning 0) (match-end 0)))
  8690. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  8691. (setq link (read-string "Link: "
  8692. (org-link-unescape
  8693. (match-string-no-properties 1)))))
  8694. ((or (org-in-regexp org-angle-link-re)
  8695. (org-in-regexp org-plain-link-re))
  8696. ;; Convert to bracket link
  8697. (setq remove (list (match-beginning 0) (match-end 0))
  8698. link (read-string "Link: "
  8699. (org-unbracket-string "<" ">" (match-string 0)))))
  8700. ((member complete-file '((4) (16)))
  8701. ;; Completing read for file names.
  8702. (setq link (org-file-complete-link complete-file)))
  8703. (t
  8704. ;; Read link, with completion for stored links.
  8705. (org-link-fontify-links-to-this-file)
  8706. (org-switch-to-buffer-other-window "*Org Links*")
  8707. (with-current-buffer "*Org Links*"
  8708. (erase-buffer)
  8709. (insert "Insert a link.
  8710. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  8711. (when org-stored-links
  8712. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  8713. (insert (mapconcat 'org-link-prettify
  8714. (reverse org-stored-links) "\n")))
  8715. (goto-char (point-min)))
  8716. (let ((cw (selected-window)))
  8717. (select-window (get-buffer-window "*Org Links*" 'visible))
  8718. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  8719. (unless (pos-visible-in-window-p (point-max))
  8720. (org-fit-window-to-buffer))
  8721. (and (window-live-p cw) (select-window cw)))
  8722. (setq all-prefixes (append (mapcar 'car abbrevs)
  8723. (mapcar 'car org-link-abbrev-alist)
  8724. (org-link-types)))
  8725. (unwind-protect
  8726. ;; Fake a link history, containing the stored links.
  8727. (let ((org--links-history
  8728. (append (mapcar #'car org-stored-links)
  8729. org-insert-link-history)))
  8730. (setq link
  8731. (org-completing-read
  8732. "Link: "
  8733. (append
  8734. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  8735. (mapcar #'car org-stored-links))
  8736. nil nil nil
  8737. 'org--links-history
  8738. (caar org-stored-links)))
  8739. (unless (org-string-nw-p link) (user-error "No link selected"))
  8740. (dolist (l org-stored-links)
  8741. (when (equal link (cadr l))
  8742. (setq link (car l))
  8743. (setq auto-desc t)))
  8744. (when (or (member link all-prefixes)
  8745. (and (equal ":" (substring link -1))
  8746. (member (substring link 0 -1) all-prefixes)
  8747. (setq link (substring link 0 -1))))
  8748. (setq link (with-current-buffer origbuf
  8749. (org-link-try-special-completion link)))))
  8750. (set-window-configuration wcf)
  8751. (kill-buffer "*Org Links*"))
  8752. (setq entry (assoc link org-stored-links))
  8753. (or entry (push link org-insert-link-history))
  8754. (setq desc (or desc (nth 1 entry)))))
  8755. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  8756. (not org-keep-stored-link-after-insertion))
  8757. (setq org-stored-links (delq (assoc link org-stored-links)
  8758. org-stored-links)))
  8759. (when (and (string-match org-plain-link-re link)
  8760. (not (string-match org-ts-regexp link)))
  8761. ;; URL-like link, normalize the use of angular brackets.
  8762. (setq link (org-unbracket-string "<" ">" link)))
  8763. ;; Check if we are linking to the current file with a search
  8764. ;; option If yes, simplify the link by using only the search
  8765. ;; option.
  8766. (when (and buffer-file-name
  8767. (let ((case-fold-search nil))
  8768. (string-match "\\`file:\\(.+?\\)::" link)))
  8769. (let ((path (match-string-no-properties 1 link))
  8770. (search (substring-no-properties link (match-end 0))))
  8771. (save-match-data
  8772. (when (equal (file-truename buffer-file-name) (file-truename path))
  8773. ;; We are linking to this same file, with a search option
  8774. (setq link search)))))
  8775. ;; Check if we can/should use a relative path. If yes, simplify
  8776. ;; the link.
  8777. (let ((case-fold-search nil))
  8778. (when (string-match "\\`\\(file\\|docview\\):" link)
  8779. (let* ((type (match-string-no-properties 0 link))
  8780. (path-start (match-end 0))
  8781. (search (and (string-match "::\\(.*\\)\\'" link)
  8782. (match-string 1 link)))
  8783. (path
  8784. (if search
  8785. (substring-no-properties
  8786. link path-start (match-beginning 0))
  8787. (substring-no-properties link (match-end 0))))
  8788. (origpath path))
  8789. (cond
  8790. ((or (eq org-link-file-path-type 'absolute)
  8791. (equal complete-file '(16)))
  8792. (setq path (abbreviate-file-name (expand-file-name path))))
  8793. ((eq org-link-file-path-type 'noabbrev)
  8794. (setq path (expand-file-name path)))
  8795. ((eq org-link-file-path-type 'relative)
  8796. (setq path (file-relative-name path)))
  8797. (t
  8798. (save-match-data
  8799. (if (string-match (concat "^" (regexp-quote
  8800. (expand-file-name
  8801. (file-name-as-directory
  8802. default-directory))))
  8803. (expand-file-name path))
  8804. ;; We are linking a file with relative path name.
  8805. (setq path (substring (expand-file-name path)
  8806. (match-end 0)))
  8807. (setq path (abbreviate-file-name (expand-file-name path)))))))
  8808. (setq link (concat type path (and search (concat "::" search))))
  8809. (when (equal desc origpath)
  8810. (setq desc path)))))
  8811. (unless auto-desc
  8812. (let ((initial-input
  8813. (cond
  8814. (default-description)
  8815. ((not org-make-link-description-function) desc)
  8816. (t (condition-case nil
  8817. (funcall org-make-link-description-function link desc)
  8818. (error
  8819. (message "Can't get link description from `%s'"
  8820. (symbol-name org-make-link-description-function))
  8821. (sit-for 2)
  8822. nil))))))
  8823. (setq desc (if (called-interactively-p 'any)
  8824. (read-string "Description: " initial-input)
  8825. initial-input))))
  8826. (unless (string-match "\\S-" desc) (setq desc nil))
  8827. (when remove (apply 'delete-region remove))
  8828. (insert (org-make-link-string link desc))
  8829. ;; Redisplay so as the new link has proper invisible characters.
  8830. (sit-for 0)))
  8831. (defun org-link-try-special-completion (type)
  8832. "If there is completion support for link type TYPE, offer it."
  8833. (let ((fun (org-link-get-parameter type :complete)))
  8834. (if (functionp fun)
  8835. (funcall fun)
  8836. (read-string "Link (no completion support): " (concat type ":")))))
  8837. (defun org-file-complete-link (&optional arg)
  8838. "Create a file link using completion."
  8839. (let ((file (read-file-name "File: "))
  8840. (pwd (file-name-as-directory (expand-file-name ".")))
  8841. (pwd1 (file-name-as-directory (abbreviate-file-name
  8842. (expand-file-name ".")))))
  8843. (cond ((equal arg '(16))
  8844. (concat "file:"
  8845. (abbreviate-file-name (expand-file-name file))))
  8846. ((string-match
  8847. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  8848. (concat "file:" (match-string 1 file)))
  8849. ((string-match
  8850. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  8851. (expand-file-name file))
  8852. (concat "file:"
  8853. (match-string 1 (expand-file-name file))))
  8854. (t (concat "file:" file)))))
  8855. ;;; Opening/following a link
  8856. (defvar org-link-search-failed nil)
  8857. (defvar org-open-link-functions nil
  8858. "Hook for functions finding a plain text link.
  8859. These functions must take a single argument, the link content.
  8860. They will be called for links that look like [[link text][description]]
  8861. when LINK TEXT does not have a protocol like \"http:\" and does not look
  8862. like a filename (e.g. \"./blue.png\").
  8863. These functions will be called *before* Org attempts to resolve the
  8864. link by doing text searches in the current buffer - so if you want a
  8865. link \"[[target]]\" to still find \"<<target>>\", your function should
  8866. handle this as a special case.
  8867. When the function does handle the link, it must return a non-nil value.
  8868. If it decides that it is not responsible for this link, it must return
  8869. nil to indicate that that Org can continue with other options like
  8870. exact and fuzzy text search.")
  8871. (defun org-next-link (&optional search-backward)
  8872. "Move forward to the next link.
  8873. If the link is in hidden text, expose it."
  8874. (interactive "P")
  8875. (when (and org-link-search-failed (eq this-command last-command))
  8876. (goto-char (point-min))
  8877. (message "Link search wrapped back to beginning of buffer"))
  8878. (setq org-link-search-failed nil)
  8879. (let* ((pos (point))
  8880. (ct (org-context))
  8881. (a (assq :link ct))
  8882. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  8883. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  8884. ((looking-at org-any-link-re)
  8885. ;; Don't stay stuck at link without an org-link face
  8886. (forward-char (if search-backward -1 1))))
  8887. (if (funcall srch-fun org-any-link-re nil t)
  8888. (progn
  8889. (goto-char (match-beginning 0))
  8890. (when (org-invisible-p) (org-show-context)))
  8891. (goto-char pos)
  8892. (setq org-link-search-failed t)
  8893. (message "No further link found"))))
  8894. (defun org-previous-link ()
  8895. "Move backward to the previous link.
  8896. If the link is in hidden text, expose it."
  8897. (interactive)
  8898. (org-next-link t))
  8899. (defun org-translate-link (s)
  8900. "Translate a link string if a translation function has been defined."
  8901. (with-temp-buffer
  8902. (insert (org-trim s))
  8903. (org-trim (org-element-interpret-data (org-element-context)))))
  8904. (defun org-translate-link-from-planner (type path)
  8905. "Translate a link from Emacs Planner syntax so that Org can follow it.
  8906. This is still an experimental function, your mileage may vary."
  8907. (cond
  8908. ((member type '("http" "https" "news" "ftp"))
  8909. ;; standard Internet links are the same.
  8910. nil)
  8911. ((and (equal type "irc") (string-match "^//" path))
  8912. ;; Planner has two / at the beginning of an irc link, we have 1.
  8913. ;; We should have zero, actually....
  8914. (setq path (substring path 1)))
  8915. ((and (equal type "lisp") (string-match "^/" path))
  8916. ;; Planner has a slash, we do not.
  8917. (setq type "elisp" path (substring path 1)))
  8918. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  8919. ;; A typical message link. Planner has the id after the final slash,
  8920. ;; we separate it with a hash mark
  8921. (setq path (concat (match-string 1 path) "#"
  8922. (org-unbracket-string "<" ">" (match-string 2 path))))))
  8923. (cons type path))
  8924. (defun org-find-file-at-mouse (ev)
  8925. "Open file link or URL at mouse."
  8926. (interactive "e")
  8927. (mouse-set-point ev)
  8928. (org-open-at-point 'in-emacs))
  8929. (defun org-open-at-mouse (ev)
  8930. "Open file link or URL at mouse.
  8931. See the docstring of `org-open-file' for details."
  8932. (interactive "e")
  8933. (mouse-set-point ev)
  8934. (when (eq major-mode 'org-agenda-mode)
  8935. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  8936. (org-open-at-point))
  8937. (defvar org-window-config-before-follow-link nil
  8938. "The window configuration before following a link.
  8939. This is saved in case the need arises to restore it.")
  8940. ;;;###autoload
  8941. (defun org-open-at-point-global ()
  8942. "Follow a link or a time-stamp like Org mode does.
  8943. Also follow links and emails as seen by `thing-at-point'.
  8944. This command can be called in any mode to follow an external
  8945. link or a time-stamp that has Org mode syntax. Its behavior
  8946. is undefined when called on internal links like fuzzy links.
  8947. Raise a user error when there is nothing to follow."
  8948. (interactive)
  8949. (let ((tap-url (thing-at-point 'url))
  8950. (tap-email (thing-at-point 'email)))
  8951. (cond ((org-in-regexp org-any-link-re)
  8952. (org-open-link-from-string (match-string-no-properties 0)))
  8953. ((or (org-in-regexp org-ts-regexp-both nil t)
  8954. (org-in-regexp org-tsr-regexp-both nil t))
  8955. (org-follow-timestamp-link))
  8956. (tap-url (org-open-link-from-string tap-url))
  8957. (tap-email (org-open-link-from-string
  8958. (concat "mailto:" tap-email)))
  8959. (t (user-error "No link found")))))
  8960. ;;;###autoload
  8961. (defun org-open-link-from-string (s &optional arg reference-buffer)
  8962. "Open a link in the string S, as if it was in Org mode."
  8963. (interactive "sLink: \nP")
  8964. (let ((reference-buffer (or reference-buffer (current-buffer))))
  8965. (with-temp-buffer
  8966. (let ((org-inhibit-startup (not reference-buffer)))
  8967. (org-mode)
  8968. (insert s)
  8969. (goto-char (point-min))
  8970. (when reference-buffer
  8971. (setq org-link-abbrev-alist-local
  8972. (with-current-buffer reference-buffer
  8973. org-link-abbrev-alist-local)))
  8974. (org-open-at-point arg reference-buffer)))))
  8975. (defvar org-open-at-point-functions nil
  8976. "Hook that is run when following a link at point.
  8977. Functions in this hook must return t if they identify and follow
  8978. a link at point. If they don't find anything interesting at point,
  8979. they must return nil.")
  8980. (defvar org-link-search-inhibit-query nil)
  8981. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  8982. (defun org--open-doi-link (path)
  8983. "Open a \"doi\" type link.
  8984. PATH is a the path to search for, as a string."
  8985. (browse-url (url-encode-url (concat org-doi-server-url path))))
  8986. (defun org--open-elisp-link (path)
  8987. "Open a \"elisp\" type link.
  8988. PATH is the sexp to evaluate, as a string."
  8989. (let ((cmd path))
  8990. (if (or (and (org-string-nw-p
  8991. org-confirm-elisp-link-not-regexp)
  8992. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  8993. (not org-confirm-elisp-link-function)
  8994. (funcall org-confirm-elisp-link-function
  8995. (format "Execute \"%s\" as elisp? "
  8996. (org-add-props cmd nil 'face 'org-warning))))
  8997. (message "%s => %s" cmd
  8998. (if (eq (string-to-char cmd) ?\()
  8999. (eval (read cmd))
  9000. (call-interactively (read cmd))))
  9001. (user-error "Abort"))))
  9002. (defun org--open-help-link (path)
  9003. "Open a \"help\" type link.
  9004. PATH is a symbol name, as a string."
  9005. (pcase (intern path)
  9006. ((and (pred fboundp) variable) (describe-function variable))
  9007. ((and (pred boundp) function) (describe-variable function))
  9008. (name (user-error "Unknown function or variable: %s" name))))
  9009. (defun org--open-shell-link (path)
  9010. "Open a \"shell\" type link.
  9011. PATH is the command to execute, as a string."
  9012. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9013. (cmd path))
  9014. (if (or (and (org-string-nw-p
  9015. org-confirm-shell-link-not-regexp)
  9016. (string-match
  9017. org-confirm-shell-link-not-regexp cmd))
  9018. (not org-confirm-shell-link-function)
  9019. (funcall org-confirm-shell-link-function
  9020. (format "Execute \"%s\" in shell? "
  9021. (org-add-props cmd nil
  9022. 'face 'org-warning))))
  9023. (progn
  9024. (message "Executing %s" cmd)
  9025. (shell-command cmd buf)
  9026. (when (featurep 'midnight)
  9027. (setq clean-buffer-list-kill-buffer-names
  9028. (cons (buffer-name buf)
  9029. clean-buffer-list-kill-buffer-names))))
  9030. (user-error "Abort"))))
  9031. (defun org-open-at-point (&optional arg reference-buffer)
  9032. "Open link, timestamp, footnote or tags at point.
  9033. When point is on a link, follow it. Normally, files will be
  9034. opened by an appropriate application. If the optional prefix
  9035. argument ARG is non-nil, Emacs will visit the file. With
  9036. a double prefix argument, try to open outside of Emacs, in the
  9037. application the system uses for this file type.
  9038. When point is on a timestamp, open the agenda at the day
  9039. specified.
  9040. When point is a footnote definition, move to the first reference
  9041. found. If it is on a reference, move to the associated
  9042. definition.
  9043. When point is on a headline, display a list of every link in the
  9044. entry, so it is possible to pick one, or all, of them. If point
  9045. is on a tag, call `org-tags-view' instead.
  9046. When optional argument REFERENCE-BUFFER is non-nil, it should
  9047. specify a buffer from where the link search should happen. This
  9048. is used internally by `org-open-link-from-string'.
  9049. On top of syntactically correct links, this function will also
  9050. try to open links and time-stamps in comments, example
  9051. blocks... i.e., whenever point is on something looking like
  9052. a timestamp or a link."
  9053. (interactive "P")
  9054. ;; On a code block, open block's results.
  9055. (unless (call-interactively 'org-babel-open-src-block-result)
  9056. (org-load-modules-maybe)
  9057. (setq org-window-config-before-follow-link (current-window-configuration))
  9058. (org-remove-occur-highlights nil nil t)
  9059. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9060. (let* ((context
  9061. ;; Only consider supported types, even if they are not
  9062. ;; the closest one.
  9063. (org-element-lineage
  9064. (org-element-context)
  9065. '(clock footnote-definition footnote-reference headline
  9066. inlinetask link timestamp)
  9067. t))
  9068. (type (org-element-type context))
  9069. (value (org-element-property :value context)))
  9070. (cond
  9071. ;; On a headline or an inlinetask, but not on a timestamp,
  9072. ;; a link, a footnote reference.
  9073. ((memq type '(headline inlinetask))
  9074. (org-match-line org-complex-heading-regexp)
  9075. (if (and (match-beginning 5)
  9076. (>= (point) (match-beginning 5))
  9077. (< (point) (match-end 5)))
  9078. ;; On tags.
  9079. (org-tags-view arg (substring (match-string 5) 0 -1))
  9080. ;; Not on tags.
  9081. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  9082. (`(nil . ,_)
  9083. (require 'org-attach)
  9084. (org-attach-reveal 'if-exists))
  9085. (`(,links . ,links-end)
  9086. (dolist (link (if (stringp links) (list links) links))
  9087. (search-forward link nil links-end)
  9088. (goto-char (match-beginning 0))
  9089. (org-open-at-point))))))
  9090. ;; On a footnote reference or at definition's label.
  9091. ((or (eq type 'footnote-reference)
  9092. (and (eq type 'footnote-definition)
  9093. (save-excursion
  9094. ;; Do not validate action when point is on the
  9095. ;; spaces right after the footnote label, in
  9096. ;; order to be on par with behavior on links.
  9097. (skip-chars-forward " \t")
  9098. (let ((begin
  9099. (org-element-property :contents-begin context)))
  9100. (if begin (< (point) begin)
  9101. (= (org-element-property :post-affiliated context)
  9102. (line-beginning-position)))))))
  9103. (org-footnote-action))
  9104. ;; No valid context. Ignore catch-all types like `headline'.
  9105. ;; If point is on something looking like a link or
  9106. ;; a time-stamp, try opening it. It may be useful in
  9107. ;; comments, example blocks...
  9108. ((memq type '(footnote-definition headline inlinetask nil))
  9109. (call-interactively #'org-open-at-point-global))
  9110. ;; On a clock line, make sure point is on the timestamp
  9111. ;; before opening it.
  9112. ((and (eq type 'clock)
  9113. value
  9114. (>= (point) (org-element-property :begin value))
  9115. (<= (point) (org-element-property :end value)))
  9116. (org-follow-timestamp-link))
  9117. ;; Do nothing on white spaces after an object.
  9118. ((>= (point)
  9119. (save-excursion
  9120. (goto-char (org-element-property :end context))
  9121. (skip-chars-backward " \t")
  9122. (point)))
  9123. (user-error "No link found"))
  9124. ((eq type 'timestamp) (org-follow-timestamp-link))
  9125. ((eq type 'link)
  9126. (let ((type (org-element-property :type context))
  9127. (path (org-link-unescape (org-element-property :path context))))
  9128. ;; Switch back to REFERENCE-BUFFER needed when called in
  9129. ;; a temporary buffer through `org-open-link-from-string'.
  9130. (with-current-buffer (or reference-buffer (current-buffer))
  9131. (cond
  9132. ((equal type "file")
  9133. (if (string-match "[*?{]" (file-name-nondirectory path))
  9134. (dired path)
  9135. ;; Look into `org-link-parameters' in order to find
  9136. ;; a DEDICATED-FUNCTION to open file. The function
  9137. ;; will be applied on raw link instead of parsed
  9138. ;; link due to the limitation in `org-add-link-type'
  9139. ;; ("open" function called with a single argument).
  9140. ;; If no such function is found, fallback to
  9141. ;; `org-open-file'.
  9142. (let* ((option (org-element-property :search-option context))
  9143. (app (org-element-property :application context))
  9144. (dedicated-function
  9145. (org-link-get-parameter
  9146. (if app (concat type "+" app) type)
  9147. :follow)))
  9148. (if dedicated-function
  9149. (funcall dedicated-function
  9150. (concat path
  9151. (and option (concat "::" option))))
  9152. (apply #'org-open-file
  9153. path
  9154. (cond (arg)
  9155. ((equal app "emacs") 'emacs)
  9156. ((equal app "sys") 'system))
  9157. (cond ((not option) nil)
  9158. ((string-match-p "\\`[0-9]+\\'" option)
  9159. (list (string-to-number option)))
  9160. (t (list nil
  9161. (org-link-unescape option)))))))))
  9162. ((functionp (org-link-get-parameter type :follow))
  9163. (funcall (org-link-get-parameter type :follow) path))
  9164. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9165. (unless (run-hook-with-args-until-success
  9166. 'org-open-link-functions path)
  9167. (if (not arg) (org-mark-ring-push)
  9168. (switch-to-buffer-other-window
  9169. (org-get-buffer-for-internal-link (current-buffer))))
  9170. (let ((destination
  9171. (org-with-wide-buffer
  9172. (if (equal type "radio")
  9173. (org-search-radio-target
  9174. (org-element-property :path context))
  9175. (org-link-search
  9176. (if (member type '("custom-id" "coderef"))
  9177. (org-element-property :raw-link context)
  9178. path)
  9179. ;; Prevent fuzzy links from matching
  9180. ;; themselves.
  9181. (and (equal type "fuzzy")
  9182. (+ 2 (org-element-property :begin context)))))
  9183. (point))))
  9184. (unless (and (<= (point-min) destination)
  9185. (>= (point-max) destination))
  9186. (widen))
  9187. (goto-char destination))))
  9188. (t (browse-url-at-point))))))
  9189. (t (user-error "No link found")))))
  9190. (run-hook-with-args 'org-follow-link-hook)))
  9191. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9192. "Offer links in the current entry and return the selected link.
  9193. If there is only one link, return it.
  9194. If NTH is an integer, return the NTH link found.
  9195. If ZERO is a string, check also this string for a link, and if
  9196. there is one, return it."
  9197. (with-current-buffer buffer
  9198. (org-with-wide-buffer
  9199. (goto-char marker)
  9200. (let ((cnt ?0)
  9201. have-zero end links link c)
  9202. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9203. (push (match-string 0 zero) links)
  9204. (setq cnt (1- cnt) have-zero t))
  9205. (save-excursion
  9206. (org-back-to-heading t)
  9207. (setq end (save-excursion (outline-next-heading) (point)))
  9208. (while (re-search-forward org-any-link-re end t)
  9209. (push (match-string 0) links))
  9210. (setq links (org-uniquify (reverse links))))
  9211. (cond
  9212. ((null links)
  9213. (message "No links"))
  9214. ((equal (length links) 1)
  9215. (setq link (car links)))
  9216. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9217. (setq link (nth (if have-zero nth (1- nth)) links)))
  9218. (t ; we have to select a link
  9219. (save-excursion
  9220. (save-window-excursion
  9221. (delete-other-windows)
  9222. (with-output-to-temp-buffer "*Select Link*"
  9223. (dolist (l links)
  9224. (cond
  9225. ((not (string-match org-bracket-link-regexp l))
  9226. (princ (format "[%c] %s\n" (cl-incf cnt)
  9227. (org-unbracket-string "<" ">" l))))
  9228. ((match-end 3)
  9229. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9230. (match-string 3 l) (match-string 1 l))))
  9231. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9232. (match-string 1 l)))))))
  9233. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9234. (message "Select link to open, RET to open all:")
  9235. (setq c (read-char-exclusive))
  9236. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9237. (when (equal c ?q) (user-error "Abort"))
  9238. (if (equal c ?\C-m)
  9239. (setq link links)
  9240. (setq nth (- c ?0))
  9241. (when have-zero (setq nth (1+ nth)))
  9242. (unless (and (integerp nth) (>= (length links) nth))
  9243. (user-error "Invalid link selection"))
  9244. (setq link (nth (1- nth) links)))))
  9245. (cons link end)))))
  9246. ;; TODO: These functions are deprecated since `org-open-at-point'
  9247. ;; hard-codes behavior for "file+emacs" and "file+sys" types.
  9248. (defun org-open-file-with-system (path)
  9249. "Open file at PATH using the system way of opening it."
  9250. (org-open-file path 'system))
  9251. (defun org-open-file-with-emacs (path)
  9252. "Open file at PATH in Emacs."
  9253. (org-open-file path 'emacs))
  9254. ;;; File search
  9255. (defvar org-create-file-search-functions nil
  9256. "List of functions to construct the right search string for a file link.
  9257. These functions are called in turn with point at the location to
  9258. which the link should point.
  9259. A function in the hook should first test if it would like to
  9260. handle this file type, for example by checking the `major-mode'
  9261. or the file extension. If it decides not to handle this file, it
  9262. should just return nil to give other functions a chance. If it
  9263. does handle the file, it must return the search string to be used
  9264. when following the link. The search string will be part of the
  9265. file link, given after a double colon, and `org-open-at-point'
  9266. will automatically search for it. If special measures must be
  9267. taken to make the search successful, another function should be
  9268. added to the companion hook `org-execute-file-search-functions',
  9269. which see.
  9270. A function in this hook may also use `setq' to set the variable
  9271. `description' to provide a suggestion for the descriptive text to
  9272. be used for this link when it gets inserted into an Org buffer
  9273. with \\[org-insert-link].")
  9274. (defvar org-execute-file-search-functions nil
  9275. "List of functions to execute a file search triggered by a link.
  9276. Functions added to this hook must accept a single argument, the
  9277. search string that was part of the file link, the part after the
  9278. double colon. The function must first check if it would like to
  9279. handle this search, for example by checking the `major-mode' or
  9280. the file extension. If it decides not to handle this search, it
  9281. should just return nil to give other functions a chance. If it
  9282. does handle the search, it must return a non-nil value to keep
  9283. other functions from trying.
  9284. Each function can access the current prefix argument through the
  9285. variable `current-prefix-arg'. Note that a single prefix is used
  9286. to force opening a link in Emacs, so it may be good to only use a
  9287. numeric or double prefix to guide the search function.
  9288. In case this is needed, a function in this hook can also restore
  9289. the window configuration before `org-open-at-point' was called using:
  9290. (set-window-configuration org-window-config-before-follow-link)")
  9291. (defun org-search-radio-target (target)
  9292. "Search a radio target matching TARGET in current buffer.
  9293. White spaces are not significant."
  9294. (let ((re (format "<<<%s>>>"
  9295. (mapconcat #'regexp-quote
  9296. (split-string target)
  9297. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9298. (origin (point)))
  9299. (goto-char (point-min))
  9300. (catch :radio-match
  9301. (while (re-search-forward re nil t)
  9302. (backward-char)
  9303. (let ((object (org-element-context)))
  9304. (when (eq (org-element-type object) 'radio-target)
  9305. (goto-char (org-element-property :begin object))
  9306. (org-show-context 'link-search)
  9307. (throw :radio-match nil))))
  9308. (goto-char origin)
  9309. (user-error "No match for radio target: %s" target))))
  9310. (defun org-link-search (s &optional avoid-pos stealth)
  9311. "Search for a search string S.
  9312. If S starts with \"#\", it triggers a custom ID search.
  9313. If S is enclosed within parenthesis, it initiates a coderef
  9314. search.
  9315. If S is surrounded by forward slashes, it is interpreted as
  9316. a regular expression. In Org mode files, this will create an
  9317. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9318. to list matches. If the current buffer is in `dired-mode', grep
  9319. will be used to search in all files.
  9320. When AVOID-POS is given, ignore matches near that position.
  9321. When optional argument STEALTH is non-nil, do not modify
  9322. visibility around point, thus ignoring `org-show-context-detail'
  9323. variable.
  9324. Search is case-insensitive and ignores white spaces. Return type
  9325. of matched result, which is either `dedicated' or `fuzzy'."
  9326. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9327. (let* ((case-fold-search t)
  9328. (origin (point))
  9329. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9330. (starred (eq (string-to-char normalized) ?*))
  9331. (words (split-string (if starred (substring s 1) s)))
  9332. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9333. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9334. type)
  9335. (cond
  9336. ;; Check if there are any special search functions.
  9337. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9338. ((eq (string-to-char s) ?#)
  9339. ;; Look for a custom ID S if S starts with "#".
  9340. (let* ((id (substring normalized 1))
  9341. (match (org-find-property "CUSTOM_ID" id)))
  9342. (if match (progn (goto-char match) (setf type 'dedicated))
  9343. (error "No match for custom ID: %s" id))))
  9344. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9345. ;; Look for coderef targets if S is enclosed within parenthesis.
  9346. (let ((coderef (match-string-no-properties 1 normalized))
  9347. (re (substring s-single-re 1 -1)))
  9348. (goto-char (point-min))
  9349. (catch :coderef-match
  9350. (while (re-search-forward re nil t)
  9351. (let ((element (org-element-at-point)))
  9352. (when (and (memq (org-element-type element)
  9353. '(example-block src-block))
  9354. ;; Build proper regexp according to current
  9355. ;; block's label format.
  9356. (let ((label-fmt
  9357. (regexp-quote
  9358. (or (org-element-property :label-fmt element)
  9359. org-coderef-label-format))))
  9360. (save-excursion
  9361. (beginning-of-line)
  9362. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9363. (format label-fmt coderef))))))
  9364. (setq type 'dedicated)
  9365. (goto-char (match-beginning 1))
  9366. (throw :coderef-match nil))))
  9367. (goto-char origin)
  9368. (error "No match for coderef: %s" coderef))))
  9369. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9370. ;; Look for a regular expression.
  9371. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9372. (match-string 1 s)))
  9373. ;; From here, we handle fuzzy links.
  9374. ;;
  9375. ;; Look for targets, only if not in a headline search.
  9376. ((and (not starred)
  9377. (let ((target (format "<<%s>>" s-multi-re)))
  9378. (catch :target-match
  9379. (goto-char (point-min))
  9380. (while (re-search-forward target nil t)
  9381. (backward-char)
  9382. (let ((context (org-element-context)))
  9383. (when (eq (org-element-type context) 'target)
  9384. (setq type 'dedicated)
  9385. (goto-char (org-element-property :begin context))
  9386. (throw :target-match t))))
  9387. nil))))
  9388. ;; Look for elements named after S, only if not in a headline
  9389. ;; search.
  9390. ((and (not starred)
  9391. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9392. (catch :name-match
  9393. (goto-char (point-min))
  9394. (while (re-search-forward name nil t)
  9395. (let ((element (org-element-at-point)))
  9396. (when (equal words
  9397. (split-string
  9398. (org-element-property :name element)))
  9399. (setq type 'dedicated)
  9400. (beginning-of-line)
  9401. (throw :name-match t))))
  9402. nil))))
  9403. ;; Regular text search. Prefer headlines in Org mode buffers.
  9404. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9405. ;; statistics cookies and tags.
  9406. ((and (derived-mode-p 'org-mode)
  9407. (let ((title-re
  9408. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9409. org-outline-regexp-bol
  9410. org-comment-string
  9411. (mapconcat #'regexp-quote words ".+")))
  9412. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9413. (comment-re (eval-when-compile
  9414. (format "\\`%s[ \t]+" org-comment-string))))
  9415. (goto-char (point-min))
  9416. (catch :found
  9417. (while (re-search-forward title-re nil t)
  9418. (when (equal words
  9419. (split-string
  9420. (replace-regexp-in-string
  9421. cookie-re ""
  9422. (replace-regexp-in-string
  9423. comment-re "" (org-get-heading t t t)))))
  9424. (throw :found t)))
  9425. nil)))
  9426. (beginning-of-line)
  9427. (setq type 'dedicated))
  9428. ;; Offer to create non-existent headline depending on
  9429. ;; `org-link-search-must-match-exact-headline'.
  9430. ((and (derived-mode-p 'org-mode)
  9431. (not org-link-search-inhibit-query)
  9432. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9433. (yes-or-no-p "No match - create this as a new heading? "))
  9434. (goto-char (point-max))
  9435. (unless (bolp) (newline))
  9436. (org-insert-heading nil t t)
  9437. (insert s "\n")
  9438. (beginning-of-line 0))
  9439. ;; Only headlines are looked after. No need to process
  9440. ;; further: throw an error.
  9441. ((and (derived-mode-p 'org-mode)
  9442. (or starred org-link-search-must-match-exact-headline))
  9443. (goto-char origin)
  9444. (error "No match for fuzzy expression: %s" normalized))
  9445. ;; Regular text search.
  9446. ((catch :fuzzy-match
  9447. (goto-char (point-min))
  9448. (while (re-search-forward s-multi-re nil t)
  9449. ;; Skip match if it contains AVOID-POS or it is included in
  9450. ;; a link with a description but outside the description.
  9451. (unless (or (and avoid-pos
  9452. (<= (match-beginning 0) avoid-pos)
  9453. (> (match-end 0) avoid-pos))
  9454. (and (save-match-data
  9455. (org-in-regexp org-bracket-link-regexp))
  9456. (match-beginning 3)
  9457. (or (> (match-beginning 3) (point))
  9458. (<= (match-end 3) (point)))
  9459. (org-element-lineage
  9460. (save-match-data (org-element-context))
  9461. '(link) t)))
  9462. (goto-char (match-beginning 0))
  9463. (setq type 'fuzzy)
  9464. (throw :fuzzy-match t)))
  9465. nil))
  9466. ;; All failed. Throw an error.
  9467. (t (goto-char origin)
  9468. (error "No match for fuzzy expression: %s" normalized)))
  9469. ;; Disclose surroundings of match, if appropriate.
  9470. (when (and (derived-mode-p 'org-mode) (not stealth))
  9471. (org-show-context 'link-search))
  9472. type))
  9473. (defun org-get-buffer-for-internal-link (buffer)
  9474. "Return a buffer to be used for displaying the link target of internal links."
  9475. (cond
  9476. ((not org-display-internal-link-with-indirect-buffer)
  9477. buffer)
  9478. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9479. (message "Buffer is already a clone, not making another one")
  9480. ;; we also do not modify visibility in this case
  9481. buffer)
  9482. (t ; make a new indirect buffer for displaying the link
  9483. (let* ((bn (buffer-name buffer))
  9484. (ibn (concat bn "(Clone)"))
  9485. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9486. (with-current-buffer ib (org-overview))
  9487. ib))))
  9488. (defun org-do-occur (regexp &optional cleanup)
  9489. "Call the Emacs command `occur'.
  9490. If CLEANUP is non-nil, remove the printout of the regular expression
  9491. in the *Occur* buffer. This is useful if the regex is long and not useful
  9492. to read."
  9493. (occur regexp)
  9494. (when cleanup
  9495. (let ((cwin (selected-window)) win beg end)
  9496. (when (setq win (get-buffer-window "*Occur*"))
  9497. (select-window win))
  9498. (goto-char (point-min))
  9499. (when (re-search-forward "match[a-z]+" nil t)
  9500. (setq beg (match-end 0))
  9501. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9502. (setq end (1- (match-beginning 0)))))
  9503. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9504. (goto-char (point-min))
  9505. (select-window cwin))))
  9506. ;;; The Mark Ring
  9507. (defvar org-mark-ring nil
  9508. "Mark ring for positions before jumps in Org mode.")
  9509. (defvar org-mark-ring-last-goto nil
  9510. "Last position in the mark ring used to go back.")
  9511. ;; Fill and close the ring
  9512. (setq org-mark-ring nil)
  9513. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  9514. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  9515. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  9516. org-mark-ring)
  9517. (defun org-mark-ring-push (&optional pos buffer)
  9518. "Put the current position into the mark ring and rotate it.
  9519. Also push position into the Emacs mark ring. If optional
  9520. argument POS and BUFFER are not nil, mark this location instead."
  9521. (interactive)
  9522. (let ((pos (or pos (point)))
  9523. (buffer (or buffer (current-buffer))))
  9524. (with-current-buffer buffer
  9525. (org-with-point-at pos (push-mark nil t)))
  9526. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  9527. (move-marker (car org-mark-ring) pos buffer))
  9528. (message
  9529. (substitute-command-keys
  9530. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  9531. (defun org-mark-ring-goto (&optional n)
  9532. "Jump to the previous position in the mark ring.
  9533. With prefix arg N, jump back that many stored positions. When
  9534. called several times in succession, walk through the entire ring.
  9535. Org mode commands jumping to a different position in the current file,
  9536. or to another Org file, automatically push the old position onto the ring."
  9537. (interactive "p")
  9538. (let (p m)
  9539. (if (eq last-command this-command)
  9540. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  9541. (setq p org-mark-ring))
  9542. (setq org-mark-ring-last-goto p)
  9543. (setq m (car p))
  9544. (pop-to-buffer-same-window (marker-buffer m))
  9545. (goto-char m)
  9546. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  9547. (defun org-add-angle-brackets (s)
  9548. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  9549. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  9550. s)
  9551. ;;; Following specific links
  9552. (defvar org-agenda-buffer-tmp-name)
  9553. (defvar org-agenda-start-on-weekday)
  9554. (defun org-follow-timestamp-link ()
  9555. "Open an agenda view for the time-stamp date/range at point."
  9556. (cond
  9557. ((org-at-date-range-p t)
  9558. (let ((org-agenda-start-on-weekday)
  9559. (t1 (match-string 1))
  9560. (t2 (match-string 2)) tt1 tt2)
  9561. (setq tt1 (time-to-days (org-time-string-to-time t1))
  9562. tt2 (time-to-days (org-time-string-to-time t2)))
  9563. (let ((org-agenda-buffer-tmp-name
  9564. (format "*Org Agenda(a:%s)"
  9565. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  9566. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  9567. ((org-at-timestamp-p 'lax)
  9568. (let ((org-agenda-buffer-tmp-name
  9569. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  9570. (org-agenda-list nil (time-to-days (org-time-string-to-time
  9571. (substring (match-string 1) 0 10)))
  9572. 1)))
  9573. (t (error "This should not happen"))))
  9574. ;;; Following file links
  9575. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  9576. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  9577. (declare-function mailcap-mime-info
  9578. "mailcap" (string &optional request no-decode))
  9579. (defvar org-wait nil)
  9580. (defun org-open-file (path &optional in-emacs line search)
  9581. "Open the file at PATH.
  9582. First, this expands any special file name abbreviations. Then the
  9583. configuration variable `org-file-apps' is checked if it contains an
  9584. entry for this file type, and if yes, the corresponding command is launched.
  9585. If no application is found, Emacs simply visits the file.
  9586. With optional prefix argument IN-EMACS, Emacs will visit the file.
  9587. With a double \\[universal-argument] \\[universal-argument] \
  9588. prefix arg, Org tries to avoid opening in Emacs
  9589. and to use an external application to visit the file.
  9590. Optional LINE specifies a line to go to, optional SEARCH a string
  9591. to search for. If LINE or SEARCH is given, the file will be
  9592. opened in Emacs, unless an entry from org-file-apps that makes
  9593. use of groups in a regexp matches.
  9594. If you want to change the way frames are used when following a
  9595. link, please customize `org-link-frame-setup'.
  9596. If the file does not exist, an error is thrown."
  9597. (let* ((file (if (equal path "")
  9598. buffer-file-name
  9599. (substitute-in-file-name (expand-file-name path))))
  9600. (file-apps (append org-file-apps (org-default-apps)))
  9601. (apps (cl-remove-if
  9602. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9603. (apps-dlink (cl-remove-if-not
  9604. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9605. (remp (and (assq 'remote apps) (file-remote-p file)))
  9606. (dirp (unless remp (file-directory-p file)))
  9607. (file (if (and dirp org-open-directory-means-index-dot-org)
  9608. (concat (file-name-as-directory file) "index.org")
  9609. file))
  9610. (a-m-a-p (assq 'auto-mode apps))
  9611. (dfile (downcase file))
  9612. ;; Reconstruct the original link from the PATH, LINE and
  9613. ;; SEARCH args.
  9614. (link (cond (line (concat file "::" (number-to-string line)))
  9615. (search (concat file "::" search))
  9616. (t file)))
  9617. (dlink (downcase link))
  9618. (ext
  9619. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  9620. (match-string 1 dfile)))
  9621. (save-position-maybe
  9622. (let ((old-buffer (current-buffer))
  9623. (old-pos (point))
  9624. (old-mode major-mode))
  9625. (lambda ()
  9626. (and (derived-mode-p 'org-mode)
  9627. (eq old-mode 'org-mode)
  9628. (or (not (eq old-buffer (current-buffer)))
  9629. (not (eq old-pos (point))))
  9630. (org-mark-ring-push old-pos old-buffer)))))
  9631. cmd link-match-data)
  9632. (cond
  9633. ((member in-emacs '((16) system))
  9634. (setq cmd (cdr (assq 'system apps))))
  9635. (in-emacs (setq cmd 'emacs))
  9636. (t
  9637. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  9638. (and dirp (cdr (assq 'directory apps)))
  9639. ;; First, try matching against apps-dlink if we
  9640. ;; get a match here, store the match data for
  9641. ;; later.
  9642. (let ((match (assoc-default dlink apps-dlink
  9643. 'string-match)))
  9644. (if match
  9645. (progn (setq link-match-data (match-data))
  9646. match)
  9647. (progn (setq in-emacs (or in-emacs line search))
  9648. nil))) ; if we have no match in apps-dlink,
  9649. ; always open the file in emacs if line or search
  9650. ; is given (for backwards compatibility)
  9651. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  9652. 'string-match)
  9653. (cdr (assoc ext apps))
  9654. (cdr (assq t apps))))))
  9655. (when (eq cmd 'system)
  9656. (setq cmd (cdr (assq 'system apps))))
  9657. (when (eq cmd 'default)
  9658. (setq cmd (cdr (assoc t apps))))
  9659. (when (eq cmd 'mailcap)
  9660. (require 'mailcap)
  9661. (mailcap-parse-mailcaps)
  9662. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  9663. (command (mailcap-mime-info mime-type)))
  9664. (if (stringp command)
  9665. (setq cmd command)
  9666. (setq cmd 'emacs))))
  9667. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  9668. (not (file-exists-p file))
  9669. (not org-open-non-existing-files))
  9670. (user-error "No such file: %s" file))
  9671. (cond
  9672. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  9673. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  9674. (while (string-match "['\"]%s['\"]" cmd)
  9675. (setq cmd (replace-match "%s" t t cmd)))
  9676. (setq cmd (replace-regexp-in-string
  9677. "%s"
  9678. (shell-quote-argument (convert-standard-filename file))
  9679. cmd
  9680. nil t))
  9681. ;; Replace "%1", "%2" etc. in command with group matches from regex
  9682. (save-match-data
  9683. (let ((match-index 1)
  9684. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  9685. (set-match-data link-match-data)
  9686. (while (<= match-index number-of-groups)
  9687. (let ((regex (concat "%" (number-to-string match-index)))
  9688. (replace-with (match-string match-index dlink)))
  9689. (while (string-match regex cmd)
  9690. (setq cmd (replace-match replace-with t t cmd))))
  9691. (setq match-index (+ match-index 1)))))
  9692. (save-window-excursion
  9693. (message "Running %s...done" cmd)
  9694. (start-process-shell-command cmd nil cmd)
  9695. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  9696. ((or (stringp cmd)
  9697. (eq cmd 'emacs))
  9698. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  9699. (widen)
  9700. (cond (line (org-goto-line line)
  9701. (when (derived-mode-p 'org-mode) (org-reveal)))
  9702. (search (condition-case err
  9703. (org-link-search search)
  9704. ;; Save position before error-ing out so user
  9705. ;; can easily move back to the original buffer.
  9706. (error (funcall save-position-maybe)
  9707. (error (nth 1 err)))))))
  9708. ((functionp cmd)
  9709. (save-match-data
  9710. (set-match-data link-match-data)
  9711. (condition-case nil
  9712. (funcall cmd file link)
  9713. ;; FIXME: Remove this check when most default installations
  9714. ;; of Emacs have at least Org 9.0.
  9715. ((debug wrong-number-of-arguments wrong-type-argument
  9716. invalid-function)
  9717. (user-error "Please see Org News for version 9.0 about \
  9718. `org-file-apps'--Lisp error: %S" cmd)))))
  9719. ((consp cmd)
  9720. ;; FIXME: Remove this check when most default installations of
  9721. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  9722. ;; fall back to `org-link-frame-setup' for an old usage of
  9723. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  9724. (user-error "Please see Org News for version 9.0 about \
  9725. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  9726. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  9727. (funcall save-position-maybe)))
  9728. (defun org-file-apps-entry-match-against-dlink-p (entry)
  9729. "This function returns non-nil if `entry' uses a regular
  9730. expression which should be matched against the whole link by
  9731. org-open-file.
  9732. It assumes that is the case when the entry uses a regular
  9733. expression which has at least one grouping construct and the
  9734. action is either a lisp form or a command string containing
  9735. `%1', i.e. using at least one subexpression match as a
  9736. parameter."
  9737. (let ((selector (car entry))
  9738. (action (cdr entry)))
  9739. (if (stringp selector)
  9740. (and (> (regexp-opt-depth selector) 0)
  9741. (or (and (stringp action)
  9742. (string-match "%[0-9]" action))
  9743. (consp action)))
  9744. nil)))
  9745. (defun org-default-apps ()
  9746. "Return the default applications for this operating system."
  9747. (cond
  9748. ((eq system-type 'darwin)
  9749. org-file-apps-defaults-macosx)
  9750. ((eq system-type 'windows-nt)
  9751. org-file-apps-defaults-windowsnt)
  9752. (t org-file-apps-defaults-gnu)))
  9753. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  9754. "Convert extensions to regular expressions in the cars of LIST.
  9755. Also, weed out any non-string entries, because the return value is used
  9756. only for regexp matching.
  9757. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  9758. point to the symbol `emacs', indicating that the file should
  9759. be opened in Emacs."
  9760. (append
  9761. (delq nil
  9762. (mapcar (lambda (x)
  9763. (unless (not (stringp (car x)))
  9764. (if (string-match "\\W" (car x))
  9765. x
  9766. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  9767. list))
  9768. (when add-auto-mode
  9769. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  9770. ;;;; Refiling
  9771. (defun org-get-org-file ()
  9772. "Read a filename, with default directory `org-directory'."
  9773. (let ((default (or org-default-notes-file remember-data-file)))
  9774. (read-file-name (format "File name [%s]: " default)
  9775. (file-name-as-directory org-directory)
  9776. default)))
  9777. (defun org-notes-order-reversed-p ()
  9778. "Check if the current file should receive notes in reversed order."
  9779. (cond
  9780. ((not org-reverse-note-order) nil)
  9781. ((eq t org-reverse-note-order) t)
  9782. ((not (listp org-reverse-note-order)) nil)
  9783. (t (catch 'exit
  9784. (dolist (entry org-reverse-note-order)
  9785. (when (string-match (car entry) buffer-file-name)
  9786. (throw 'exit (cdr entry))))))))
  9787. (defvar org-refile-target-table nil
  9788. "The list of refile targets, created by `org-refile'.")
  9789. (defvar org-agenda-new-buffers nil
  9790. "Buffers created to visit agenda files.")
  9791. (defvar org-refile-cache nil
  9792. "Cache for refile targets.")
  9793. (defvar org-refile-markers nil
  9794. "All the markers used for caching refile locations.")
  9795. (defun org-refile-marker (pos)
  9796. "Get a new refile marker, but only if caching is in use."
  9797. (if (not org-refile-use-cache)
  9798. pos
  9799. (let ((m (make-marker)))
  9800. (move-marker m pos)
  9801. (push m org-refile-markers)
  9802. m)))
  9803. (defun org-refile-cache-clear ()
  9804. "Clear the refile cache and disable all the markers."
  9805. (dolist (m org-refile-markers) (move-marker m nil))
  9806. (setq org-refile-markers nil)
  9807. (setq org-refile-cache nil)
  9808. (message "Refile cache has been cleared"))
  9809. (defun org-refile-cache-check-set (set)
  9810. "Check if all the markers in the cache still have live buffers."
  9811. (let (marker)
  9812. (catch 'exit
  9813. (while (and set (setq marker (nth 3 (pop set))))
  9814. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  9815. (when (and marker (null (marker-buffer marker)))
  9816. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  9817. (sit-for 3)
  9818. (throw 'exit nil)))
  9819. t)))
  9820. (defun org-refile-cache-put (set &rest identifiers)
  9821. "Push the refile targets SET into the cache, under IDENTIFIERS."
  9822. (let* ((key (sha1 (prin1-to-string identifiers)))
  9823. (entry (assoc key org-refile-cache)))
  9824. (if entry
  9825. (setcdr entry set)
  9826. (push (cons key set) org-refile-cache))))
  9827. (defun org-refile-cache-get (&rest identifiers)
  9828. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  9829. (cond
  9830. ((not org-refile-cache) nil)
  9831. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  9832. (t
  9833. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  9834. org-refile-cache))))
  9835. (and set (org-refile-cache-check-set set) set)))))
  9836. (defvar org-outline-path-cache nil
  9837. "Alist between buffer positions and outline paths.
  9838. It value is an alist (POSITION . PATH) where POSITION is the
  9839. buffer position at the beginning of an entry and PATH is a list
  9840. of strings describing the outline path for that entry, in reverse
  9841. order.")
  9842. (defun org-refile-get-targets (&optional default-buffer)
  9843. "Produce a table with refile targets."
  9844. (let ((case-fold-search nil)
  9845. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  9846. (entries (or org-refile-targets '((nil . (:level . 1)))))
  9847. targets tgs files desc descre)
  9848. (message "Getting targets...")
  9849. (with-current-buffer (or default-buffer (current-buffer))
  9850. (dolist (entry entries)
  9851. (setq files (car entry) desc (cdr entry))
  9852. (cond
  9853. ((null files) (setq files (list (current-buffer))))
  9854. ((eq files 'org-agenda-files)
  9855. (setq files (org-agenda-files 'unrestricted)))
  9856. ((and (symbolp files) (fboundp files))
  9857. (setq files (funcall files)))
  9858. ((and (symbolp files) (boundp files))
  9859. (setq files (symbol-value files))))
  9860. (when (stringp files) (setq files (list files)))
  9861. (cond
  9862. ((eq (car desc) :tag)
  9863. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  9864. ((eq (car desc) :todo)
  9865. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  9866. ((eq (car desc) :regexp)
  9867. (setq descre (cdr desc)))
  9868. ((eq (car desc) :level)
  9869. (setq descre (concat "^\\*\\{" (number-to-string
  9870. (if org-odd-levels-only
  9871. (1- (* 2 (cdr desc)))
  9872. (cdr desc)))
  9873. "\\}[ \t]")))
  9874. ((eq (car desc) :maxlevel)
  9875. (setq descre (concat "^\\*\\{1," (number-to-string
  9876. (if org-odd-levels-only
  9877. (1- (* 2 (cdr desc)))
  9878. (cdr desc)))
  9879. "\\}[ \t]")))
  9880. (t (error "Bad refiling target description %s" desc)))
  9881. (dolist (f files)
  9882. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  9883. (or
  9884. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  9885. (progn
  9886. (when (bufferp f)
  9887. (setq f (buffer-file-name (buffer-base-buffer f))))
  9888. (setq f (and f (expand-file-name f)))
  9889. (when (eq org-refile-use-outline-path 'file)
  9890. (push (list (file-name-nondirectory f) f nil nil) tgs))
  9891. (when (eq org-refile-use-outline-path 'buffer-name)
  9892. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  9893. (when (eq org-refile-use-outline-path 'full-file-path)
  9894. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  9895. (org-with-wide-buffer
  9896. (goto-char (point-min))
  9897. (setq org-outline-path-cache nil)
  9898. (while (re-search-forward descre nil t)
  9899. (beginning-of-line)
  9900. (let ((case-fold-search nil))
  9901. (looking-at org-complex-heading-regexp))
  9902. (let ((begin (point))
  9903. (heading (match-string-no-properties 4)))
  9904. (unless (or (and
  9905. org-refile-target-verify-function
  9906. (not
  9907. (funcall org-refile-target-verify-function)))
  9908. (not heading))
  9909. (let ((re (format org-complex-heading-regexp-format
  9910. (regexp-quote heading)))
  9911. (target
  9912. (if (not org-refile-use-outline-path) heading
  9913. (mapconcat
  9914. #'identity
  9915. (append
  9916. (pcase org-refile-use-outline-path
  9917. (`file (list (file-name-nondirectory
  9918. (buffer-file-name
  9919. (buffer-base-buffer)))))
  9920. (`full-file-path
  9921. (list (buffer-file-name
  9922. (buffer-base-buffer))))
  9923. (`buffer-name
  9924. (list (buffer-name
  9925. (buffer-base-buffer))))
  9926. (_ nil))
  9927. (mapcar (lambda (s) (replace-regexp-in-string
  9928. "/" "\\/" s nil t))
  9929. (org-get-outline-path t t)))
  9930. "/"))))
  9931. (push (list target f re (org-refile-marker (point)))
  9932. tgs)))
  9933. (when (= (point) begin)
  9934. ;; Verification function has not moved point.
  9935. (end-of-line)))))))
  9936. (when org-refile-use-cache
  9937. (org-refile-cache-put tgs (buffer-file-name) descre))
  9938. (setq targets (append tgs targets))))))
  9939. (message "Getting targets...done")
  9940. (delete-dups (nreverse targets))))
  9941. (defun org--get-outline-path-1 (&optional use-cache)
  9942. "Return outline path to current headline.
  9943. Outline path is a list of strings, in reverse order. When
  9944. optional argument USE-CACHE is non-nil, make use of a cache. See
  9945. `org-get-outline-path' for details.
  9946. Assume buffer is widened and point is on a headline."
  9947. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  9948. (let ((p (point))
  9949. (heading (let ((case-fold-search nil))
  9950. (looking-at org-complex-heading-regexp)
  9951. (if (not (match-end 4)) ""
  9952. ;; Remove statistics cookies.
  9953. (org-trim
  9954. (org-link-display-format
  9955. (replace-regexp-in-string
  9956. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  9957. (match-string-no-properties 4))))))))
  9958. (if (org-up-heading-safe)
  9959. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  9960. (when use-cache
  9961. (push (cons p path) org-outline-path-cache))
  9962. path)
  9963. ;; This is a new root node. Since we assume we are moving
  9964. ;; forward, we can drop previous cache so as to limit number
  9965. ;; of associations there.
  9966. (let ((path (list heading)))
  9967. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  9968. path)))))
  9969. (defun org-get-outline-path (&optional with-self use-cache)
  9970. "Return the outline path to the current entry.
  9971. An outline path is a list of ancestors for current headline, as
  9972. a list of strings. Statistics cookies are removed and links are
  9973. replaced with their description, if any, or their path otherwise.
  9974. When optional argument WITH-SELF is non-nil, the path also
  9975. includes the current headline.
  9976. When optional argument USE-CACHE is non-nil, cache outline paths
  9977. between calls to this function so as to avoid backtracking. This
  9978. argument is useful when planning to find more than one outline
  9979. path in the same document. In that case, there are two
  9980. conditions to satisfy:
  9981. - `org-outline-path-cache' is set to nil before starting the
  9982. process;
  9983. - outline paths are computed by increasing buffer positions."
  9984. (org-with-wide-buffer
  9985. (and (or (and with-self (org-back-to-heading t))
  9986. (org-up-heading-safe))
  9987. (reverse (org--get-outline-path-1 use-cache)))))
  9988. (defun org-format-outline-path (path &optional width prefix separator)
  9989. "Format the outline path PATH for display.
  9990. WIDTH is the maximum number of characters that is available.
  9991. PREFIX is a prefix to be included in the returned string,
  9992. such as the file name.
  9993. SEPARATOR is inserted between the different parts of the path,
  9994. the default is \"/\"."
  9995. (setq width (or width 79))
  9996. (setq path (delq nil path))
  9997. (unless (> width 0)
  9998. (user-error "Argument `width' must be positive"))
  9999. (setq separator (or separator "/"))
  10000. (let* ((org-odd-levels-only nil)
  10001. (fpath (concat
  10002. prefix (and prefix path separator)
  10003. (mapconcat
  10004. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10005. (cl-loop for head in path
  10006. for n from 0
  10007. collect (org-add-props
  10008. head nil 'face
  10009. (nth (% n org-n-level-faces) org-level-faces)))
  10010. separator))))
  10011. (when (> (length fpath) width)
  10012. (if (< width 7)
  10013. ;; It's unlikely that `width' will be this small, but don't
  10014. ;; waste characters by adding ".." if it is.
  10015. (setq fpath (substring fpath 0 width))
  10016. (setf (substring fpath (- width 2)) "..")))
  10017. fpath))
  10018. (defun org-display-outline-path (&optional file current separator just-return-string)
  10019. "Display the current outline path in the echo area.
  10020. If FILE is non-nil, prepend the output with the file name.
  10021. If CURRENT is non-nil, append the current heading to the output.
  10022. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10023. the different parts of the path and defaults to \"/\".
  10024. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10025. (interactive "P")
  10026. (let* (case-fold-search
  10027. (bfn (buffer-file-name (buffer-base-buffer)))
  10028. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10029. res)
  10030. (when current (setq path (append path
  10031. (save-excursion
  10032. (org-back-to-heading t)
  10033. (when (looking-at org-complex-heading-regexp)
  10034. (list (match-string 4)))))))
  10035. (setq res
  10036. (org-format-outline-path
  10037. path
  10038. (1- (frame-width))
  10039. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10040. separator))
  10041. (if just-return-string
  10042. (org-no-properties res)
  10043. (org-unlogged-message "%s" res))))
  10044. (defvar org-refile-history nil
  10045. "History for refiling operations.")
  10046. (defvar org-after-refile-insert-hook nil
  10047. "Hook run after `org-refile' has inserted its stuff at the new location.
  10048. Note that this is still *before* the stuff will be removed from
  10049. the *old* location.")
  10050. (defvar org-capture-last-stored-marker)
  10051. (defvar org-refile-keep nil
  10052. "Non-nil means `org-refile' will copy instead of refile.")
  10053. (defun org-copy ()
  10054. "Like `org-refile', but copy."
  10055. (interactive)
  10056. (let ((org-refile-keep t))
  10057. (org-refile nil nil nil "Copy")))
  10058. (defun org-refile (&optional arg default-buffer rfloc msg)
  10059. "Move the entry or entries at point to another heading.
  10060. The list of target headings is compiled using the information in
  10061. `org-refile-targets', which see.
  10062. At the target location, the entry is filed as a subitem of the
  10063. target heading. Depending on `org-reverse-note-order', the new
  10064. subitem will either be the first or the last subitem.
  10065. If there is an active region, all entries in that region will be
  10066. refiled. However, the region must fulfill the requirement that
  10067. the first heading sets the top-level of the moved text.
  10068. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10069. location
  10070. and not actually move anything.
  10071. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10072. location where the last
  10073. refiling operation has put the subtree.
  10074. With a numeric prefix argument of `2', refile to the running clock.
  10075. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10076. being set to t and copy to the target location, don't move it.
  10077. Beware that keeping refiled entries may result in duplicated ID
  10078. properties.
  10079. RFLOC can be a refile location obtained in a different way.
  10080. MSG is a string to replace \"Refile\" in the default prompt with
  10081. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10082. See also `org-refile-use-outline-path'.
  10083. If you are using target caching (see `org-refile-use-cache'), you
  10084. have to clear the target cache in order to find new targets.
  10085. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10086. prefix argument (`C-u C-u C-u C-c C-w')."
  10087. (interactive "P")
  10088. (if (member arg '(0 (64)))
  10089. (org-refile-cache-clear)
  10090. (let* ((actionmsg (cond (msg msg)
  10091. ((equal arg 3) "Refile (and keep)")
  10092. (t "Refile")))
  10093. (regionp (org-region-active-p))
  10094. (region-start (and regionp (region-beginning)))
  10095. (region-end (and regionp (region-end)))
  10096. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10097. pos it nbuf file level reversed)
  10098. (setq last-command nil)
  10099. (when regionp
  10100. (goto-char region-start)
  10101. (or (bolp) (goto-char (point-at-bol)))
  10102. (setq region-start (point))
  10103. (unless (or (org-kill-is-subtree-p
  10104. (buffer-substring region-start region-end))
  10105. (prog1 org-refile-active-region-within-subtree
  10106. (let ((s (point-at-eol)))
  10107. (org-toggle-heading)
  10108. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10109. (user-error "The region is not a (sequence of) subtree(s)")))
  10110. (if (equal arg '(16))
  10111. (org-refile-goto-last-stored)
  10112. (when (or
  10113. (and (equal arg 2)
  10114. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10115. (prog1
  10116. (setq it (list (or org-clock-heading "running clock")
  10117. (buffer-file-name
  10118. (marker-buffer org-clock-hd-marker))
  10119. ""
  10120. (marker-position org-clock-hd-marker)))
  10121. (setq arg nil)))
  10122. (setq it
  10123. (or rfloc
  10124. (let (heading-text)
  10125. (save-excursion
  10126. (unless (and arg (listp arg))
  10127. (org-back-to-heading t)
  10128. (setq heading-text
  10129. (replace-regexp-in-string
  10130. org-bracket-link-regexp
  10131. "\\3"
  10132. (or (nth 4 (org-heading-components))
  10133. ""))))
  10134. (org-refile-get-location
  10135. (cond ((and arg (listp arg)) "Goto")
  10136. (regionp (concat actionmsg " region to"))
  10137. (t (concat actionmsg " subtree \""
  10138. heading-text "\" to")))
  10139. default-buffer
  10140. (and (not (equal '(4) arg))
  10141. org-refile-allow-creating-parent-nodes)))))))
  10142. (setq file (nth 1 it)
  10143. pos (nth 3 it))
  10144. (when (and (not arg)
  10145. pos
  10146. (equal (buffer-file-name) file)
  10147. (if regionp
  10148. (and (>= pos region-start)
  10149. (<= pos region-end))
  10150. (and (>= pos (point))
  10151. (< pos (save-excursion
  10152. (org-end-of-subtree t t))))))
  10153. (error "Cannot refile to position inside the tree or region"))
  10154. (setq nbuf (or (find-buffer-visiting file)
  10155. (find-file-noselect file)))
  10156. (if (and arg (not (equal arg 3)))
  10157. (progn
  10158. (pop-to-buffer-same-window nbuf)
  10159. (goto-char (cond (pos)
  10160. ((org-notes-order-reversed-p) (point-min))
  10161. (t (point-max))))
  10162. (org-show-context 'org-goto))
  10163. (if regionp
  10164. (progn
  10165. (org-kill-new (buffer-substring region-start region-end))
  10166. (org-save-markers-in-region region-start region-end))
  10167. (org-copy-subtree 1 nil t))
  10168. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10169. (find-file-noselect file)))
  10170. (setq reversed (org-notes-order-reversed-p))
  10171. (org-with-wide-buffer
  10172. (if pos
  10173. (progn
  10174. (goto-char pos)
  10175. (setq level (org-get-valid-level (funcall outline-level) 1))
  10176. (goto-char
  10177. (if reversed
  10178. (or (outline-next-heading) (point-max))
  10179. (or (save-excursion (org-get-next-sibling))
  10180. (org-end-of-subtree t t)
  10181. (point-max)))))
  10182. (setq level 1)
  10183. (if (not reversed)
  10184. (goto-char (point-max))
  10185. (goto-char (point-min))
  10186. (or (outline-next-heading) (goto-char (point-max)))))
  10187. (unless (bolp) (newline))
  10188. (org-paste-subtree level nil nil t)
  10189. (when org-log-refile
  10190. (org-add-log-setup 'refile nil nil org-log-refile)
  10191. (unless (eq org-log-refile 'note)
  10192. (save-excursion (org-add-log-note))))
  10193. (and org-auto-align-tags
  10194. (let ((org-loop-over-headlines-in-active-region nil))
  10195. (org-align-tags)))
  10196. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10197. :last-refile)))
  10198. (when bookmark-name
  10199. (with-demoted-errors
  10200. (bookmark-set bookmark-name))))
  10201. ;; If we are refiling for capture, make sure that the
  10202. ;; last-capture pointers point here
  10203. (when (bound-and-true-p org-capture-is-refiling)
  10204. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10205. :last-capture-marker)))
  10206. (when bookmark-name
  10207. (with-demoted-errors
  10208. (bookmark-set bookmark-name))))
  10209. (move-marker org-capture-last-stored-marker (point)))
  10210. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10211. (run-hooks 'org-after-refile-insert-hook)))
  10212. (unless org-refile-keep
  10213. (if regionp
  10214. (delete-region (point) (+ (point) (- region-end region-start)))
  10215. (org-preserve-local-variables
  10216. (delete-region
  10217. (and (org-back-to-heading t) (point))
  10218. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  10219. (when (featurep 'org-inlinetask)
  10220. (org-inlinetask-remove-END-maybe))
  10221. (setq org-markers-to-move nil)
  10222. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10223. (defun org-refile-goto-last-stored ()
  10224. "Go to the location where the last refile was stored."
  10225. (interactive)
  10226. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10227. (message "This is the location of the last refile"))
  10228. (defun org-refile--get-location (refloc tbl)
  10229. "When user refile to REFLOC, find the associated target in TBL.
  10230. Also check `org-refile-target-table'."
  10231. (car (delq
  10232. nil
  10233. (mapcar
  10234. (lambda (r) (or (assoc r tbl)
  10235. (assoc r org-refile-target-table)))
  10236. (list (replace-regexp-in-string "/$" "" refloc)
  10237. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10238. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10239. "Prompt the user for a refile location, using PROMPT.
  10240. PROMPT should not be suffixed with a colon and a space, because
  10241. this function appends the default value from
  10242. `org-refile-history' automatically, if that is not empty."
  10243. (let ((org-refile-targets org-refile-targets)
  10244. (org-refile-use-outline-path org-refile-use-outline-path))
  10245. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10246. (unless org-refile-target-table
  10247. (user-error "No refile targets"))
  10248. (let* ((cbuf (current-buffer))
  10249. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10250. (cfunc (if (and org-refile-use-outline-path
  10251. org-outline-path-complete-in-steps)
  10252. #'org-olpath-completing-read
  10253. #'completing-read))
  10254. (extra (if org-refile-use-outline-path "/" ""))
  10255. (cbnex (concat (buffer-name) extra))
  10256. (filename (and cfn (expand-file-name cfn)))
  10257. (tbl (mapcar
  10258. (lambda (x)
  10259. (if (and (not (member org-refile-use-outline-path
  10260. '(file full-file-path)))
  10261. (not (equal filename (nth 1 x))))
  10262. (cons (concat (car x) extra " ("
  10263. (file-name-nondirectory (nth 1 x)) ")")
  10264. (cdr x))
  10265. (cons (concat (car x) extra) (cdr x))))
  10266. org-refile-target-table))
  10267. (completion-ignore-case t)
  10268. cdef
  10269. (prompt (concat prompt
  10270. (or (and (car org-refile-history)
  10271. (concat " (default " (car org-refile-history) ")"))
  10272. (and (assoc cbnex tbl) (setq cdef cbnex)
  10273. (concat " (default " cbnex ")"))) ": "))
  10274. pa answ parent-target child parent old-hist)
  10275. (setq old-hist org-refile-history)
  10276. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10277. nil 'org-refile-history (or cdef (car org-refile-history))))
  10278. (if (setq pa (org-refile--get-location answ tbl))
  10279. (progn
  10280. (org-refile-check-position pa)
  10281. (when (or (not org-refile-history)
  10282. (not (eq old-hist org-refile-history))
  10283. (not (equal (car pa) (car org-refile-history))))
  10284. (setq org-refile-history
  10285. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10286. org-refile-history
  10287. (cdr org-refile-history))))
  10288. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10289. (pop org-refile-history)))
  10290. pa)
  10291. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10292. (progn
  10293. (setq parent (match-string 1 answ)
  10294. child (match-string 2 answ))
  10295. (setq parent-target (org-refile--get-location parent tbl))
  10296. (when (and parent-target
  10297. (or (eq new-nodes t)
  10298. (and (eq new-nodes 'confirm)
  10299. (y-or-n-p (format "Create new node \"%s\"? "
  10300. child)))))
  10301. (org-refile-new-child parent-target child)))
  10302. (user-error "Invalid target location")))))
  10303. (declare-function org-string-nw-p "org-macs" (s))
  10304. (defun org-refile-check-position (refile-pointer)
  10305. "Check if the refile pointer matches the headline to which it points."
  10306. (let* ((file (nth 1 refile-pointer))
  10307. (re (nth 2 refile-pointer))
  10308. (pos (nth 3 refile-pointer))
  10309. buffer)
  10310. (if (and (not (markerp pos)) (not file))
  10311. (user-error "Please indicate a target file in the refile path")
  10312. (when (org-string-nw-p re)
  10313. (setq buffer (if (markerp pos)
  10314. (marker-buffer pos)
  10315. (or (find-buffer-visiting file)
  10316. (find-file-noselect file))))
  10317. (with-current-buffer buffer
  10318. (org-with-wide-buffer
  10319. (goto-char pos)
  10320. (beginning-of-line 1)
  10321. (unless (looking-at-p re)
  10322. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10323. (defun org-refile-new-child (parent-target child)
  10324. "Use refile target PARENT-TARGET to add new CHILD below it."
  10325. (unless parent-target
  10326. (error "Cannot find parent for new node"))
  10327. (let ((file (nth 1 parent-target))
  10328. (pos (nth 3 parent-target))
  10329. level)
  10330. (with-current-buffer (or (find-buffer-visiting file)
  10331. (find-file-noselect file))
  10332. (org-with-wide-buffer
  10333. (if pos
  10334. (goto-char pos)
  10335. (goto-char (point-max))
  10336. (unless (bolp) (newline)))
  10337. (when (looking-at org-outline-regexp)
  10338. (setq level (funcall outline-level))
  10339. (org-end-of-subtree t t))
  10340. (org-back-over-empty-lines)
  10341. (insert "\n" (make-string
  10342. (if pos (org-get-valid-level level 1) 1) ?*)
  10343. " " child "\n")
  10344. (beginning-of-line 0)
  10345. (list (concat (car parent-target) "/" child) file "" (point))))))
  10346. (defun org-olpath-completing-read (prompt collection &rest args)
  10347. "Read an outline path like a file name."
  10348. (let ((thetable collection))
  10349. (apply #'completing-read
  10350. prompt
  10351. (lambda (string predicate &optional flag)
  10352. (cond
  10353. ((eq flag nil) (try-completion string thetable))
  10354. ((eq flag t)
  10355. (let ((l (length string)))
  10356. (mapcar (lambda (x)
  10357. (let ((r (substring x l))
  10358. (f (if (string-match " ([^)]*)$" x)
  10359. (match-string 0 x)
  10360. "")))
  10361. (if (string-match "/" r)
  10362. (concat string (substring r 0 (match-end 0)) f)
  10363. x)))
  10364. (all-completions string thetable predicate))))
  10365. ;; Exact match?
  10366. ((eq flag 'lambda) (assoc string thetable))))
  10367. args)))
  10368. ;;;; Dynamic blocks
  10369. (defun org-find-dblock (name)
  10370. "Find the first dynamic block with name NAME in the buffer.
  10371. If not found, stay at current position and return nil."
  10372. (let ((case-fold-search t) pos)
  10373. (save-excursion
  10374. (goto-char (point-min))
  10375. (setq pos (and (re-search-forward
  10376. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10377. (match-beginning 0))))
  10378. (when pos (goto-char pos))
  10379. pos))
  10380. (defun org-create-dblock (plist)
  10381. "Create a dynamic block section, with parameters taken from PLIST.
  10382. PLIST must contain a :name entry which is used as the name of the block."
  10383. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10384. (end-of-line 1)
  10385. (newline))
  10386. (let ((col (current-column))
  10387. (name (plist-get plist :name)))
  10388. (insert "#+BEGIN: " name)
  10389. (while plist
  10390. (if (eq (car plist) :name)
  10391. (setq plist (cddr plist))
  10392. (insert " " (prin1-to-string (pop plist)))))
  10393. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10394. (beginning-of-line -2)))
  10395. (defun org-prepare-dblock ()
  10396. "Prepare dynamic block for refresh.
  10397. This empties the block, puts the cursor at the insert position and returns
  10398. the property list including an extra property :name with the block name."
  10399. (unless (looking-at org-dblock-start-re)
  10400. (user-error "Not at a dynamic block"))
  10401. (let* ((begdel (1+ (match-end 0)))
  10402. (name (org-no-properties (match-string 1)))
  10403. (params (append (list :name name)
  10404. (read (concat "(" (match-string 3) ")")))))
  10405. (save-excursion
  10406. (beginning-of-line 1)
  10407. (skip-chars-forward " \t")
  10408. (setq params (plist-put params :indentation-column (current-column))))
  10409. (unless (re-search-forward org-dblock-end-re nil t)
  10410. (error "Dynamic block not terminated"))
  10411. (setq params
  10412. (append params
  10413. (list :content (buffer-substring
  10414. begdel (match-beginning 0)))))
  10415. (delete-region begdel (match-beginning 0))
  10416. (goto-char begdel)
  10417. (open-line 1)
  10418. params))
  10419. (defun org-map-dblocks (&optional command)
  10420. "Apply COMMAND to all dynamic blocks in the current buffer.
  10421. If COMMAND is not given, use `org-update-dblock'."
  10422. (let ((cmd (or command 'org-update-dblock)))
  10423. (save-excursion
  10424. (goto-char (point-min))
  10425. (while (re-search-forward org-dblock-start-re nil t)
  10426. (goto-char (match-beginning 0))
  10427. (save-excursion
  10428. (condition-case nil
  10429. (funcall cmd)
  10430. (error (message "Error during update of dynamic block"))))
  10431. (unless (re-search-forward org-dblock-end-re nil t)
  10432. (error "Dynamic block not terminated"))))))
  10433. (defun org-dblock-update (&optional arg)
  10434. "User command for updating dynamic blocks.
  10435. Update the dynamic block at point. With prefix ARG, update all dynamic
  10436. blocks in the buffer."
  10437. (interactive "P")
  10438. (if arg
  10439. (org-update-all-dblocks)
  10440. (or (looking-at org-dblock-start-re)
  10441. (org-beginning-of-dblock))
  10442. (org-update-dblock)))
  10443. (defun org-update-dblock ()
  10444. "Update the dynamic block at point.
  10445. This means to empty the block, parse for parameters and then call
  10446. the correct writing function."
  10447. (interactive)
  10448. (save-excursion
  10449. (let* ((win (selected-window))
  10450. (pos (point))
  10451. (line (org-current-line))
  10452. (params (org-prepare-dblock))
  10453. (name (plist-get params :name))
  10454. (indent (plist-get params :indentation-column))
  10455. (cmd (intern (concat "org-dblock-write:" name))))
  10456. (message "Updating dynamic block `%s' at line %d..." name line)
  10457. (funcall cmd params)
  10458. (message "Updating dynamic block `%s' at line %d...done" name line)
  10459. (goto-char pos)
  10460. (when (and indent (> indent 0))
  10461. (setq indent (make-string indent ?\ ))
  10462. (save-excursion
  10463. (select-window win)
  10464. (org-beginning-of-dblock)
  10465. (forward-line 1)
  10466. (while (not (looking-at org-dblock-end-re))
  10467. (insert indent)
  10468. (beginning-of-line 2))
  10469. (when (looking-at org-dblock-end-re)
  10470. (and (looking-at "[ \t]+")
  10471. (replace-match ""))
  10472. (insert indent)))))))
  10473. (defun org-beginning-of-dblock ()
  10474. "Find the beginning of the dynamic block at point.
  10475. Error if there is no such block at point."
  10476. (let ((pos (point))
  10477. beg)
  10478. (end-of-line 1)
  10479. (if (and (re-search-backward org-dblock-start-re nil t)
  10480. (setq beg (match-beginning 0))
  10481. (re-search-forward org-dblock-end-re nil t)
  10482. (> (match-end 0) pos))
  10483. (goto-char beg)
  10484. (goto-char pos)
  10485. (error "Not in a dynamic block"))))
  10486. (defun org-update-all-dblocks ()
  10487. "Update all dynamic blocks in the buffer.
  10488. This function can be used in a hook."
  10489. (interactive)
  10490. (when (derived-mode-p 'org-mode)
  10491. (org-map-dblocks 'org-update-dblock)))
  10492. ;;;; Completion
  10493. (declare-function org-export-backend-options "ox" (cl-x) t)
  10494. (defun org-get-export-keywords ()
  10495. "Return a list of all currently understood export keywords.
  10496. Export keywords include options, block names, attributes and
  10497. keywords relative to each registered export back-end."
  10498. (let (keywords)
  10499. (dolist (backend
  10500. (bound-and-true-p org-export-registered-backends)
  10501. (delq nil keywords))
  10502. ;; Back-end name (for keywords, like #+LATEX:)
  10503. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10504. (dolist (option-entry (org-export-backend-options backend))
  10505. ;; Back-end options.
  10506. (push (nth 1 option-entry) keywords)))))
  10507. (defconst org-options-keywords
  10508. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10509. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10510. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10511. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10512. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10513. (defcustom org-structure-template-alist
  10514. '(("a" . "export ascii")
  10515. ("c" . "center")
  10516. ("C" . "comment")
  10517. ("e" . "example")
  10518. ("E" . "export")
  10519. ("h" . "export html")
  10520. ("l" . "export latex")
  10521. ("q" . "quote")
  10522. ("s" . "src")
  10523. ("v" . "verse"))
  10524. "An alist of keys and block types.
  10525. `org-insert-structure-template' will display a menu with this
  10526. list of templates to choose from. The block type is inserted,
  10527. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  10528. The menu keys are defined by the car of each entry in this alist.
  10529. If two entries have the keys \"a\" and \"aa\" respectively, the
  10530. former will be inserted by typing \"a TAB/RET/SPC\" and the
  10531. latter will be inserted by typing \"aa\". If an entry with the
  10532. key \"aab\" is later added, it can be inserted by typing \"ab\".
  10533. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  10534. block can be inserted by pressing TAB after the string \"<KEY\"."
  10535. :group 'org-edit-structure
  10536. :type '(repeat
  10537. (cons (string :tag "Key")
  10538. (string :tag "Template")))
  10539. :package-version '(Org . "9.2"))
  10540. (defun org--check-org-structure-template-alist (&optional checklist)
  10541. "Check whether `org-structure-template-alist' is set up correctly.
  10542. In particular, check if the Org 9.2 format is used as opposed to
  10543. previous format.
  10544. "
  10545. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  10546. (or (eval checklist)
  10547. org-structure-template-alist))))
  10548. (when elm
  10549. (org-display-warning
  10550. (format "
  10551. Please update the entries of `%s'.
  10552. In Org 9.2 the format was changed from something like
  10553. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  10554. to something like
  10555. (\"s\" . \"src\")
  10556. Please refer to the documentation of `org-structure-template-alist'.
  10557. The following entries must be updated:
  10558. %s"
  10559. (or checklist 'org-structure-template-alist)
  10560. (pp-to-string elm))))))
  10561. (defun org--insert-structure-template-mks ()
  10562. "Present `org-structure-template-alist' with `org-mks'.
  10563. Menus are added if keys require more than one keystroke. Tabs
  10564. are added to single key entries when more than one stroke is
  10565. needed. Keys longer than two characters are reduced to two
  10566. characters."
  10567. (org--check-org-structure-template-alist)
  10568. (let* (case-fold-search
  10569. (templates (append org-structure-template-alist
  10570. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  10571. (keys (mapcar #'car templates))
  10572. (start-letters
  10573. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  10574. ;; Sort each element of `org-structure-template-alist' into
  10575. ;; sublists according to the first letter.
  10576. (superlist
  10577. (mapcar (lambda (letter)
  10578. (list letter
  10579. (cl-remove-if-not
  10580. (apply-partially #'string-match-p (concat "^" letter))
  10581. templates :key #'car)))
  10582. start-letters)))
  10583. (org-mks
  10584. (apply #'append
  10585. ;; Make an `org-mks' table. If only one element is
  10586. ;; present in a sublist, make it part of the top-menu,
  10587. ;; otherwise make a submenu according to the starting
  10588. ;; letter and populate it.
  10589. (mapcar (lambda (sublist)
  10590. (if (eq 1 (length (cadr sublist)))
  10591. (mapcar (lambda (elm)
  10592. (list (substring (car elm) 0 1)
  10593. (cdr elm) ""))
  10594. (cadr sublist))
  10595. ;; Create submenu.
  10596. (let* ((topkey (car sublist))
  10597. (elms (cadr sublist))
  10598. (keys (mapcar #'car elms))
  10599. (long (> (length elms) 3)))
  10600. (append
  10601. (list
  10602. ;; Make a description of the submenu.
  10603. (list topkey
  10604. (concat
  10605. (mapconcat #'cdr
  10606. (cl-subseq elms 0 (if long 3 (length elms)))
  10607. ", ")
  10608. (when long ", ..."))))
  10609. ;; List of entries in submenu.
  10610. (cl-mapcar #'list
  10611. (org--insert-structure-template-unique-keys keys)
  10612. (mapcar #'cdr elms)
  10613. (make-list (length elms) ""))))))
  10614. superlist))
  10615. "Select a key\n============"
  10616. "Key: ")))
  10617. (defun org--insert-structure-template-unique-keys (keys)
  10618. "Make a list of unique, two characters long elements from KEYS.
  10619. Elements of length one have a tab appended. Elements of length
  10620. two are kept as is. Longer elements are truncated to length two.
  10621. If an element cannot be made unique, an error is raised."
  10622. (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  10623. menu-keys)
  10624. (dolist (key orderd-keys)
  10625. (let ((potential-key
  10626. (cl-case (length key)
  10627. (1 (concat key "\t"))
  10628. (2 key)
  10629. (otherwise
  10630. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  10631. (mapcar (apply-partially #'concat (substring key 0 1))
  10632. (split-string (substring key 1) "" t)))))))
  10633. (if (or (not potential-key) (assoc potential-key menu-keys))
  10634. (user-error "Could not make unique key for %s." key)
  10635. (push (cons potential-key key) menu-keys))))
  10636. (mapcar #'car
  10637. (cl-sort menu-keys #'<
  10638. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  10639. (defun org-insert-structure-template (type)
  10640. "Insert a block structure of the type #+begin_foo/#+end_foo.
  10641. Select a block from `org-structure-template-alist' then type
  10642. either RET, TAB or SPC to write the block type. With an active
  10643. region, wrap the region in the block. Otherwise, insert an empty
  10644. block."
  10645. (interactive
  10646. (list (pcase (org--insert-structure-template-mks)
  10647. (`("\t" . ,_) (read-string "Structure type: "))
  10648. (`(,_ ,choice . ,_) choice))))
  10649. (let* ((region? (use-region-p))
  10650. (region-start (and region? (region-beginning)))
  10651. (region-end (and region? (copy-marker (region-end))))
  10652. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  10653. (verbatim? (string-match-p
  10654. (concat "\\`" (regexp-opt '("example" "export" "src")))
  10655. type)))
  10656. (when region? (goto-char region-start))
  10657. (let ((column (current-indentation)))
  10658. (if (save-excursion (skip-chars-backward " \t") (bolp))
  10659. (beginning-of-line)
  10660. (insert "\n"))
  10661. (save-excursion
  10662. (indent-to column)
  10663. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  10664. (when region?
  10665. (when verbatim? (org-escape-code-in-region (point) region-end))
  10666. (goto-char region-end)
  10667. ;; Ignore empty lines at the end of the region.
  10668. (skip-chars-backward " \r\t\n")
  10669. (end-of-line))
  10670. (unless (bolp) (insert "\n"))
  10671. (indent-to column)
  10672. (insert (format "#+end_%s" (car (split-string type))))
  10673. (if (looking-at "[ \t]*$") (replace-match "")
  10674. (insert "\n"))
  10675. (when (and (eobp) (not (bolp))) (insert "\n")))
  10676. (if extended? (end-of-line)
  10677. (forward-line)
  10678. (skip-chars-forward " \t")))))
  10679. ;;;; TODO, DEADLINE, Comments
  10680. (defun org-toggle-comment ()
  10681. "Change the COMMENT state of an entry."
  10682. (interactive)
  10683. (save-excursion
  10684. (org-back-to-heading)
  10685. (let ((case-fold-search nil))
  10686. (looking-at org-complex-heading-regexp))
  10687. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  10688. (skip-chars-forward " \t")
  10689. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  10690. (if (org-in-commented-heading-p t)
  10691. (delete-region (point)
  10692. (progn (search-forward " " (line-end-position) 'move)
  10693. (skip-chars-forward " \t")
  10694. (point)))
  10695. (insert org-comment-string)
  10696. (unless (eolp) (insert " ")))))
  10697. (defvar org-last-todo-state-is-todo nil
  10698. "This is non-nil when the last TODO state change led to a TODO state.
  10699. If the last change removed the TODO tag or switched to DONE, then
  10700. this is nil.")
  10701. (defvar org-todo-setup-filter-hook nil
  10702. "Hook for functions that pre-filter todo specs.
  10703. Each function takes a todo spec and returns either nil or the spec
  10704. transformed into canonical form." )
  10705. (defvar org-todo-get-default-hook nil
  10706. "Hook for functions that get a default item for todo.
  10707. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  10708. nil or a string to be used for the todo mark." )
  10709. (defvar org-agenda-headline-snapshot-before-repeat)
  10710. (defun org-current-effective-time ()
  10711. "Return current time adjusted for `org-extend-today-until' variable."
  10712. (let* ((ct (org-current-time))
  10713. (dct (decode-time ct))
  10714. (ct1
  10715. (cond
  10716. (org-use-last-clock-out-time-as-effective-time
  10717. (or (org-clock-get-last-clock-out-time) ct))
  10718. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  10719. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  10720. (t ct))))
  10721. ct1))
  10722. (defun org-todo-yesterday (&optional arg)
  10723. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  10724. (interactive "P")
  10725. (if (eq major-mode 'org-agenda-mode)
  10726. (apply 'org-agenda-todo-yesterday arg)
  10727. (let* ((org-use-effective-time t)
  10728. (hour (nth 2 (decode-time (org-current-time))))
  10729. (org-extend-today-until (1+ hour)))
  10730. (org-todo arg))))
  10731. (defvar org-block-entry-blocking ""
  10732. "First entry preventing the TODO state change.")
  10733. (defun org-cancel-repeater ()
  10734. "Cancel a repeater by setting its numeric value to zero."
  10735. (interactive)
  10736. (save-excursion
  10737. (org-back-to-heading t)
  10738. (let ((bound1 (point))
  10739. (bound0 (save-excursion (outline-next-heading) (point))))
  10740. (when (and (re-search-forward
  10741. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  10742. org-deadline-time-regexp "\\)\\|\\("
  10743. org-ts-regexp "\\)")
  10744. bound0 t)
  10745. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  10746. bound1 t))
  10747. (replace-match "0" t nil nil 1)))))
  10748. (defvar org-state)
  10749. (defvar org-blocked-by-checkboxes)
  10750. (defun org-todo (&optional arg)
  10751. "Change the TODO state of an item.
  10752. The state of an item is given by a keyword at the start of the heading,
  10753. like
  10754. *** TODO Write paper
  10755. *** DONE Call mom
  10756. The different keywords are specified in the variable `org-todo-keywords'.
  10757. By default the available states are \"TODO\" and \"DONE\". So, for this
  10758. example: when the item starts with TODO, it is changed to DONE.
  10759. When it starts with DONE, the DONE is removed. And when neither TODO nor
  10760. DONE are present, add TODO at the beginning of the heading.
  10761. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  10762. state.
  10763. With numeric prefix ARG, switch to that state.
  10764. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  10765. next set of TODO \
  10766. keywords (nextset).
  10767. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  10768. prefix, circumvent any state blocking.
  10769. With a numeric prefix arg of 0, inhibit note taking for the change.
  10770. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  10771. When called through ELisp, arg is also interpreted in the following way:
  10772. `none' -> empty state
  10773. \"\" -> switch to empty state
  10774. `done' -> switch to DONE
  10775. `nextset' -> switch to the next set of keywords
  10776. `previousset' -> switch to the previous set of keywords
  10777. \"WAITING\" -> switch to the specified keyword, but only if it
  10778. really is a member of `org-todo-keywords'."
  10779. (interactive "P")
  10780. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10781. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10782. 'region-start-level 'region))
  10783. org-loop-over-headlines-in-active-region)
  10784. (org-map-entries
  10785. `(org-todo ,arg)
  10786. org-loop-over-headlines-in-active-region
  10787. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  10788. (when (equal arg '(16)) (setq arg 'nextset))
  10789. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  10790. (let ((org-blocker-hook org-blocker-hook)
  10791. commentp
  10792. case-fold-search)
  10793. (when (equal arg '(64))
  10794. (setq arg nil org-blocker-hook nil))
  10795. (when (and org-blocker-hook
  10796. (or org-inhibit-blocking
  10797. (org-entry-get nil "NOBLOCKING")))
  10798. (setq org-blocker-hook nil))
  10799. (save-excursion
  10800. (catch 'exit
  10801. (org-back-to-heading t)
  10802. (when (org-in-commented-heading-p t)
  10803. (org-toggle-comment)
  10804. (setq commentp t))
  10805. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  10806. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  10807. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  10808. (let* ((match-data (match-data))
  10809. (startpos (copy-marker (line-beginning-position)))
  10810. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  10811. (org-log-done org-log-done)
  10812. (org-log-repeat org-log-repeat)
  10813. (org-todo-log-states org-todo-log-states)
  10814. (org-inhibit-logging
  10815. (if (equal arg 0)
  10816. (progn (setq arg nil) 'note) org-inhibit-logging))
  10817. (this (match-string 1))
  10818. (hl-pos (match-beginning 0))
  10819. (head (org-get-todo-sequence-head this))
  10820. (ass (assoc head org-todo-kwd-alist))
  10821. (interpret (nth 1 ass))
  10822. (done-word (nth 3 ass))
  10823. (final-done-word (nth 4 ass))
  10824. (org-last-state (or this ""))
  10825. (completion-ignore-case t)
  10826. (member (member this org-todo-keywords-1))
  10827. (tail (cdr member))
  10828. (org-state (cond
  10829. ((and org-todo-key-trigger
  10830. (or (and (equal arg '(4))
  10831. (eq org-use-fast-todo-selection 'prefix))
  10832. (and (not arg) org-use-fast-todo-selection
  10833. (not (eq org-use-fast-todo-selection
  10834. 'prefix)))))
  10835. ;; Use fast selection.
  10836. (org-fast-todo-selection))
  10837. ((and (equal arg '(4))
  10838. (or (not org-use-fast-todo-selection)
  10839. (not org-todo-key-trigger)))
  10840. ;; Read a state with completion.
  10841. (completing-read
  10842. "State: " (mapcar #'list org-todo-keywords-1)
  10843. nil t))
  10844. ((eq arg 'right)
  10845. (if this
  10846. (if tail (car tail) nil)
  10847. (car org-todo-keywords-1)))
  10848. ((eq arg 'left)
  10849. (unless (equal member org-todo-keywords-1)
  10850. (if this
  10851. (nth (- (length org-todo-keywords-1)
  10852. (length tail) 2)
  10853. org-todo-keywords-1)
  10854. (org-last org-todo-keywords-1))))
  10855. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  10856. (setq arg nil))) ;hack to fall back to cycling
  10857. (arg
  10858. ;; User or caller requests a specific state.
  10859. (cond
  10860. ((equal arg "") nil)
  10861. ((eq arg 'none) nil)
  10862. ((eq arg 'done) (or done-word (car org-done-keywords)))
  10863. ((eq arg 'nextset)
  10864. (or (car (cdr (member head org-todo-heads)))
  10865. (car org-todo-heads)))
  10866. ((eq arg 'previousset)
  10867. (let ((org-todo-heads (reverse org-todo-heads)))
  10868. (or (car (cdr (member head org-todo-heads)))
  10869. (car org-todo-heads))))
  10870. ((car (member arg org-todo-keywords-1)))
  10871. ((stringp arg)
  10872. (user-error "State `%s' not valid in this file" arg))
  10873. ((nth (1- (prefix-numeric-value arg))
  10874. org-todo-keywords-1))))
  10875. ((null member) (or head (car org-todo-keywords-1)))
  10876. ((equal this final-done-word) nil) ;-> make empty
  10877. ((null tail) nil) ;-> first entry
  10878. ((memq interpret '(type priority))
  10879. (if (eq this-command last-command)
  10880. (car tail)
  10881. (if (> (length tail) 0)
  10882. (or done-word (car org-done-keywords))
  10883. nil)))
  10884. (t
  10885. (car tail))))
  10886. (org-state (or
  10887. (run-hook-with-args-until-success
  10888. 'org-todo-get-default-hook org-state org-last-state)
  10889. org-state))
  10890. (next (if org-state (concat " " org-state " ") " "))
  10891. (change-plist (list :type 'todo-state-change :from this :to org-state
  10892. :position startpos))
  10893. dolog now-done-p)
  10894. (when org-blocker-hook
  10895. (let (org-blocked-by-checkboxes block-reason)
  10896. (setq org-last-todo-state-is-todo
  10897. (not (member this org-done-keywords)))
  10898. (unless (save-excursion
  10899. (save-match-data
  10900. (org-with-wide-buffer
  10901. (run-hook-with-args-until-failure
  10902. 'org-blocker-hook change-plist))))
  10903. (setq block-reason (if org-blocked-by-checkboxes
  10904. "contained checkboxes"
  10905. (format "\"%s\"" org-block-entry-blocking)))
  10906. (if (called-interactively-p 'interactive)
  10907. (user-error "TODO state change from %s to %s blocked (by %s)"
  10908. this org-state block-reason)
  10909. ;; Fail silently.
  10910. (message "TODO state change from %s to %s blocked (by %s)"
  10911. this org-state block-reason)
  10912. (throw 'exit nil)))))
  10913. (store-match-data match-data)
  10914. (replace-match next t t)
  10915. (cond ((equal this org-state)
  10916. (message "TODO state was already %s" (org-trim next)))
  10917. ((not (pos-visible-in-window-p hl-pos))
  10918. (message "TODO state changed to %s" (org-trim next))))
  10919. (unless head
  10920. (setq head (org-get-todo-sequence-head org-state)
  10921. ass (assoc head org-todo-kwd-alist)
  10922. interpret (nth 1 ass)
  10923. done-word (nth 3 ass)
  10924. final-done-word (nth 4 ass)))
  10925. (when (memq arg '(nextset previousset))
  10926. (message "Keyword-Set %d/%d: %s"
  10927. (- (length org-todo-sets) -1
  10928. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  10929. (length org-todo-sets)
  10930. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  10931. (setq org-last-todo-state-is-todo
  10932. (not (member org-state org-done-keywords)))
  10933. (setq now-done-p (and (member org-state org-done-keywords)
  10934. (not (member this org-done-keywords))))
  10935. (and logging (org-local-logging logging))
  10936. (when (and (or org-todo-log-states org-log-done)
  10937. (not (eq org-inhibit-logging t))
  10938. (not (memq arg '(nextset previousset))))
  10939. ;; We need to look at recording a time and note.
  10940. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  10941. (nth 2 (assoc this org-todo-log-states))))
  10942. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  10943. (setq dolog 'time))
  10944. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  10945. (and org-state
  10946. (member org-state org-not-done-keywords)
  10947. (not (member this org-not-done-keywords))))
  10948. ;; This is now a todo state and was not one before
  10949. ;; If there was a CLOSED time stamp, get rid of it.
  10950. (org-add-planning-info nil nil 'closed))
  10951. (when (and now-done-p org-log-done)
  10952. ;; It is now done, and it was not done before.
  10953. (org-add-planning-info 'closed (org-current-effective-time))
  10954. (when (and (not dolog) (eq 'note org-log-done))
  10955. (org-add-log-setup 'done org-state this 'note)))
  10956. (when (and org-state dolog)
  10957. ;; This is a non-nil state, and we need to log it.
  10958. (org-add-log-setup 'state org-state this dolog)))
  10959. ;; Fixup tag positioning.
  10960. (org-todo-trigger-tag-changes org-state)
  10961. (when org-auto-align-tags (org-align-tags))
  10962. (when org-provide-todo-statistics
  10963. (org-update-parent-todo-statistics))
  10964. (run-hooks 'org-after-todo-state-change-hook)
  10965. (when (and arg (not (member org-state org-done-keywords)))
  10966. (setq head (org-get-todo-sequence-head org-state)))
  10967. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  10968. ;; Do we need to trigger a repeat?
  10969. (when now-done-p
  10970. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  10971. ;; This is for the agenda, take a snapshot of the headline.
  10972. (save-match-data
  10973. (setq org-agenda-headline-snapshot-before-repeat
  10974. (org-get-heading))))
  10975. (org-auto-repeat-maybe org-state))
  10976. ;; Fixup cursor location if close to the keyword.
  10977. (when (and (outline-on-heading-p)
  10978. (not (bolp))
  10979. (save-excursion (beginning-of-line 1)
  10980. (looking-at org-todo-line-regexp))
  10981. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  10982. (goto-char (or (match-end 2) (match-end 1)))
  10983. (and (looking-at " ") (just-one-space)))
  10984. (when org-trigger-hook
  10985. (save-excursion
  10986. (run-hook-with-args 'org-trigger-hook change-plist)))
  10987. (when commentp (org-toggle-comment))))))))
  10988. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  10989. "Block turning an entry into a TODO, using the hierarchy.
  10990. This checks whether the current task should be blocked from state
  10991. changes. Such blocking occurs when:
  10992. 1. The task has children which are not all in a completed state.
  10993. 2. A task has a parent with the property :ORDERED:, and there
  10994. are siblings prior to the current task with incomplete
  10995. status.
  10996. 3. The parent of the task is blocked because it has siblings that should
  10997. be done first, or is child of a block grandparent TODO entry."
  10998. (if (not org-enforce-todo-dependencies)
  10999. t ; if locally turned off don't block
  11000. (catch 'dont-block
  11001. ;; If this is not a todo state change, or if this entry is already DONE,
  11002. ;; do not block
  11003. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11004. (member (plist-get change-plist :from)
  11005. (cons 'done org-done-keywords))
  11006. (member (plist-get change-plist :to)
  11007. (cons 'todo org-not-done-keywords))
  11008. (not (plist-get change-plist :to)))
  11009. (throw 'dont-block t))
  11010. ;; If this task has children, and any are undone, it's blocked
  11011. (save-excursion
  11012. (org-back-to-heading t)
  11013. (let ((this-level (funcall outline-level)))
  11014. (outline-next-heading)
  11015. (let ((child-level (funcall outline-level)))
  11016. (while (and (not (eobp))
  11017. (> child-level this-level))
  11018. ;; this todo has children, check whether they are all
  11019. ;; completed
  11020. (when (and (not (org-entry-is-done-p))
  11021. (org-entry-is-todo-p))
  11022. (setq org-block-entry-blocking (org-get-heading))
  11023. (throw 'dont-block nil))
  11024. (outline-next-heading)
  11025. (setq child-level (funcall outline-level))))))
  11026. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11027. ;; any previous siblings are undone, it's blocked
  11028. (save-excursion
  11029. (org-back-to-heading t)
  11030. (let* ((pos (point))
  11031. (parent-pos (and (org-up-heading-safe) (point)))
  11032. (case-fold-search nil))
  11033. (unless parent-pos (throw 'dont-block t)) ; no parent
  11034. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11035. (forward-line 1)
  11036. (re-search-forward org-not-done-heading-regexp pos t))
  11037. (setq org-block-entry-blocking (match-string 0))
  11038. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11039. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11040. (while t
  11041. (goto-char parent-pos)
  11042. (unless (looking-at org-not-done-heading-regexp)
  11043. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11044. (setq pos (point))
  11045. (setq parent-pos (and (org-up-heading-safe) (point)))
  11046. (unless parent-pos (throw 'dont-block t)) ; no parent
  11047. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11048. (forward-line 1)
  11049. (re-search-forward org-not-done-heading-regexp pos t)
  11050. (setq org-block-entry-blocking (org-get-heading)))
  11051. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11052. (defcustom org-track-ordered-property-with-tag nil
  11053. "Should the ORDERED property also be shown as a tag?
  11054. The ORDERED property decides if an entry should require subtasks to be
  11055. completed in sequence. Since a property is not very visible, setting
  11056. this option means that toggling the ORDERED property with the command
  11057. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11058. not relevant for the behavior, but it makes things more visible.
  11059. Note that toggling the tag with tags commands will not change the property
  11060. and therefore not influence behavior!
  11061. This can be t, meaning the tag ORDERED should be used, It can also be a
  11062. string to select a different tag for this task."
  11063. :group 'org-todo
  11064. :type '(choice
  11065. (const :tag "No tracking" nil)
  11066. (const :tag "Track with ORDERED tag" t)
  11067. (string :tag "Use other tag")))
  11068. (defun org-toggle-ordered-property ()
  11069. "Toggle the ORDERED property of the current entry.
  11070. For better visibility, you can track the value of this property with a tag.
  11071. See variable `org-track-ordered-property-with-tag'."
  11072. (interactive)
  11073. (let* ((t1 org-track-ordered-property-with-tag)
  11074. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11075. (save-excursion
  11076. (org-back-to-heading)
  11077. (if (org-entry-get nil "ORDERED")
  11078. (progn
  11079. (org-delete-property "ORDERED")
  11080. (and tag (org-toggle-tag tag 'off))
  11081. (message "Subtasks can be completed in arbitrary order"))
  11082. (org-entry-put nil "ORDERED" "t")
  11083. (and tag (org-toggle-tag tag 'on))
  11084. (message "Subtasks must be completed in sequence")))))
  11085. (defun org-block-todo-from-checkboxes (change-plist)
  11086. "Block turning an entry into a TODO, using checkboxes.
  11087. This checks whether the current task should be blocked from state
  11088. changes because there are unchecked boxes in this entry."
  11089. (if (not org-enforce-todo-checkbox-dependencies)
  11090. t ; if locally turned off don't block
  11091. (catch 'dont-block
  11092. ;; If this is not a todo state change, or if this entry is already DONE,
  11093. ;; do not block
  11094. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11095. (member (plist-get change-plist :from)
  11096. (cons 'done org-done-keywords))
  11097. (member (plist-get change-plist :to)
  11098. (cons 'todo org-not-done-keywords))
  11099. (not (plist-get change-plist :to)))
  11100. (throw 'dont-block t))
  11101. ;; If this task has checkboxes that are not checked, it's blocked
  11102. (save-excursion
  11103. (org-back-to-heading t)
  11104. (let ((beg (point)) end)
  11105. (outline-next-heading)
  11106. (setq end (point))
  11107. (goto-char beg)
  11108. (when (org-list-search-forward
  11109. (concat (org-item-beginning-re)
  11110. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11111. "\\[[- ]\\]")
  11112. end t)
  11113. (when (boundp 'org-blocked-by-checkboxes)
  11114. (setq org-blocked-by-checkboxes t))
  11115. (throw 'dont-block nil))))
  11116. t))) ; do not block
  11117. (defun org-entry-blocked-p ()
  11118. "Non-nil if entry at point is blocked."
  11119. (and (not (org-entry-get nil "NOBLOCKING"))
  11120. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11121. (not (run-hook-with-args-until-failure
  11122. 'org-blocker-hook
  11123. (list :type 'todo-state-change
  11124. :position (point)
  11125. :from 'todo
  11126. :to 'done)))))
  11127. (defun org-update-statistics-cookies (all)
  11128. "Update the statistics cookie, either from TODO or from checkboxes.
  11129. This should be called with the cursor in a line with a statistics
  11130. cookie. When called with a \\[universal-argument] prefix, update
  11131. all statistics cookies in the buffer."
  11132. (interactive "P")
  11133. (if all
  11134. (progn
  11135. (org-update-checkbox-count 'all)
  11136. (org-map-entries 'org-update-parent-todo-statistics))
  11137. (if (not (org-at-heading-p))
  11138. (org-update-checkbox-count)
  11139. (let ((pos (point-marker))
  11140. end l1 l2)
  11141. (ignore-errors (org-back-to-heading t))
  11142. (if (not (org-at-heading-p))
  11143. (org-update-checkbox-count)
  11144. (setq l1 (org-outline-level))
  11145. (setq end (save-excursion
  11146. (outline-next-heading)
  11147. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11148. (point)))
  11149. (if (and (save-excursion
  11150. (re-search-forward
  11151. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11152. (not (save-excursion (re-search-forward
  11153. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11154. (org-update-checkbox-count)
  11155. (if (and l2 (> l2 l1))
  11156. (progn
  11157. (goto-char end)
  11158. (org-update-parent-todo-statistics))
  11159. (goto-char pos)
  11160. (beginning-of-line 1)
  11161. (while (re-search-forward
  11162. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11163. (point-at-eol) t)
  11164. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11165. (goto-char pos)
  11166. (move-marker pos nil)))))
  11167. (defvar org-entry-property-inherited-from) ;; defined below
  11168. (defun org-update-parent-todo-statistics ()
  11169. "Update any statistics cookie in the parent of the current headline.
  11170. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11171. the entire subtree and this will travel up the hierarchy and update
  11172. statistics everywhere."
  11173. (let* ((prop (save-excursion (org-up-heading-safe)
  11174. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11175. (recursive (or (not org-hierarchical-todo-statistics)
  11176. (and prop (string-match "\\<recursive\\>" prop))))
  11177. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11178. 0))
  11179. (first t)
  11180. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11181. level ltoggle l1 new ndel
  11182. (cnt-all 0) (cnt-done 0) is-percent kwd
  11183. checkbox-beg cookie-present)
  11184. (catch 'exit
  11185. (save-excursion
  11186. (beginning-of-line 1)
  11187. (setq ltoggle (funcall outline-level))
  11188. ;; Three situations are to consider:
  11189. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11190. ;; to the top-level ancestor on the headline;
  11191. ;; 2. If parent has "recursive" property, repeat up to the
  11192. ;; headline setting that property, taking inheritance into
  11193. ;; account;
  11194. ;; 3. Else, move up to direct parent and proceed only once.
  11195. (while (and (setq level (org-up-heading-safe))
  11196. (or recursive first)
  11197. (>= (point) lim))
  11198. (setq first nil cookie-present nil)
  11199. (unless (and level
  11200. (not (string-match
  11201. "\\<checkbox\\>"
  11202. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11203. "")))))
  11204. (throw 'exit nil))
  11205. (while (re-search-forward box-re (point-at-eol) t)
  11206. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11207. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11208. (save-match-data
  11209. (unless (outline-next-heading) (throw 'exit nil))
  11210. (while (and (looking-at org-complex-heading-regexp)
  11211. (> (setq l1 (length (match-string 1))) level))
  11212. (setq kwd (and (or recursive (= l1 ltoggle))
  11213. (match-string 2)))
  11214. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11215. (and (eq org-provide-todo-statistics t)
  11216. (or (member kwd org-done-keywords)))
  11217. (and (listp org-provide-todo-statistics)
  11218. (stringp (car org-provide-todo-statistics))
  11219. (or (member kwd org-provide-todo-statistics)
  11220. (member kwd org-done-keywords)))
  11221. (and (listp org-provide-todo-statistics)
  11222. (listp (car org-provide-todo-statistics))
  11223. (or (member kwd (car org-provide-todo-statistics))
  11224. (and (member kwd org-done-keywords)
  11225. (member kwd (cadr org-provide-todo-statistics))))))
  11226. (setq cnt-all (1+ cnt-all))
  11227. (and (eq org-provide-todo-statistics t)
  11228. kwd
  11229. (setq cnt-all (1+ cnt-all))))
  11230. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11231. (member kwd org-done-keywords))
  11232. (and (listp org-provide-todo-statistics)
  11233. (listp (car org-provide-todo-statistics))
  11234. (member kwd org-done-keywords)
  11235. (member kwd (cadr org-provide-todo-statistics)))
  11236. (and (listp org-provide-todo-statistics)
  11237. (stringp (car org-provide-todo-statistics))
  11238. (member kwd org-done-keywords)))
  11239. (setq cnt-done (1+ cnt-done)))
  11240. (outline-next-heading)))
  11241. (setq new
  11242. (if is-percent
  11243. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11244. (max 1 cnt-all)))
  11245. (format "[%d/%d]" cnt-done cnt-all))
  11246. ndel (- (match-end 0) checkbox-beg))
  11247. (goto-char checkbox-beg)
  11248. (insert new)
  11249. (delete-region (point) (+ (point) ndel))
  11250. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11251. (when cookie-present
  11252. (run-hook-with-args 'org-after-todo-statistics-hook
  11253. cnt-done (- cnt-all cnt-done))))))
  11254. (run-hooks 'org-todo-statistics-hook)))
  11255. (defvar org-after-todo-statistics-hook nil
  11256. "Hook that is called after a TODO statistics cookie has been updated.
  11257. Each function is called with two arguments: the number of not-done entries
  11258. and the number of done entries.
  11259. For example, the following function, when added to this hook, will switch
  11260. an entry to DONE when all children are done, and back to TODO when new
  11261. entries are set to a TODO status. Note that this hook is only called
  11262. when there is a statistics cookie in the headline!
  11263. (defun org-summary-todo (n-done n-not-done)
  11264. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11265. (let (org-log-done org-log-states) ; turn off logging
  11266. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11267. ")
  11268. (defvar org-todo-statistics-hook nil
  11269. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11270. This hook runs even if there is no statistics cookie present, in which case
  11271. `org-after-todo-statistics-hook' would not run.")
  11272. (defun org-todo-trigger-tag-changes (state)
  11273. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11274. (let ((l org-todo-state-tags-triggers)
  11275. changes)
  11276. (when (or (not state) (equal state ""))
  11277. (setq changes (append changes (cdr (assoc "" l)))))
  11278. (when (and (stringp state) (> (length state) 0))
  11279. (setq changes (append changes (cdr (assoc state l)))))
  11280. (when (member state org-not-done-keywords)
  11281. (setq changes (append changes (cdr (assq 'todo l)))))
  11282. (when (member state org-done-keywords)
  11283. (setq changes (append changes (cdr (assq 'done l)))))
  11284. (dolist (c changes)
  11285. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11286. (defun org-local-logging (value)
  11287. "Get logging settings from a property VALUE."
  11288. ;; Directly set the variables, they are already local.
  11289. (setq org-log-done nil
  11290. org-log-repeat nil
  11291. org-todo-log-states nil)
  11292. (dolist (w (split-string value))
  11293. (let (a)
  11294. (cond
  11295. ((setq a (assoc w org-startup-options))
  11296. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11297. (set (nth 1 a) (nth 2 a))))
  11298. ((setq a (org-extract-log-state-settings w))
  11299. (and (member (car a) org-todo-keywords-1)
  11300. (push a org-todo-log-states)))))))
  11301. (defun org-get-todo-sequence-head (kwd)
  11302. "Return the head of the TODO sequence to which KWD belongs.
  11303. If KWD is not set, check if there is a text property remembering the
  11304. right sequence."
  11305. (let (p)
  11306. (cond
  11307. ((not kwd)
  11308. (or (get-text-property (point-at-bol) 'org-todo-head)
  11309. (progn
  11310. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11311. nil (point-at-eol)))
  11312. (get-text-property p 'org-todo-head))))
  11313. ((not (member kwd org-todo-keywords-1))
  11314. (car org-todo-keywords-1))
  11315. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11316. (defun org-fast-todo-selection ()
  11317. "Fast TODO keyword selection with single keys.
  11318. Returns the new TODO keyword, or nil if no state change should occur."
  11319. (let* ((fulltable org-todo-key-alist)
  11320. (done-keywords org-done-keywords) ;; needed for the faces.
  11321. (maxlen (apply 'max (mapcar
  11322. (lambda (x)
  11323. (if (stringp (car x)) (string-width (car x)) 0))
  11324. fulltable)))
  11325. (expert nil)
  11326. (fwidth (+ maxlen 3 1 3))
  11327. (ncol (/ (- (window-width) 4) fwidth))
  11328. tg cnt e c tbl
  11329. groups ingroup)
  11330. (save-excursion
  11331. (save-window-excursion
  11332. (if expert
  11333. (set-buffer (get-buffer-create " *Org todo*"))
  11334. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11335. (erase-buffer)
  11336. (setq-local org-done-keywords done-keywords)
  11337. (setq tbl fulltable cnt 0)
  11338. (while (setq e (pop tbl))
  11339. (cond
  11340. ((equal e '(:startgroup))
  11341. (push '() groups) (setq ingroup t)
  11342. (unless (= cnt 0)
  11343. (setq cnt 0)
  11344. (insert "\n"))
  11345. (insert "{ "))
  11346. ((equal e '(:endgroup))
  11347. (setq ingroup nil cnt 0)
  11348. (insert "}\n"))
  11349. ((equal e '(:newline))
  11350. (unless (= cnt 0)
  11351. (setq cnt 0)
  11352. (insert "\n")
  11353. (setq e (car tbl))
  11354. (while (equal (car tbl) '(:newline))
  11355. (insert "\n")
  11356. (setq tbl (cdr tbl)))))
  11357. (t
  11358. (setq tg (car e) c (cdr e))
  11359. (when ingroup (push tg (car groups)))
  11360. (setq tg (org-add-props tg nil 'face
  11361. (org-get-todo-face tg)))
  11362. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11363. (insert "[" c "] " tg (make-string
  11364. (- fwidth 4 (length tg)) ?\ ))
  11365. (when (= (setq cnt (1+ cnt)) ncol)
  11366. (insert "\n")
  11367. (when ingroup (insert " "))
  11368. (setq cnt 0)))))
  11369. (insert "\n")
  11370. (goto-char (point-min))
  11371. (unless expert (org-fit-window-to-buffer))
  11372. (message "[a-z..]:Set [SPC]:clear")
  11373. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11374. (cond
  11375. ((or (= c ?\C-g)
  11376. (and (= c ?q) (not (rassoc c fulltable))))
  11377. (setq quit-flag t))
  11378. ((= c ?\ ) nil)
  11379. ((setq e (rassoc c fulltable) tg (car e))
  11380. tg)
  11381. (t (setq quit-flag t)))))))
  11382. (defun org-entry-is-todo-p ()
  11383. (member (org-get-todo-state) org-not-done-keywords))
  11384. (defun org-entry-is-done-p ()
  11385. (member (org-get-todo-state) org-done-keywords))
  11386. (defun org-get-todo-state ()
  11387. "Return the TODO keyword of the current subtree."
  11388. (save-excursion
  11389. (org-back-to-heading t)
  11390. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11391. (match-end 2)
  11392. (match-string 2))))
  11393. (defun org-at-date-range-p (&optional inactive-ok)
  11394. "Non-nil if point is inside a date range.
  11395. When optional argument INACTIVE-OK is non-nil, also consider
  11396. inactive time ranges.
  11397. When this function returns a non-nil value, match data is set
  11398. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11399. on INACTIVE-OK."
  11400. (interactive)
  11401. (save-excursion
  11402. (catch 'exit
  11403. (let ((pos (point)))
  11404. (skip-chars-backward "^[<\r\n")
  11405. (skip-chars-backward "<[")
  11406. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11407. (>= (match-end 0) pos)
  11408. (throw 'exit t))
  11409. (skip-chars-backward "^<[\r\n")
  11410. (skip-chars-backward "<[")
  11411. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11412. (>= (match-end 0) pos)
  11413. (throw 'exit t)))
  11414. nil)))
  11415. (defun org-get-repeat (&optional timestamp)
  11416. "Check if there is a time-stamp with repeater in this entry.
  11417. Return the repeater, as a string, or nil. Also return nil when
  11418. this function is called before first heading.
  11419. When optional argument TIMESTAMP is a string, extract the
  11420. repeater from there instead."
  11421. (save-match-data
  11422. (cond (timestamp
  11423. (and (string-match org-repeat-re timestamp)
  11424. (match-string-no-properties 1 timestamp)))
  11425. ((org-before-first-heading-p) nil)
  11426. (t
  11427. (save-excursion
  11428. (org-back-to-heading t)
  11429. (let ((end (org-entry-end-position)))
  11430. (catch :repeat
  11431. (while (re-search-forward org-repeat-re end t)
  11432. (when (save-match-data (org-at-timestamp-p 'agenda))
  11433. (throw :repeat (match-string-no-properties 1)))))))))))
  11434. (defvar org-last-changed-timestamp)
  11435. (defvar org-last-inserted-timestamp)
  11436. (defvar org-log-post-message)
  11437. (defvar org-log-note-purpose)
  11438. (defvar org-log-note-how nil)
  11439. (defvar org-log-note-extra)
  11440. (defun org-auto-repeat-maybe (done-word)
  11441. "Check if the current headline contains a repeated time-stamp.
  11442. If yes, set TODO state back to what it was and change the base date
  11443. of repeating deadline/scheduled time stamps to new date.
  11444. This function is run automatically after each state change to a DONE state."
  11445. (let* ((repeat (org-get-repeat))
  11446. (aa (assoc org-last-state org-todo-kwd-alist))
  11447. (interpret (nth 1 aa))
  11448. (head (nth 2 aa))
  11449. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11450. (msg "Entry repeats: ")
  11451. (org-log-done nil)
  11452. (org-todo-log-states nil)
  11453. (end (copy-marker (org-entry-end-position))))
  11454. (unwind-protect
  11455. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11456. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11457. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11458. (and (stringp org-todo-repeat-to-state)
  11459. org-todo-repeat-to-state)
  11460. (and org-todo-repeat-to-state org-last-state))))
  11461. (org-todo (cond
  11462. ((and to-state (member to-state org-todo-keywords-1))
  11463. to-state)
  11464. ((eq interpret 'type) org-last-state)
  11465. (head)
  11466. (t 'none))))
  11467. (org-back-to-heading t)
  11468. (org-add-planning-info nil nil 'closed)
  11469. ;; When `org-log-repeat' is non-nil or entry contains
  11470. ;; a clock, set LAST_REPEAT property.
  11471. (when (or org-log-repeat
  11472. (catch :clock
  11473. (save-excursion
  11474. (while (re-search-forward org-clock-line-re end t)
  11475. (when (org-at-clock-log-p) (throw :clock t))))))
  11476. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11477. (org-time-stamp-format t t)
  11478. (current-time))))
  11479. (when org-log-repeat
  11480. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11481. (memq 'org-add-log-note post-command-hook))
  11482. ;; We are already setup for some record.
  11483. (when (eq org-log-repeat 'note)
  11484. ;; Make sure we take a note, not only a time stamp.
  11485. (setq org-log-note-how 'note))
  11486. ;; Set up for taking a record.
  11487. (org-add-log-setup 'state
  11488. (or done-word (car org-done-keywords))
  11489. org-last-state
  11490. org-log-repeat)))
  11491. (let ((planning-re (regexp-opt
  11492. (list org-scheduled-string org-deadline-string))))
  11493. (while (re-search-forward org-ts-regexp end t)
  11494. (let* ((ts (match-string 0))
  11495. (planning? (org-at-planning-p))
  11496. (type (if (not planning?) "Plain:"
  11497. (save-excursion
  11498. (re-search-backward
  11499. planning-re (line-beginning-position) t)
  11500. (match-string 0)))))
  11501. (cond
  11502. ;; Ignore fake time-stamps (e.g., within comments).
  11503. ((not (org-at-timestamp-p 'agenda)))
  11504. ;; Time-stamps without a repeater are usually
  11505. ;; skipped. However, a SCHEDULED time-stamp without
  11506. ;; one is removed, as they are no longer relevant.
  11507. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11508. ts))
  11509. (when (equal type org-scheduled-string)
  11510. (org-remove-timestamp-with-keyword type)))
  11511. (t
  11512. (let ((n (string-to-number (match-string 2 ts)))
  11513. (what (match-string 3 ts)))
  11514. (when (equal what "w") (setq n (* n 7) what "d"))
  11515. (when (and (equal what "h")
  11516. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11517. ts)))
  11518. (user-error
  11519. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11520. has been set"
  11521. n))
  11522. ;; Preparation, see if we need to modify the start
  11523. ;; date for the change.
  11524. (when (match-end 1)
  11525. (let ((time (save-match-data
  11526. (org-time-string-to-time ts))))
  11527. (cond
  11528. ((equal (match-string 1 ts) ".")
  11529. ;; Shift starting date to today
  11530. (org-timestamp-change
  11531. (- (org-today) (time-to-days time))
  11532. 'day))
  11533. ((equal (match-string 1 ts) "+")
  11534. (let ((nshiftmax 10)
  11535. (nshift 0))
  11536. (while (or (= nshift 0)
  11537. (not (time-less-p (current-time) time)))
  11538. (when (= (cl-incf nshift) nshiftmax)
  11539. (or (y-or-n-p
  11540. (format "%d repeater intervals were not \
  11541. enough to shift date past today. Continue? "
  11542. nshift))
  11543. (user-error "Abort")))
  11544. (org-timestamp-change n (cdr (assoc what whata)))
  11545. (org-in-regexp org-ts-regexp3)
  11546. (setq ts (match-string 1))
  11547. (setq time
  11548. (save-match-data
  11549. (org-time-string-to-time ts)))))
  11550. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11551. ;; Rematch, so that we have everything in place
  11552. ;; for the real shift.
  11553. (org-in-regexp org-ts-regexp3)
  11554. (setq ts (match-string 1))
  11555. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11556. ts)))))
  11557. (save-excursion
  11558. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11559. (setq msg
  11560. (concat
  11561. msg type " " org-last-changed-timestamp " "))))))))
  11562. (setq org-log-post-message msg)
  11563. (message "%s" msg))
  11564. (set-marker end nil))))
  11565. (defun org-show-todo-tree (arg)
  11566. "Make a compact tree which shows all headlines marked with TODO.
  11567. The tree will show the lines where the regexp matches, and all higher
  11568. headlines above the match.
  11569. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11570. With a numeric prefix N, construct a sparse tree for the Nth element
  11571. of `org-todo-keywords-1'."
  11572. (interactive "P")
  11573. (let ((case-fold-search nil)
  11574. (kwd-re
  11575. (cond ((null arg) org-not-done-regexp)
  11576. ((equal arg '(4))
  11577. (let ((kwd
  11578. (completing-read "Keyword (or KWD1|KWD2|...): "
  11579. (mapcar #'list org-todo-keywords-1))))
  11580. (concat "\\("
  11581. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11582. "\\)\\>")))
  11583. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11584. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11585. org-todo-keywords-1)))
  11586. (t (user-error "Invalid prefix argument: %s" arg)))))
  11587. (message "%d TODO entries found"
  11588. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11589. (defun org--deadline-or-schedule (arg type time)
  11590. "Insert DEADLINE or SCHEDULE information in current entry.
  11591. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11592. `org-schedule' for information about ARG and TIME arguments."
  11593. (let* ((deadline? (eq type 'deadline))
  11594. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11595. (log (if deadline? org-log-redeadline org-log-reschedule))
  11596. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11597. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11598. ;; Save repeater cookie from either TIME or current scheduled
  11599. ;; time stamp. We are going to insert it back at the end of
  11600. ;; the process.
  11601. (repeater (or (and (org-string-nw-p time)
  11602. ;; We use `org-repeat-re' because we need
  11603. ;; to tell the difference between a real
  11604. ;; repeater and a time delta, e.g. "+2d".
  11605. (string-match org-repeat-re time)
  11606. (match-string 1 time))
  11607. (and (org-string-nw-p old-date)
  11608. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11609. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11610. old-date)
  11611. (match-string 1 old-date)))))
  11612. (pcase arg
  11613. (`(4)
  11614. (if (not old-date)
  11615. (message (if deadline? "Entry had no deadline to remove"
  11616. "Entry was not scheduled"))
  11617. (when (and old-date log)
  11618. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11619. nil old-date log))
  11620. (org-remove-timestamp-with-keyword keyword)
  11621. (message (if deadline? "Entry no longer has a deadline."
  11622. "Entry is no longer scheduled."))))
  11623. (`(16)
  11624. (save-excursion
  11625. (org-back-to-heading t)
  11626. (let ((regexp (if deadline? org-deadline-time-regexp
  11627. org-scheduled-time-regexp)))
  11628. (if (not (re-search-forward regexp (line-end-position 2) t))
  11629. (user-error (if deadline? "No deadline information to update"
  11630. "No scheduled information to update"))
  11631. (let* ((rpl0 (match-string 1))
  11632. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  11633. (msg (if deadline? "Warn starting from" "Delay until")))
  11634. (replace-match
  11635. (concat keyword
  11636. " <" rpl
  11637. (format " -%dd"
  11638. (abs (- (time-to-days
  11639. (save-match-data
  11640. (org-read-date
  11641. nil t nil msg old-date-time)))
  11642. (time-to-days old-date-time))))
  11643. ">") t t))))))
  11644. (_
  11645. (org-add-planning-info type time 'closed)
  11646. (when (and old-date
  11647. log
  11648. (not (equal old-date org-last-inserted-timestamp)))
  11649. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  11650. org-last-inserted-timestamp
  11651. old-date
  11652. log))
  11653. (when repeater
  11654. (save-excursion
  11655. (org-back-to-heading t)
  11656. (when (re-search-forward
  11657. (concat keyword " " org-last-inserted-timestamp)
  11658. (line-end-position 2)
  11659. t)
  11660. (goto-char (1- (match-end 0)))
  11661. (insert " " repeater)
  11662. (setq org-last-inserted-timestamp
  11663. (concat (substring org-last-inserted-timestamp 0 -1)
  11664. " " repeater
  11665. (substring org-last-inserted-timestamp -1))))))
  11666. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  11667. org-last-inserted-timestamp)))))
  11668. (defun org-deadline (arg &optional time)
  11669. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  11670. With one universal prefix argument, remove any deadline from the item.
  11671. With two universal prefix arguments, prompt for a warning delay.
  11672. With argument TIME, set the deadline at the corresponding date. TIME
  11673. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11674. (interactive "P")
  11675. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11676. (org-map-entries
  11677. (lambda () (org--deadline-or-schedule arg 'deadline time))
  11678. nil
  11679. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11680. 'region-start-level
  11681. 'region)
  11682. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11683. (org--deadline-or-schedule arg 'deadline time)))
  11684. (defun org-schedule (arg &optional time)
  11685. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  11686. With one universal prefix argument, remove any scheduling date from the item.
  11687. With two universal prefix arguments, prompt for a delay cookie.
  11688. With argument TIME, scheduled at the corresponding date. TIME can
  11689. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11690. (interactive "P")
  11691. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11692. (org-map-entries
  11693. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  11694. nil
  11695. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11696. 'region-start-level
  11697. 'region)
  11698. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11699. (org--deadline-or-schedule arg 'scheduled time)))
  11700. (defun org-get-scheduled-time (pom &optional inherit)
  11701. "Get the scheduled time as a time tuple, of a format suitable
  11702. for calling org-schedule with, or if there is no scheduling,
  11703. returns nil."
  11704. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  11705. (when time
  11706. (apply 'encode-time (org-parse-time-string time)))))
  11707. (defun org-get-deadline-time (pom &optional inherit)
  11708. "Get the deadline as a time tuple, of a format suitable for
  11709. calling org-deadline with, or if there is no scheduling, returns
  11710. nil."
  11711. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  11712. (when time
  11713. (apply 'encode-time (org-parse-time-string time)))))
  11714. (defun org-remove-timestamp-with-keyword (keyword)
  11715. "Remove all time stamps with KEYWORD in the current entry."
  11716. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  11717. beg)
  11718. (save-excursion
  11719. (org-back-to-heading t)
  11720. (setq beg (point))
  11721. (outline-next-heading)
  11722. (while (re-search-backward re beg t)
  11723. (replace-match "")
  11724. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  11725. (equal (char-before) ?\ ))
  11726. (backward-delete-char 1)
  11727. (when (string-match "^[ \t]*$" (buffer-substring
  11728. (point-at-bol) (point-at-eol)))
  11729. (delete-region (point-at-bol)
  11730. (min (point-max) (1+ (point-at-eol))))))))))
  11731. (defvar org-time-was-given) ; dynamically scoped parameter
  11732. (defvar org-end-time-was-given) ; dynamically scoped parameter
  11733. (defun org-at-planning-p ()
  11734. "Non-nil when point is on a planning info line."
  11735. ;; This is as accurate and faster than `org-element-at-point' since
  11736. ;; planning info location is fixed in the section.
  11737. (org-with-wide-buffer
  11738. (beginning-of-line)
  11739. (and (looking-at-p org-planning-line-re)
  11740. (eq (point)
  11741. (ignore-errors
  11742. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  11743. (org-back-to-heading t)
  11744. (org-with-limited-levels (org-back-to-heading t)))
  11745. (line-beginning-position 2))))))
  11746. (defun org-add-planning-info (what &optional time &rest remove)
  11747. "Insert new timestamp with keyword in the planning line.
  11748. WHAT indicates what kind of time stamp to add. It is a symbol
  11749. among `closed', `deadline', `scheduled' and nil. TIME indicates
  11750. the time to use. If none is given, the user is prompted for
  11751. a date. REMOVE indicates what kind of entries to remove. An old
  11752. WHAT entry will also be removed."
  11753. (let (org-time-was-given org-end-time-was-given default-time default-input)
  11754. (catch 'exit
  11755. (when (and (memq what '(scheduled deadline))
  11756. (or (not time)
  11757. (and (stringp time)
  11758. (string-match "^[-+]+[0-9]" time))))
  11759. ;; Try to get a default date/time from existing timestamp
  11760. (save-excursion
  11761. (org-back-to-heading t)
  11762. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  11763. (when (re-search-forward (if (eq what 'scheduled)
  11764. org-scheduled-time-regexp
  11765. org-deadline-time-regexp)
  11766. end t)
  11767. (setq ts (match-string 1)
  11768. default-time (apply 'encode-time (org-parse-time-string ts))
  11769. default-input (and ts (org-get-compact-tod ts)))))))
  11770. (when what
  11771. (setq time
  11772. (if (stringp time)
  11773. ;; This is a string (relative or absolute), set
  11774. ;; proper date.
  11775. (apply #'encode-time
  11776. (org-read-date-analyze
  11777. time default-time (decode-time default-time)))
  11778. ;; If necessary, get the time from the user
  11779. (or time (org-read-date nil 'to-time nil nil
  11780. default-time default-input)))))
  11781. (org-with-wide-buffer
  11782. (org-back-to-heading t)
  11783. (forward-line)
  11784. (unless (bolp) (insert "\n"))
  11785. (cond ((looking-at-p org-planning-line-re)
  11786. ;; Move to current indentation.
  11787. (skip-chars-forward " \t")
  11788. ;; Check if we have to remove something.
  11789. (dolist (type (if what (cons what remove) remove))
  11790. (save-excursion
  11791. (when (re-search-forward
  11792. (cl-case type
  11793. (closed org-closed-time-regexp)
  11794. (deadline org-deadline-time-regexp)
  11795. (scheduled org-scheduled-time-regexp)
  11796. (otherwise
  11797. (error "Invalid planning type: %s" type)))
  11798. (line-end-position) t)
  11799. ;; Delete until next keyword or end of line.
  11800. (delete-region
  11801. (match-beginning 0)
  11802. (if (re-search-forward org-keyword-time-not-clock-regexp
  11803. (line-end-position)
  11804. t)
  11805. (match-beginning 0)
  11806. (line-end-position))))))
  11807. ;; If there is nothing more to add and no more keyword
  11808. ;; is left, remove the line completely.
  11809. (if (and (looking-at-p "[ \t]*$") (not what))
  11810. (delete-region (line-beginning-position)
  11811. (line-beginning-position 2))
  11812. ;; If we removed last keyword, do not leave trailing
  11813. ;; white space at the end of line.
  11814. (let ((p (point)))
  11815. (save-excursion
  11816. (end-of-line)
  11817. (unless (= (skip-chars-backward " \t" p) 0)
  11818. (delete-region (point) (line-end-position)))))))
  11819. ((not what) (throw 'exit nil)) ; Nothing to do.
  11820. (t (insert-before-markers "\n")
  11821. (backward-char 1)
  11822. (when org-adapt-indentation
  11823. (indent-to-column (1+ (org-outline-level))))))
  11824. (when what
  11825. ;; Insert planning keyword.
  11826. (insert (cl-case what
  11827. (closed org-closed-string)
  11828. (deadline org-deadline-string)
  11829. (scheduled org-scheduled-string)
  11830. (otherwise (error "Invalid planning type: %s" what)))
  11831. " ")
  11832. ;; Insert associated timestamp.
  11833. (let ((ts (org-insert-time-stamp
  11834. time
  11835. (or org-time-was-given
  11836. (and (eq what 'closed) org-log-done-with-time))
  11837. (eq what 'closed)
  11838. nil nil (list org-end-time-was-given))))
  11839. (unless (eolp) (insert " "))
  11840. ts))))))
  11841. (defvar org-log-note-marker (make-marker)
  11842. "Marker pointing at the entry where the note is to be inserted.")
  11843. (defvar org-log-note-purpose nil)
  11844. (defvar org-log-note-state nil)
  11845. (defvar org-log-note-previous-state nil)
  11846. (defvar org-log-note-extra nil)
  11847. (defvar org-log-note-window-configuration nil)
  11848. (defvar org-log-note-return-to (make-marker))
  11849. (defvar org-log-note-effective-time nil
  11850. "Remembered current time so that dynamically scoped
  11851. `org-extend-today-until' affects timestamps in state change log")
  11852. (defvar org-log-post-message nil
  11853. "Message to be displayed after a log note has been stored.
  11854. The auto-repeater uses this.")
  11855. (defun org-add-note ()
  11856. "Add a note to the current entry.
  11857. This is done in the same way as adding a state change note."
  11858. (interactive)
  11859. (org-add-log-setup 'note))
  11860. (defun org-log-beginning (&optional create)
  11861. "Return expected start of log notes in current entry.
  11862. When optional argument CREATE is non-nil, the function creates
  11863. a drawer to store notes, if necessary. Returned position ignores
  11864. narrowing."
  11865. (org-with-wide-buffer
  11866. (let ((drawer (org-log-into-drawer)))
  11867. (cond
  11868. (drawer
  11869. (org-end-of-meta-data)
  11870. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  11871. (end (if (org-at-heading-p) (point)
  11872. (save-excursion (outline-next-heading) (point))))
  11873. (case-fold-search t))
  11874. (catch 'exit
  11875. ;; Try to find existing drawer.
  11876. (while (re-search-forward regexp end t)
  11877. (let ((element (org-element-at-point)))
  11878. (when (eq (org-element-type element) 'drawer)
  11879. (let ((cend (org-element-property :contents-end element)))
  11880. (when (and (not org-log-states-order-reversed) cend)
  11881. (goto-char cend)))
  11882. (throw 'exit nil))))
  11883. ;; No drawer found. Create one, if permitted.
  11884. (when create
  11885. (unless (bolp) (insert "\n"))
  11886. (let ((beg (point)))
  11887. (insert ":" drawer ":\n:END:\n")
  11888. (org-indent-region beg (point))
  11889. (org-flag-region
  11890. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  11891. (end-of-line -1)))))
  11892. (t
  11893. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  11894. (skip-chars-forward " \t\n")
  11895. (beginning-of-line)
  11896. (unless org-log-states-order-reversed
  11897. (org-skip-over-state-notes)
  11898. (skip-chars-backward " \t\n")
  11899. (forward-line)))))
  11900. (if (bolp) (point) (line-beginning-position 2))))
  11901. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  11902. "Set up the post command hook to take a note.
  11903. If this is about to TODO state change, the new state is expected in STATE.
  11904. HOW is an indicator what kind of note should be created.
  11905. EXTRA is additional text that will be inserted into the notes buffer."
  11906. (move-marker org-log-note-marker (point))
  11907. (setq org-log-note-purpose purpose
  11908. org-log-note-state state
  11909. org-log-note-previous-state prev-state
  11910. org-log-note-how how
  11911. org-log-note-extra extra
  11912. org-log-note-effective-time (org-current-effective-time))
  11913. (add-hook 'post-command-hook 'org-add-log-note 'append))
  11914. (defun org-skip-over-state-notes ()
  11915. "Skip past the list of State notes in an entry."
  11916. (when (ignore-errors (goto-char (org-in-item-p)))
  11917. (let* ((struct (org-list-struct))
  11918. (prevs (org-list-prevs-alist struct))
  11919. (regexp
  11920. (concat "[ \t]*- +"
  11921. (replace-regexp-in-string
  11922. " +" " +"
  11923. (org-replace-escapes
  11924. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  11925. `(("%d" . ,org-ts-regexp-inactive)
  11926. ("%D" . ,org-ts-regexp)
  11927. ("%s" . "\\(?:\"\\S-+\"\\)?")
  11928. ("%S" . "\\(?:\"\\S-+\"\\)?")
  11929. ("%t" . ,org-ts-regexp-inactive)
  11930. ("%T" . ,org-ts-regexp)
  11931. ("%u" . ".*?")
  11932. ("%U" . ".*?")))))))
  11933. (while (looking-at-p regexp)
  11934. (goto-char (or (org-list-get-next-item (point) struct prevs)
  11935. (org-list-get-item-end (point) struct)))))))
  11936. (defun org-add-log-note (&optional _purpose)
  11937. "Pop up a window for taking a note, and add this note later."
  11938. (remove-hook 'post-command-hook 'org-add-log-note)
  11939. (setq org-log-note-window-configuration (current-window-configuration))
  11940. (delete-other-windows)
  11941. (move-marker org-log-note-return-to (point))
  11942. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  11943. (goto-char org-log-note-marker)
  11944. (org-switch-to-buffer-other-window "*Org Note*")
  11945. (erase-buffer)
  11946. (if (memq org-log-note-how '(time state))
  11947. (org-store-log-note)
  11948. (let ((org-inhibit-startup t)) (org-mode))
  11949. (insert (format "# Insert note for %s.
  11950. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  11951. (cl-case org-log-note-purpose
  11952. (clock-out "stopped clock")
  11953. (done "closed todo item")
  11954. (reschedule "rescheduling")
  11955. (delschedule "no longer scheduled")
  11956. (redeadline "changing deadline")
  11957. (deldeadline "removing deadline")
  11958. (refile "refiling")
  11959. (note "this entry")
  11960. (state
  11961. (format "state change from \"%s\" to \"%s\""
  11962. (or org-log-note-previous-state "")
  11963. (or org-log-note-state "")))
  11964. (t (error "This should not happen")))))
  11965. (when org-log-note-extra (insert org-log-note-extra))
  11966. (setq-local org-finish-function 'org-store-log-note)
  11967. (run-hooks 'org-log-buffer-setup-hook)))
  11968. (defvar org-note-abort nil) ; dynamically scoped
  11969. (defun org-store-log-note ()
  11970. "Finish taking a log note, and insert it to where it belongs."
  11971. (let ((txt (prog1 (buffer-string)
  11972. (kill-buffer)))
  11973. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  11974. lines)
  11975. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  11976. (setq txt (replace-match "" t t txt)))
  11977. (when (string-match "\\s-+\\'" txt)
  11978. (setq txt (replace-match "" t t txt)))
  11979. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  11980. (when (org-string-nw-p note)
  11981. (setq note
  11982. (org-replace-escapes
  11983. note
  11984. (list (cons "%u" (user-login-name))
  11985. (cons "%U" user-full-name)
  11986. (cons "%t" (format-time-string
  11987. (org-time-stamp-format 'long 'inactive)
  11988. org-log-note-effective-time))
  11989. (cons "%T" (format-time-string
  11990. (org-time-stamp-format 'long nil)
  11991. org-log-note-effective-time))
  11992. (cons "%d" (format-time-string
  11993. (org-time-stamp-format nil 'inactive)
  11994. org-log-note-effective-time))
  11995. (cons "%D" (format-time-string
  11996. (org-time-stamp-format nil nil)
  11997. org-log-note-effective-time))
  11998. (cons "%s" (cond
  11999. ((not org-log-note-state) "")
  12000. ((string-match-p org-ts-regexp
  12001. org-log-note-state)
  12002. (format "\"[%s]\""
  12003. (substring org-log-note-state 1 -1)))
  12004. (t (format "\"%s\"" org-log-note-state))))
  12005. (cons "%S"
  12006. (cond
  12007. ((not org-log-note-previous-state) "")
  12008. ((string-match-p org-ts-regexp
  12009. org-log-note-previous-state)
  12010. (format "\"[%s]\""
  12011. (substring
  12012. org-log-note-previous-state 1 -1)))
  12013. (t (format "\"%s\""
  12014. org-log-note-previous-state)))))))
  12015. (when lines (setq note (concat note " \\\\")))
  12016. (push note lines))
  12017. (when (and lines (not org-note-abort))
  12018. (with-current-buffer (marker-buffer org-log-note-marker)
  12019. (org-with-wide-buffer
  12020. ;; Find location for the new note.
  12021. (goto-char org-log-note-marker)
  12022. (set-marker org-log-note-marker nil)
  12023. ;; Note associated to a clock is to be located right after
  12024. ;; the clock. Do not move point.
  12025. (unless (eq org-log-note-purpose 'clock-out)
  12026. (goto-char (org-log-beginning t)))
  12027. ;; Make sure point is at the beginning of an empty line.
  12028. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12029. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12030. ;; In an existing list, add a new item at the top level.
  12031. ;; Otherwise, indent line like a regular one.
  12032. (let ((itemp (org-in-item-p)))
  12033. (if itemp
  12034. (indent-line-to
  12035. (let ((struct (save-excursion
  12036. (goto-char itemp) (org-list-struct))))
  12037. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12038. (org-indent-line)))
  12039. (insert (org-list-bullet-string "-") (pop lines))
  12040. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12041. (dolist (line lines)
  12042. (insert "\n")
  12043. (indent-line-to ind)
  12044. (insert line)))
  12045. (message "Note stored")
  12046. (org-back-to-heading t))
  12047. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12048. ;; from within `org-add-log-note' because `buffer-undo-list'
  12049. ;; is then modified outside of `org-with-remote-undo'.
  12050. (when (eq this-command 'org-agenda-todo)
  12051. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12052. ;; Don't add undo information when called from `org-agenda-todo'.
  12053. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12054. (set-window-configuration org-log-note-window-configuration)
  12055. (with-current-buffer (marker-buffer org-log-note-return-to)
  12056. (goto-char org-log-note-return-to))
  12057. (move-marker org-log-note-return-to nil)
  12058. (when org-log-post-message (message "%s" org-log-post-message))))
  12059. (defun org-remove-empty-drawer-at (pos)
  12060. "Remove an empty drawer at position POS.
  12061. POS may also be a marker."
  12062. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12063. (org-with-wide-buffer
  12064. (goto-char pos)
  12065. (let ((drawer (org-element-at-point)))
  12066. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12067. (not (org-element-property :contents-begin drawer)))
  12068. (delete-region (org-element-property :begin drawer)
  12069. (progn (goto-char (org-element-property :end drawer))
  12070. (skip-chars-backward " \r\t\n")
  12071. (forward-line)
  12072. (point))))))))
  12073. (defvar org-ts-type nil)
  12074. (defun org-sparse-tree (&optional arg type)
  12075. "Create a sparse tree, prompt for the details.
  12076. This command can create sparse trees. You first need to select the type
  12077. of match used to create the tree:
  12078. t Show all TODO entries.
  12079. T Show entries with a specific TODO keyword.
  12080. m Show entries selected by a tags/property match.
  12081. p Enter a property name and its value (both with completion on existing
  12082. names/values) and show entries with that property.
  12083. r Show entries matching a regular expression (`/' can be used as well).
  12084. b Show deadlines and scheduled items before a date.
  12085. a Show deadlines and scheduled items after a date.
  12086. d Show deadlines due within `org-deadline-warning-days'.
  12087. D Show deadlines and scheduled items between a date range."
  12088. (interactive "P")
  12089. (setq type (or type org-sparse-tree-default-date-type))
  12090. (setq org-ts-type type)
  12091. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12092. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12093. \[c]ycle through date types: %s"
  12094. (cl-case type
  12095. (all "all timestamps")
  12096. (scheduled "only scheduled")
  12097. (deadline "only deadline")
  12098. (active "only active timestamps")
  12099. (inactive "only inactive timestamps")
  12100. (closed "with a closed time-stamp")
  12101. (otherwise "scheduled/deadline")))
  12102. (let ((answer (read-char-exclusive)))
  12103. (cl-case answer
  12104. (?c
  12105. (org-sparse-tree
  12106. arg
  12107. (cadr
  12108. (memq type '(nil all scheduled deadline active inactive closed)))))
  12109. (?d (call-interactively 'org-check-deadlines))
  12110. (?b (call-interactively 'org-check-before-date))
  12111. (?a (call-interactively 'org-check-after-date))
  12112. (?D (call-interactively 'org-check-dates-range))
  12113. (?t (call-interactively 'org-show-todo-tree))
  12114. (?T (org-show-todo-tree '(4)))
  12115. (?m (call-interactively 'org-match-sparse-tree))
  12116. ((?p ?P)
  12117. (let* ((kwd (completing-read
  12118. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12119. (value (completing-read
  12120. "Value: " (mapcar #'list (org-property-values kwd)))))
  12121. (unless (string-match "\\`{.*}\\'" value)
  12122. (setq value (concat "\"" value "\"")))
  12123. (org-match-sparse-tree arg (concat kwd "=" value))))
  12124. ((?r ?R ?/) (call-interactively 'org-occur))
  12125. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12126. (defvar-local org-occur-highlights nil
  12127. "List of overlays used for occur matches.")
  12128. (defvar-local org-occur-parameters nil
  12129. "Parameters of the active org-occur calls.
  12130. This is a list, each call to org-occur pushes as cons cell,
  12131. containing the regular expression and the callback, onto the list.
  12132. The list can contain several entries if `org-occur' has been called
  12133. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12134. will only contain one set of parameters. When the highlights are
  12135. removed (for example with `C-c C-c', or with the next edit (depending
  12136. on `org-remove-highlights-with-change'), this variable is emptied
  12137. as well.")
  12138. (defun org-occur (regexp &optional keep-previous callback)
  12139. "Make a compact tree which shows all matches of REGEXP.
  12140. The tree will show the lines where the regexp matches, and any other context
  12141. defined in `org-show-context-detail', which see.
  12142. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12143. done by a previous call to `org-occur' will be kept, to allow stacking of
  12144. calls to this command.
  12145. Optional argument CALLBACK can be a function of no argument. In this case,
  12146. it is called with point at the end of the match, match data being set
  12147. accordingly. Current match is shown only if the return value is non-nil.
  12148. The function must neither move point nor alter narrowing."
  12149. (interactive "sRegexp: \nP")
  12150. (when (equal regexp "")
  12151. (user-error "Regexp cannot be empty"))
  12152. (unless keep-previous
  12153. (org-remove-occur-highlights nil nil t))
  12154. (push (cons regexp callback) org-occur-parameters)
  12155. (let ((cnt 0))
  12156. (save-excursion
  12157. (goto-char (point-min))
  12158. (when (or (not keep-previous) ; do not want to keep
  12159. (not org-occur-highlights)) ; no previous matches
  12160. ;; hide everything
  12161. (org-overview))
  12162. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12163. (isearch-no-upper-case-p regexp t)
  12164. org-occur-case-fold-search)))
  12165. (while (re-search-forward regexp nil t)
  12166. (when (or (not callback)
  12167. (save-match-data (funcall callback)))
  12168. (setq cnt (1+ cnt))
  12169. (when org-highlight-sparse-tree-matches
  12170. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12171. (org-show-context 'occur-tree)))))
  12172. (when org-remove-highlights-with-change
  12173. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12174. nil 'local))
  12175. (unless org-sparse-tree-open-archived-trees
  12176. (org-hide-archived-subtrees (point-min) (point-max)))
  12177. (run-hooks 'org-occur-hook)
  12178. (when (called-interactively-p 'interactive)
  12179. (message "%d match(es) for regexp %s" cnt regexp))
  12180. cnt))
  12181. (defun org-occur-next-match (&optional n _reset)
  12182. "Function for `next-error-function' to find sparse tree matches.
  12183. N is the number of matches to move, when negative move backwards.
  12184. This function always goes back to the starting point when no
  12185. match is found."
  12186. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12187. (search-func (if (< n 0)
  12188. 'previous-single-char-property-change
  12189. 'next-single-char-property-change))
  12190. (n (abs n))
  12191. (pos (point))
  12192. p1)
  12193. (catch 'exit
  12194. (while (setq p1 (funcall search-func (point) 'org-type))
  12195. (when (equal p1 limit)
  12196. (goto-char pos)
  12197. (user-error "No more matches"))
  12198. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12199. (setq n (1- n))
  12200. (when (= n 0)
  12201. (goto-char p1)
  12202. (throw 'exit (point))))
  12203. (goto-char p1))
  12204. (goto-char p1)
  12205. (user-error "No more matches"))))
  12206. (defun org-highlight-new-match (beg end)
  12207. "Highlight from BEG to END and mark the highlight is an occur headline."
  12208. (let ((ov (make-overlay beg end)))
  12209. (overlay-put ov 'face 'secondary-selection)
  12210. (overlay-put ov 'org-type 'org-occur)
  12211. (push ov org-occur-highlights)))
  12212. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12213. "Remove the occur highlights from the buffer.
  12214. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12215. from the `before-change-functions' in the current buffer."
  12216. (interactive)
  12217. (unless org-inhibit-highlight-removal
  12218. (mapc #'delete-overlay org-occur-highlights)
  12219. (setq org-occur-highlights nil)
  12220. (setq org-occur-parameters nil)
  12221. (unless noremove
  12222. (remove-hook 'before-change-functions
  12223. 'org-remove-occur-highlights 'local))))
  12224. ;;;; Priorities
  12225. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12226. "Regular expression matching the priority indicator.")
  12227. (defvar org-remove-priority-next-time nil)
  12228. (defun org-priority-up ()
  12229. "Increase the priority of the current item."
  12230. (interactive)
  12231. (org-priority 'up))
  12232. (defun org-priority-down ()
  12233. "Decrease the priority of the current item."
  12234. (interactive)
  12235. (org-priority 'down))
  12236. (defun org-priority (&optional action show)
  12237. "Change the priority of an item.
  12238. When called interactively with a `\\[universal-argument]' prefix,
  12239. show the priority in the minibuffer instead of changing it.
  12240. When called programatically, ACTION can be `set', `up', `down',
  12241. or a character."
  12242. (interactive "P")
  12243. (when show
  12244. ;; Deprecation warning inserted for Org 9.2; once enough time has
  12245. ;; passed the SHOW argument should be removed.
  12246. (warn "`org-priority' called with deprecated SHOW argument"))
  12247. (if (equal action '(4))
  12248. (org-show-priority)
  12249. (unless org-enable-priority-commands
  12250. (user-error "Priority commands are disabled"))
  12251. (setq action (or action 'set))
  12252. (let (current new news have remove)
  12253. (save-excursion
  12254. (org-back-to-heading t)
  12255. (when (looking-at org-priority-regexp)
  12256. (setq current (string-to-char (match-string 2))
  12257. have t))
  12258. (cond
  12259. ((eq action 'remove)
  12260. (setq remove t new ?\ ))
  12261. ((or (eq action 'set)
  12262. (integerp action))
  12263. (if (not (eq action 'set))
  12264. (setq new action)
  12265. (message "Priority %c-%c, SPC to remove: "
  12266. org-highest-priority org-lowest-priority)
  12267. (save-match-data
  12268. (setq new (read-char-exclusive))))
  12269. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12270. (= (upcase org-lowest-priority) org-lowest-priority))
  12271. (setq new (upcase new)))
  12272. (cond ((equal new ?\s) (setq remove t))
  12273. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12274. (user-error "Priority must be between `%c' and `%c'"
  12275. org-highest-priority org-lowest-priority))))
  12276. ((eq action 'up)
  12277. (setq new (if have
  12278. (1- current) ; normal cycling
  12279. ;; last priority was empty
  12280. (if (eq last-command this-command)
  12281. org-lowest-priority ; wrap around empty to lowest
  12282. ;; default
  12283. (if org-priority-start-cycle-with-default
  12284. org-default-priority
  12285. (1- org-default-priority))))))
  12286. ((eq action 'down)
  12287. (setq new (if have
  12288. (1+ current) ; normal cycling
  12289. ;; last priority was empty
  12290. (if (eq last-command this-command)
  12291. org-highest-priority ; wrap around empty to highest
  12292. ;; default
  12293. (if org-priority-start-cycle-with-default
  12294. org-default-priority
  12295. (1+ org-default-priority))))))
  12296. (t (user-error "Invalid action")))
  12297. (when (or (< (upcase new) org-highest-priority)
  12298. (> (upcase new) org-lowest-priority))
  12299. (if (and (memq action '(up down))
  12300. (not have) (not (eq last-command this-command)))
  12301. ;; `new' is from default priority
  12302. (error
  12303. "The default can not be set, see `org-default-priority' why")
  12304. ;; normal cycling: `new' is beyond highest/lowest priority
  12305. ;; and is wrapped around to the empty priority
  12306. (setq remove t)))
  12307. (setq news (format "%c" new))
  12308. (if have
  12309. (if remove
  12310. (replace-match "" t t nil 1)
  12311. (replace-match news t t nil 2))
  12312. (if remove
  12313. (user-error "No priority cookie found in line")
  12314. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12315. (if (match-end 2)
  12316. (progn
  12317. (goto-char (match-end 2))
  12318. (insert " [#" news "]"))
  12319. (goto-char (match-beginning 3))
  12320. (insert "[#" news "] "))))
  12321. (org-align-tags))
  12322. (if remove
  12323. (message "Priority removed")
  12324. (message "Priority of current item set to %s" news)))))
  12325. (defun org-show-priority ()
  12326. "Show the priority of the current item.
  12327. This priority is composed of the main priority given with the [#A] cookies,
  12328. and by additional input from the age of a schedules or deadline entry."
  12329. (interactive)
  12330. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12331. (org-get-at-bol 'priority)
  12332. (save-excursion
  12333. (save-match-data
  12334. (beginning-of-line)
  12335. (and (looking-at org-heading-regexp)
  12336. (org-get-priority (match-string 0))))))))
  12337. (message "Priority is %d" (if pri pri -1000))))
  12338. (defun org-get-priority (s)
  12339. "Find priority cookie and return priority."
  12340. (save-match-data
  12341. (if (functionp org-get-priority-function)
  12342. (funcall org-get-priority-function)
  12343. (if (not (string-match org-priority-regexp s))
  12344. (* 1000 (- org-lowest-priority org-default-priority))
  12345. (* 1000 (- org-lowest-priority
  12346. (string-to-char (match-string 2 s))))))))
  12347. ;;;; Tags
  12348. (defvar org-agenda-archives-mode)
  12349. (defvar org-map-continue-from nil
  12350. "Position from where mapping should continue.
  12351. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12352. (defvar org-scanner-tags nil
  12353. "The current tag list while the tags scanner is running.")
  12354. (defvar org-trust-scanner-tags nil
  12355. "Should `org-get-tags' use the tags for the scanner.
  12356. This is for internal dynamical scoping only.
  12357. When this is non-nil, the function `org-get-tags' will return the value
  12358. of `org-scanner-tags' instead of building the list by itself. This
  12359. can lead to large speed-ups when the tags scanner is used in a file with
  12360. many entries, and when the list of tags is retrieved, for example to
  12361. obtain a list of properties. Building the tags list for each entry in such
  12362. a file becomes an N^2 operation - but with this variable set, it scales
  12363. as N.")
  12364. (defvar org--matcher-tags-todo-only nil)
  12365. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12366. "Scan headline tags with inheritance and produce output ACTION.
  12367. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12368. or `agenda' to produce an entry list for an agenda view. It can also be
  12369. a Lisp form or a function that should be called at each matched headline, in
  12370. this case the return value is a list of all return values from these calls.
  12371. MATCHER is a function accepting three arguments, returning
  12372. a non-nil value whenever a given set of tags qualifies a headline
  12373. for inclusion. See `org-make-tags-matcher' for more information.
  12374. As a special case, it can also be set to t (respectively nil) in
  12375. order to match all (respectively none) headline.
  12376. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  12377. included in the output.
  12378. START-LEVEL can be a string with asterisks, reducing the scope to
  12379. headlines matching this string."
  12380. (require 'org-agenda)
  12381. (let* ((re (concat "^"
  12382. (if start-level
  12383. ;; Get the correct level to match
  12384. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12385. org-outline-regexp)
  12386. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  12387. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  12388. (props (list 'face 'default
  12389. 'done-face 'org-agenda-done
  12390. 'undone-face 'default
  12391. 'mouse-face 'highlight
  12392. 'org-not-done-regexp org-not-done-regexp
  12393. 'org-todo-regexp org-todo-regexp
  12394. 'org-complex-heading-regexp org-complex-heading-regexp
  12395. 'help-echo
  12396. (format "mouse-2 or RET jump to Org file %S"
  12397. (abbreviate-file-name
  12398. (or (buffer-file-name (buffer-base-buffer))
  12399. (buffer-name (buffer-base-buffer)))))))
  12400. (org-map-continue-from nil)
  12401. lspos tags tags-list
  12402. (tags-alist (list (cons 0 org-file-tags)))
  12403. (llast 0) rtn rtn1 level category i txt
  12404. todo marker entry priority
  12405. ts-date ts-date-type ts-date-pair)
  12406. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12407. (setq action (list 'lambda nil action)))
  12408. (save-excursion
  12409. (goto-char (point-min))
  12410. (when (eq action 'sparse-tree)
  12411. (org-overview)
  12412. (org-remove-occur-highlights))
  12413. (while (let (case-fold-search)
  12414. (re-search-forward re nil t))
  12415. (setq org-map-continue-from nil)
  12416. (catch :skip
  12417. ;; Ignore closing parts of inline tasks.
  12418. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  12419. (throw :skip t))
  12420. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  12421. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  12422. (goto-char (setq lspos (match-beginning 0)))
  12423. (setq level (org-reduced-level (org-outline-level))
  12424. category (org-get-category))
  12425. (when (eq action 'agenda)
  12426. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12427. ts-date (car ts-date-pair)
  12428. ts-date-type (cdr ts-date-pair)))
  12429. (setq i llast llast level)
  12430. ;; remove tag lists from same and sublevels
  12431. (while (>= i level)
  12432. (when (setq entry (assoc i tags-alist))
  12433. (setq tags-alist (delete entry tags-alist)))
  12434. (setq i (1- i)))
  12435. ;; add the next tags
  12436. (when tags
  12437. (setq tags (org-split-string tags ":")
  12438. tags-alist
  12439. (cons (cons level tags) tags-alist)))
  12440. ;; compile tags for current headline
  12441. (setq tags-list
  12442. (if org-use-tag-inheritance
  12443. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12444. tags)
  12445. org-scanner-tags tags-list)
  12446. (when org-use-tag-inheritance
  12447. (setcdr (car tags-alist)
  12448. (mapcar (lambda (x)
  12449. (setq x (copy-sequence x))
  12450. (org-add-prop-inherited x))
  12451. (cdar tags-alist))))
  12452. (when (and tags org-use-tag-inheritance
  12453. (or (not (eq t org-use-tag-inheritance))
  12454. org-tags-exclude-from-inheritance))
  12455. ;; Selective inheritance, remove uninherited ones.
  12456. (setcdr (car tags-alist)
  12457. (org-remove-uninherited-tags (cdar tags-alist))))
  12458. (when (and
  12459. ;; eval matcher only when the todo condition is OK
  12460. (and (or (not todo-only) (member todo org-todo-keywords-1))
  12461. (if (functionp matcher)
  12462. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12463. (funcall matcher todo tags-list level))
  12464. matcher))
  12465. ;; Call the skipper, but return t if it does not
  12466. ;; skip, so that the `and' form continues evaluating.
  12467. (progn
  12468. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12469. t)
  12470. ;; Check if timestamps are deselecting this entry
  12471. (or (not todo-only)
  12472. (and (member todo org-todo-keywords-1)
  12473. (or (not org-agenda-tags-todo-honor-ignore-options)
  12474. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12475. ;; select this headline
  12476. (cond
  12477. ((eq action 'sparse-tree)
  12478. (and org-highlight-sparse-tree-matches
  12479. (org-get-heading) (match-end 0)
  12480. (org-highlight-new-match
  12481. (match-beginning 1) (match-end 1)))
  12482. (org-show-context 'tags-tree))
  12483. ((eq action 'agenda)
  12484. (setq txt (org-agenda-format-item
  12485. ""
  12486. (concat
  12487. (if (eq org-tags-match-list-sublevels 'indented)
  12488. (make-string (1- level) ?.) "")
  12489. (org-get-heading))
  12490. (make-string level ?\s)
  12491. category
  12492. tags-list)
  12493. priority (org-get-priority txt))
  12494. (goto-char lspos)
  12495. (setq marker (org-agenda-new-marker))
  12496. (org-add-props txt props
  12497. 'org-marker marker 'org-hd-marker marker 'org-category category
  12498. 'todo-state todo
  12499. 'ts-date ts-date
  12500. 'priority priority
  12501. 'type (concat "tagsmatch" ts-date-type))
  12502. (push txt rtn))
  12503. ((functionp action)
  12504. (setq org-map-continue-from nil)
  12505. (save-excursion
  12506. (setq rtn1 (funcall action))
  12507. (push rtn1 rtn)))
  12508. (t (user-error "Invalid action")))
  12509. ;; if we are to skip sublevels, jump to end of subtree
  12510. (unless org-tags-match-list-sublevels
  12511. (org-end-of-subtree t)
  12512. (backward-char 1))))
  12513. ;; Get the correct position from where to continue
  12514. (if org-map-continue-from
  12515. (goto-char org-map-continue-from)
  12516. (and (= (point) lspos) (end-of-line 1)))))
  12517. (when (and (eq action 'sparse-tree)
  12518. (not org-sparse-tree-open-archived-trees))
  12519. (org-hide-archived-subtrees (point-min) (point-max)))
  12520. (nreverse rtn)))
  12521. (defun org-remove-uninherited-tags (tags)
  12522. "Remove all tags that are not inherited from the list TAGS."
  12523. (cond
  12524. ((eq org-use-tag-inheritance t)
  12525. (if org-tags-exclude-from-inheritance
  12526. (org-delete-all org-tags-exclude-from-inheritance tags)
  12527. tags))
  12528. ((not org-use-tag-inheritance) nil)
  12529. ((stringp org-use-tag-inheritance)
  12530. (delq nil (mapcar
  12531. (lambda (x)
  12532. (if (and (string-match org-use-tag-inheritance x)
  12533. (not (member x org-tags-exclude-from-inheritance)))
  12534. x nil))
  12535. tags)))
  12536. ((listp org-use-tag-inheritance)
  12537. (delq nil (mapcar
  12538. (lambda (x)
  12539. (if (member x org-use-tag-inheritance) x nil))
  12540. tags)))))
  12541. (defun org-match-sparse-tree (&optional todo-only match)
  12542. "Create a sparse tree according to tags string MATCH.
  12543. MATCH is a string with match syntax. It can contain a selection
  12544. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12545. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12546. those. See the manual for details.
  12547. If optional argument TODO-ONLY is non-nil, only select lines that
  12548. are also TODO tasks."
  12549. (interactive "P")
  12550. (org-agenda-prepare-buffers (list (current-buffer)))
  12551. (let ((org--matcher-tags-todo-only todo-only))
  12552. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12553. org--matcher-tags-todo-only)))
  12554. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12555. (defvar org-cached-props nil)
  12556. (defun org-cached-entry-get (pom property)
  12557. (if (or (eq t org-use-property-inheritance)
  12558. (and (stringp org-use-property-inheritance)
  12559. (let ((case-fold-search t))
  12560. (string-match-p org-use-property-inheritance property)))
  12561. (and (listp org-use-property-inheritance)
  12562. (member-ignore-case property org-use-property-inheritance)))
  12563. ;; Caching is not possible, check it directly.
  12564. (org-entry-get pom property 'inherit)
  12565. ;; Get all properties, so we can do complicated checks easily.
  12566. (cdr (assoc-string property
  12567. (or org-cached-props
  12568. (setq org-cached-props (org-entry-properties pom)))
  12569. t))))
  12570. (defun org-global-tags-completion-table (&optional files)
  12571. "Return the list of all tags in all agenda buffer/files.
  12572. Optional FILES argument is a list of files which can be used
  12573. instead of the agenda files."
  12574. (save-excursion
  12575. (org-uniquify
  12576. (delq nil
  12577. (apply #'append
  12578. (mapcar
  12579. (lambda (file)
  12580. (set-buffer (find-file-noselect file))
  12581. (org--tag-add-to-alist
  12582. (org-get-buffer-tags)
  12583. (mapcar (lambda (x)
  12584. (and (stringp (car-safe x))
  12585. (list (car-safe x))))
  12586. org-current-tag-alist)))
  12587. (if (car-safe files) files
  12588. (org-agenda-files))))))))
  12589. (defun org-make-tags-matcher (match)
  12590. "Create the TAGS/TODO matcher form for the selection string MATCH.
  12591. Returns a cons of the selection string MATCH and a function
  12592. implementing the matcher.
  12593. The matcher is to be called at an Org entry, with point on the
  12594. headline, and returns non-nil if the entry matches the selection
  12595. string MATCH. It must be called with three arguments: the TODO
  12596. keyword at the entry (or nil if none), the list of all tags at
  12597. the entry including inherited ones and the reduced level of the
  12598. headline. Additionally, the category of the entry, if any, must
  12599. be specified as the text property `org-category' on the headline.
  12600. This function sets the variable `org--matcher-tags-todo-only' to
  12601. a non-nil value if the matcher restricts matching to TODO
  12602. entries, otherwise it is not touched.
  12603. See also `org-scan-tags'."
  12604. (unless match
  12605. ;; Get a new match request, with completion against the global
  12606. ;; tags table and the local tags in current buffer.
  12607. (let ((org-last-tags-completion-table
  12608. (org--tag-add-to-alist
  12609. (org-get-buffer-tags)
  12610. (org-global-tags-completion-table))))
  12611. (setq match
  12612. (completing-read
  12613. "Match: "
  12614. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  12615. (let ((match0 match)
  12616. (re (concat
  12617. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  12618. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  12619. "\\([<>=]\\{1,2\\}\\)"
  12620. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  12621. "\\|" org-tag-re "\\)"))
  12622. (start 0)
  12623. tagsmatch todomatch tagsmatcher todomatcher)
  12624. ;; Expand group tags.
  12625. (setq match (org-tags-expand match))
  12626. ;; Check if there is a TODO part of this match, which would be the
  12627. ;; part after a "/". To make sure that this slash is not part of
  12628. ;; a property value to be matched against, we also check that
  12629. ;; there is no / after that slash. First, find the last slash.
  12630. (let ((s 0))
  12631. (while (string-match "/+" match s)
  12632. (setq start (match-beginning 0))
  12633. (setq s (match-end 0))))
  12634. (if (and (string-match "/+" match start)
  12635. (not (string-match-p "\"" match start)))
  12636. ;; Match contains also a TODO-matching request.
  12637. (progn
  12638. (setq tagsmatch (substring match 0 (match-beginning 0)))
  12639. (setq todomatch (substring match (match-end 0)))
  12640. (when (string-prefix-p "!" todomatch)
  12641. (setq org--matcher-tags-todo-only t)
  12642. (setq todomatch (substring todomatch 1)))
  12643. (when (string-match "\\`\\s-*\\'" todomatch)
  12644. (setq todomatch nil)))
  12645. ;; Only matching tags.
  12646. (setq tagsmatch match)
  12647. (setq todomatch nil))
  12648. ;; Make the tags matcher.
  12649. (when (org-string-nw-p tagsmatch)
  12650. (let ((orlist nil)
  12651. (orterms (org-split-string tagsmatch "|"))
  12652. term)
  12653. (while (setq term (pop orterms))
  12654. (while (and (equal (substring term -1) "\\") orterms)
  12655. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  12656. (while (string-match re term)
  12657. (let* ((rest (substring term (match-end 0)))
  12658. (minus (and (match-end 1)
  12659. (equal (match-string 1 term) "-")))
  12660. (tag (save-match-data
  12661. (replace-regexp-in-string
  12662. "\\\\-" "-" (match-string 2 term))))
  12663. (regexp (eq (string-to-char tag) ?{))
  12664. (levelp (match-end 4))
  12665. (propp (match-end 5))
  12666. (mm
  12667. (cond
  12668. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  12669. (levelp
  12670. `(,(org-op-to-function (match-string 3 term))
  12671. level
  12672. ,(string-to-number (match-string 4 term))))
  12673. (propp
  12674. (let* ((gv (pcase (upcase (match-string 5 term))
  12675. ("CATEGORY"
  12676. '(get-text-property (point) 'org-category))
  12677. ("TODO" 'todo)
  12678. (p `(org-cached-entry-get nil ,p))))
  12679. (pv (match-string 7 term))
  12680. (regexp (eq (string-to-char pv) ?{))
  12681. (strp (eq (string-to-char pv) ?\"))
  12682. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  12683. (po (org-op-to-function (match-string 6 term)
  12684. (if timep 'time strp))))
  12685. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  12686. (when timep (setq pv (org-matcher-time pv)))
  12687. (cond ((and regexp (eq po '/=))
  12688. `(not (string-match ,pv (or ,gv ""))))
  12689. (regexp `(string-match ,pv (or ,gv "")))
  12690. (strp `(,po (or ,gv "") ,pv))
  12691. (t
  12692. `(,po
  12693. (string-to-number (or ,gv ""))
  12694. ,(string-to-number pv))))))
  12695. (t `(member ,tag tags-list)))))
  12696. (push (if minus `(not ,mm) mm) tagsmatcher)
  12697. (setq term rest)))
  12698. (push `(and ,@tagsmatcher) orlist)
  12699. (setq tagsmatcher nil))
  12700. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  12701. ;; Make the TODO matcher.
  12702. (when (org-string-nw-p todomatch)
  12703. (let ((orlist nil))
  12704. (dolist (term (org-split-string todomatch "|"))
  12705. (while (string-match re term)
  12706. (let* ((minus (and (match-end 1)
  12707. (equal (match-string 1 term) "-")))
  12708. (kwd (match-string 2 term))
  12709. (regexp (eq (string-to-char kwd) ?{))
  12710. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  12711. `(equal todo ,kwd))))
  12712. (push (if minus `(not ,mm) mm) todomatcher))
  12713. (setq term (substring term (match-end 0))))
  12714. (push (if (> (length todomatcher) 1)
  12715. (cons 'and todomatcher)
  12716. (car todomatcher))
  12717. orlist)
  12718. (setq todomatcher nil))
  12719. (setq todomatcher (cons 'or orlist))))
  12720. ;; Return the string and function of the matcher. If no
  12721. ;; tags-specific or todo-specific matcher exists, match
  12722. ;; everything.
  12723. (let ((matcher (if (and tagsmatcher todomatcher)
  12724. `(and ,tagsmatcher ,todomatcher)
  12725. (or tagsmatcher todomatcher t))))
  12726. (when org--matcher-tags-todo-only
  12727. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  12728. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  12729. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  12730. "Expand group tags in MATCH.
  12731. This replaces every group tag in MATCH with a regexp tag search.
  12732. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  12733. will be replaced like this:
  12734. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12735. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12736. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12737. Replacing by a regexp preserves the structure of the match.
  12738. E.g., this expansion
  12739. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  12740. will match anything tagged with \"Lab\" and \"Home\", or tagged
  12741. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  12742. A group tag in MATCH can contain regular expressions of its own.
  12743. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  12744. will be replaced like this:
  12745. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  12746. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  12747. assumed to be a single group tag, and the function will return
  12748. the list of tags in this group.
  12749. When DOWNCASE is non-nil, expand downcased TAGS."
  12750. (if org-group-tags
  12751. (let* ((case-fold-search t)
  12752. (stable org-mode-syntax-table)
  12753. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  12754. (taggroups (if downcased
  12755. (mapcar (lambda (tg) (mapcar #'downcase tg))
  12756. taggroups)
  12757. taggroups))
  12758. (taggroups-keys (mapcar #'car taggroups))
  12759. (return-match (if downcased (downcase match) match))
  12760. (count 0)
  12761. (work-already-expanded tags-already-expanded)
  12762. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  12763. ;; @ and _ are allowed as word-components in tags.
  12764. (modify-syntax-entry ?@ "w" stable)
  12765. (modify-syntax-entry ?_ "w" stable)
  12766. ;; Temporarily replace regexp-expressions in the match-expression.
  12767. (while (string-match "{.+?}" return-match)
  12768. (cl-incf count)
  12769. (push (match-string 0 return-match) regexps-in-match)
  12770. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  12771. (while (and taggroups-keys
  12772. (with-syntax-table stable
  12773. (string-match
  12774. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  12775. (regexp-opt taggroups-keys) "\\>\\)")
  12776. return-match)))
  12777. (let* ((dir (match-string 1 return-match))
  12778. (tag (match-string 2 return-match))
  12779. (tag (if downcased (downcase tag) tag)))
  12780. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  12781. (member tag tags-already-expanded))
  12782. (setq tags-in-group (assoc tag taggroups))
  12783. (push tag work-already-expanded)
  12784. ;; Recursively expand each tag in the group, if the tag hasn't
  12785. ;; already been expanded. Restore the match-data after all recursive calls.
  12786. (save-match-data
  12787. (let (tags-expanded)
  12788. (dolist (x (cdr tags-in-group))
  12789. (if (and (member x taggroups-keys)
  12790. (not (member x work-already-expanded)))
  12791. (setq tags-expanded
  12792. (delete-dups
  12793. (append
  12794. (org-tags-expand x t downcased
  12795. work-already-expanded)
  12796. tags-expanded)))
  12797. (setq tags-expanded
  12798. (append (list x) tags-expanded)))
  12799. (setq work-already-expanded
  12800. (delete-dups
  12801. (append tags-expanded
  12802. work-already-expanded))))
  12803. (setq tags-in-group
  12804. (delete-dups (cons (car tags-in-group)
  12805. tags-expanded)))))
  12806. ;; Filter tag-regexps from tags.
  12807. (setq regexp-in-group-escaped
  12808. (delq nil (mapcar (lambda (x)
  12809. (if (stringp x)
  12810. (and (equal "{" (substring x 0 1))
  12811. (equal "}" (substring x -1))
  12812. x)
  12813. x))
  12814. tags-in-group))
  12815. regexp-in-group
  12816. (mapcar (lambda (x)
  12817. (substring x 1 -1))
  12818. regexp-in-group-escaped)
  12819. tags-in-group
  12820. (delq nil (mapcar (lambda (x)
  12821. (if (stringp x)
  12822. (and (not (equal "{" (substring x 0 1)))
  12823. (not (equal "}" (substring x -1)))
  12824. x)
  12825. x))
  12826. tags-in-group)))
  12827. ;; If single-as-list, do no more in the while-loop.
  12828. (if (not single-as-list)
  12829. (progn
  12830. (when regexp-in-group
  12831. (setq regexp-in-group
  12832. (concat "\\|"
  12833. (mapconcat 'identity regexp-in-group
  12834. "\\|"))))
  12835. (setq tags-in-group
  12836. (concat dir
  12837. "{\\<"
  12838. (regexp-opt tags-in-group)
  12839. "\\>"
  12840. regexp-in-group
  12841. "}"))
  12842. (when (stringp tags-in-group)
  12843. (org-add-props tags-in-group '(grouptag t)))
  12844. (setq return-match
  12845. (replace-match tags-in-group t t return-match)))
  12846. (setq tags-in-group
  12847. (append regexp-in-group-escaped tags-in-group))))
  12848. (setq taggroups-keys (delete tag taggroups-keys))))
  12849. ;; Add the regular expressions back into the match-expression again.
  12850. (while regexps-in-match
  12851. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  12852. (pop regexps-in-match)
  12853. return-match t t))
  12854. (cl-decf count))
  12855. (if single-as-list
  12856. (if tags-in-group tags-in-group (list return-match))
  12857. return-match))
  12858. (if single-as-list
  12859. (list (if downcased (downcase match) match))
  12860. match)))
  12861. (defun org-op-to-function (op &optional stringp)
  12862. "Turn an operator into the appropriate function."
  12863. (setq op
  12864. (cond
  12865. ((equal op "<" ) '(< org-string< org-time<))
  12866. ((equal op ">" ) '(> org-string> org-time>))
  12867. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  12868. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  12869. ((member op '("=" "==")) '(= string= org-time=))
  12870. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  12871. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  12872. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  12873. (defvar org-tags-overlay (make-overlay 1 1))
  12874. (delete-overlay org-tags-overlay)
  12875. (defun org-add-prop-inherited (s)
  12876. (add-text-properties 0 (length s) '(inherited t) s)
  12877. s)
  12878. (defun org-toggle-tag (tag &optional onoff)
  12879. "Toggle the tag TAG for the current line.
  12880. If ONOFF is `on' or `off', don't toggle but set to this state."
  12881. (save-excursion
  12882. (org-back-to-heading t)
  12883. (let ((current
  12884. ;; Reverse the tags list so any new tag is appended to the
  12885. ;; current list of tags.
  12886. (nreverse (org-get-tags nil t)))
  12887. res)
  12888. (pcase onoff
  12889. (`off (setq current (delete tag current)))
  12890. ((or `on (guard (not (member tag current))))
  12891. (setq res t)
  12892. (cl-pushnew tag current :test #'equal))
  12893. (_ (setq current (delete tag current))))
  12894. (org-set-tags (nreverse current))
  12895. res)))
  12896. (defun org--align-tags-here (to-col)
  12897. "Align tags on the current headline to TO-COL.
  12898. Assume point is on a headline. Preserve point when aligning
  12899. tags."
  12900. (when (and (org-match-line org-tag-line-re)
  12901. (/= to-col (save-excursion ;nothing to do?
  12902. (goto-char (match-beginning 1)) (current-column))))
  12903. (let* ((shift (if (>= to-col 0) to-col
  12904. (- (abs to-col) (string-width (match-string 1)))))
  12905. (origin (point-marker))
  12906. (column (current-column))
  12907. (tags-start (match-beginning 1))
  12908. (blank-start (save-excursion
  12909. (goto-char tags-start)
  12910. (skip-chars-backward " \t")
  12911. (point)))
  12912. (in-blank? (and (> origin blank-start)
  12913. (<= origin tags-start))))
  12914. (delete-region blank-start tags-start)
  12915. (goto-char blank-start)
  12916. (let ((indent-tabs-mode nil)) (indent-to shift 1))
  12917. ;; Try to move back to original position. If point was in the
  12918. ;; blanks before the tags, ORIGIN marker is of no use because it
  12919. ;; now points to BLANK-START. Use COLUMN instead.
  12920. (if in-blank? (org-move-to-column column)
  12921. (goto-char origin)))))
  12922. (defun org-set-tags-command (&optional arg)
  12923. "Set the tags for the current visible entry.
  12924. When called with `\\[universal-argument]' prefix argument ARG, \
  12925. realign all tags
  12926. in the current buffer. If a region is active, set tags for
  12927. all headlines in the region.
  12928. This function is for interactive use only;
  12929. in Lisp code use `org-set-tags' instead."
  12930. (interactive "P")
  12931. (cond
  12932. (arg (org-align-tags t))
  12933. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12934. ;; Disable `org-loop-over-headlines-in-active-region' for
  12935. ;; successive calls.
  12936. (let (org-loop-over-headlines-in-active-region)
  12937. (org-map-entries
  12938. #'org-set-tags-command
  12939. nil
  12940. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12941. 'region-start-level
  12942. 'region)
  12943. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  12944. (t
  12945. (save-excursion
  12946. (org-back-to-heading)
  12947. (let* ((all-tags (org-get-tags))
  12948. (table (setq org-last-tags-completion-table
  12949. (org--tag-add-to-alist
  12950. (and org-complete-tags-always-offer-all-agenda-tags
  12951. (org-global-tags-completion-table
  12952. (org-agenda-files)))
  12953. (or org-current-tag-alist (org-get-buffer-tags)))))
  12954. (current-tags
  12955. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  12956. all-tags))
  12957. (inherited-tags
  12958. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  12959. all-tags))
  12960. (tags
  12961. (replace-regexp-in-string
  12962. ;; Ignore all forbidden characters in tags.
  12963. "[^[:alnum:]_@#%]+" ":"
  12964. (if (or (eq t org-use-fast-tag-selection)
  12965. (and org-use-fast-tag-selection
  12966. (delq nil (mapcar #'cdr table))))
  12967. (org-fast-tag-selection
  12968. current-tags
  12969. inherited-tags
  12970. table
  12971. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  12972. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  12973. (org-trim (completing-read
  12974. "Tags: "
  12975. #'org-tags-completion-function
  12976. nil nil (org-make-tag-string current-tags)
  12977. 'org-tags-history)))))))
  12978. (org-set-tags tags))))))
  12979. (defun org-align-tags (&optional all)
  12980. "Align tags in current entry.
  12981. When optional argument ALL is non-nil, align all tags in the
  12982. visible part of the buffer."
  12983. (let ((get-indent-column
  12984. (lambda ()
  12985. (let ((offset (if (bound-and-true-p org-indent-mode)
  12986. (* (1- org-indent-indentation-per-level)
  12987. (1- (org-current-level)))
  12988. 0)))
  12989. (+ org-tags-column
  12990. (if (> org-tags-column 0) (- offset) offset))))))
  12991. (if (and (not all) (org-at-heading-p))
  12992. (org--align-tags-here (funcall get-indent-column))
  12993. (save-excursion
  12994. (if all
  12995. (while (re-search-forward org-tag-line-re nil t)
  12996. (org--align-tags-here (funcall get-indent-column)))
  12997. (org-back-to-heading t)
  12998. (org--align-tags-here (funcall get-indent-column)))))))
  12999. (defun org-set-tags (tags)
  13000. "Set the tags of the current entry to TAGS, replacing current tags.
  13001. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  13002. If TAGS is nil or the empty string, all tags are removed.
  13003. This function assumes point is on a headline."
  13004. (org-with-wide-buffer
  13005. (let ((tags (pcase tags
  13006. ((pred listp) tags)
  13007. ((pred stringp) (split-string (org-trim tags) ":" t))
  13008. (_ (error "Invalid tag specification: %S" tags))))
  13009. (old-tags (org-get-tags nil t))
  13010. (change-flag nil))
  13011. (when (functionp org-tags-sort-function)
  13012. (setq tags (sort tags org-tags-sort-function)))
  13013. (unless (equal tags old-tags) (setq change-flag t))
  13014. ;; Delete previous tags and any trailing white space.
  13015. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  13016. (line-end-position)))
  13017. (skip-chars-backward " \t")
  13018. (delete-region (point) (line-end-position))
  13019. ;; Deleting white spaces may break an otherwise empty headline.
  13020. ;; Re-introduce one space in this case.
  13021. (unless (org-at-heading-p) (insert " "))
  13022. (when tags
  13023. (save-excursion (insert " " (org-make-tag-string tags)))
  13024. ;; When text is being inserted on an invisible region
  13025. ;; boundary, it can be inadvertently sucked into
  13026. ;; invisibility.
  13027. (unless (org-invisible-p (line-beginning-position))
  13028. (org-flag-region (point) (line-end-position) nil 'outline)))
  13029. ;; Align tags, if any.
  13030. (when tags (org-align-tags))
  13031. (when change-flag (run-hooks 'org-after-tags-change-hook)))))
  13032. (defun org-change-tag-in-region (beg end tag off)
  13033. "Add or remove TAG for each entry in the region.
  13034. This works in the agenda, and also in an Org buffer."
  13035. (interactive
  13036. (list (region-beginning) (region-end)
  13037. (let ((org-last-tags-completion-table
  13038. (if (derived-mode-p 'org-mode)
  13039. (org--tag-add-to-alist
  13040. (org-get-buffer-tags)
  13041. (org-global-tags-completion-table))
  13042. (org-global-tags-completion-table))))
  13043. (completing-read
  13044. "Tag: " 'org-tags-completion-function nil nil nil
  13045. 'org-tags-history))
  13046. (progn
  13047. (message "[s]et or [r]emove? ")
  13048. (equal (read-char-exclusive) ?r))))
  13049. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13050. (let ((agendap (equal major-mode 'org-agenda-mode))
  13051. l1 l2 m buf pos newhead (cnt 0))
  13052. (goto-char end)
  13053. (setq l2 (1- (org-current-line)))
  13054. (goto-char beg)
  13055. (setq l1 (org-current-line))
  13056. (cl-loop for l from l1 to l2 do
  13057. (org-goto-line l)
  13058. (setq m (get-text-property (point) 'org-hd-marker))
  13059. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13060. (and agendap m))
  13061. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13062. pos (if agendap m (point)))
  13063. (with-current-buffer buf
  13064. (save-excursion
  13065. (save-restriction
  13066. (goto-char pos)
  13067. (setq cnt (1+ cnt))
  13068. (org-toggle-tag tag (if off 'off 'on))
  13069. (setq newhead (org-get-heading)))))
  13070. (and agendap (org-agenda-change-all-lines newhead m))))
  13071. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13072. (defun org-tags-completion-function (string _predicate &optional flag)
  13073. "Complete tag STRING.
  13074. FLAG specifies the type of completion operation to perform. This
  13075. function is passed as a collection function to `completing-read',
  13076. which see."
  13077. (let ((completion-ignore-case nil) ;tags are case-sensitive
  13078. (confirm (lambda (x) (stringp (car x))))
  13079. (prefix ""))
  13080. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13081. (setq prefix (match-string 1 string))
  13082. (setq string (match-string 2 string)))
  13083. (pcase flag
  13084. (`t (all-completions string org-last-tags-completion-table confirm))
  13085. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  13086. (`nil
  13087. (pcase (try-completion string org-last-tags-completion-table confirm)
  13088. ((and completion (pred stringp))
  13089. (concat prefix
  13090. completion
  13091. (if (and org-add-colon-after-tag-completion
  13092. (assoc completion org-last-tags-completion-table))
  13093. ":"
  13094. "")))
  13095. (completion completion)))
  13096. (_ nil))))
  13097. (defun org-fast-tag-insert (kwd tags face &optional end)
  13098. "Insert KWD, and the TAGS, the latter with face FACE.
  13099. Also insert END."
  13100. (insert (format "%-12s" (concat kwd ":"))
  13101. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13102. (or end "")))
  13103. (defun org-fast-tag-show-exit (flag)
  13104. (save-excursion
  13105. (org-goto-line 3)
  13106. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13107. (replace-match ""))
  13108. (when flag
  13109. (end-of-line 1)
  13110. (org-move-to-column (- (window-width) 19) t)
  13111. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13112. (defun org-set-current-tags-overlay (current prefix)
  13113. "Add an overlay to CURRENT tag with PREFIX."
  13114. (let ((s (org-make-tag-string current)))
  13115. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13116. (org-overlay-display org-tags-overlay (concat prefix s))))
  13117. (defvar org-last-tag-selection-key nil)
  13118. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13119. "Fast tag selection with single keys.
  13120. CURRENT is the current list of tags in the headline, INHERITED is the
  13121. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13122. possibly with grouping information. TODO-TABLE is a similar table with
  13123. TODO keywords, should these have keys assigned to them.
  13124. If the keys are nil, a-z are automatically assigned.
  13125. Returns the new tags string, or nil to not change the current settings."
  13126. (let* ((fulltable (append table todo-table))
  13127. (maxlen (if (null fulltable) 0
  13128. (apply #'max
  13129. (mapcar (lambda (x)
  13130. (if (stringp (car x)) (string-width (car x))
  13131. 0))
  13132. fulltable))))
  13133. (buf (current-buffer))
  13134. (expert (eq org-fast-tag-selection-single-key 'expert))
  13135. (buffer-tags nil)
  13136. (fwidth (+ maxlen 3 1 3))
  13137. (ncol (/ (- (window-width) 4) fwidth))
  13138. (i-face 'org-done)
  13139. (c-face 'org-todo)
  13140. tg cnt e c char c1 c2 ntable tbl rtn
  13141. ov-start ov-end ov-prefix
  13142. (exit-after-next org-fast-tag-selection-single-key)
  13143. (done-keywords org-done-keywords)
  13144. groups ingroup intaggroup)
  13145. (save-excursion
  13146. (beginning-of-line)
  13147. (if (looking-at org-tag-line-re)
  13148. (setq ov-start (match-beginning 1)
  13149. ov-end (match-end 1)
  13150. ov-prefix "")
  13151. (setq ov-start (1- (point-at-eol))
  13152. ov-end (1+ ov-start))
  13153. (skip-chars-forward "^\n\r")
  13154. (setq ov-prefix
  13155. (concat
  13156. (buffer-substring (1- (point)) (point))
  13157. (if (> (current-column) org-tags-column)
  13158. " "
  13159. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13160. (move-overlay org-tags-overlay ov-start ov-end)
  13161. (save-window-excursion
  13162. (if expert
  13163. (set-buffer (get-buffer-create " *Org tags*"))
  13164. (delete-other-windows)
  13165. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13166. (org-switch-to-buffer-other-window " *Org tags*"))
  13167. (erase-buffer)
  13168. (setq-local org-done-keywords done-keywords)
  13169. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13170. (org-fast-tag-insert "Current" current c-face "\n\n")
  13171. (org-fast-tag-show-exit exit-after-next)
  13172. (org-set-current-tags-overlay current ov-prefix)
  13173. (setq tbl fulltable char ?a cnt 0)
  13174. (while (setq e (pop tbl))
  13175. (cond
  13176. ((eq (car e) :startgroup)
  13177. (push '() groups) (setq ingroup t)
  13178. (unless (zerop cnt)
  13179. (setq cnt 0)
  13180. (insert "\n"))
  13181. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13182. ((eq (car e) :endgroup)
  13183. (setq ingroup nil cnt 0)
  13184. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13185. ((eq (car e) :startgrouptag)
  13186. (setq intaggroup t)
  13187. (unless (zerop cnt)
  13188. (setq cnt 0)
  13189. (insert "\n"))
  13190. (insert "[ "))
  13191. ((eq (car e) :endgrouptag)
  13192. (setq intaggroup nil cnt 0)
  13193. (insert "]\n"))
  13194. ((equal e '(:newline))
  13195. (unless (zerop cnt)
  13196. (setq cnt 0)
  13197. (insert "\n")
  13198. (setq e (car tbl))
  13199. (while (equal (car tbl) '(:newline))
  13200. (insert "\n")
  13201. (setq tbl (cdr tbl)))))
  13202. ((equal e '(:grouptags)) (insert " : "))
  13203. (t
  13204. (setq tg (copy-sequence (car e)) c2 nil)
  13205. (if (cdr e)
  13206. (setq c (cdr e))
  13207. ;; automatically assign a character.
  13208. (setq c1 (string-to-char
  13209. (downcase (substring
  13210. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13211. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13212. (while (or (rassoc char ntable) (rassoc char table))
  13213. (setq char (1+ char)))
  13214. (setq c2 c1))
  13215. (setq c (or c2 char)))
  13216. (when ingroup (push tg (car groups)))
  13217. (setq tg (org-add-props tg nil 'face
  13218. (cond
  13219. ((not (assoc tg table))
  13220. (org-get-todo-face tg))
  13221. ((member tg current) c-face)
  13222. ((member tg inherited) i-face))))
  13223. (when (equal (caar tbl) :grouptags)
  13224. (org-add-props tg nil 'face 'org-tag-group))
  13225. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13226. (insert "[" c "] " tg (make-string
  13227. (- fwidth 4 (length tg)) ?\ ))
  13228. (push (cons tg c) ntable)
  13229. (when (= (cl-incf cnt) ncol)
  13230. (insert "\n")
  13231. (when (or ingroup intaggroup) (insert " "))
  13232. (setq cnt 0)))))
  13233. (setq ntable (nreverse ntable))
  13234. (insert "\n")
  13235. (goto-char (point-min))
  13236. (unless expert (org-fit-window-to-buffer))
  13237. (setq rtn
  13238. (catch 'exit
  13239. (while t
  13240. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  13241. (if (not groups) "no " "")
  13242. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13243. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13244. (setq org-last-tag-selection-key c)
  13245. (cond
  13246. ((= c ?\r) (throw 'exit t))
  13247. ((= c ?!)
  13248. (setq groups (not groups))
  13249. (goto-char (point-min))
  13250. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13251. ((= c ?\C-c)
  13252. (if (not expert)
  13253. (org-fast-tag-show-exit
  13254. (setq exit-after-next (not exit-after-next)))
  13255. (setq expert nil)
  13256. (delete-other-windows)
  13257. (set-window-buffer (split-window-vertically) " *Org tags*")
  13258. (org-switch-to-buffer-other-window " *Org tags*")
  13259. (org-fit-window-to-buffer)))
  13260. ((or (= c ?\C-g)
  13261. (and (= c ?q) (not (rassoc c ntable))))
  13262. (delete-overlay org-tags-overlay)
  13263. (setq quit-flag t))
  13264. ((= c ?\ )
  13265. (setq current nil)
  13266. (when exit-after-next (setq exit-after-next 'now)))
  13267. ((= c ?\t)
  13268. (condition-case nil
  13269. (setq tg (completing-read
  13270. "Tag: "
  13271. (or buffer-tags
  13272. (with-current-buffer buf
  13273. (setq buffer-tags
  13274. (org-get-buffer-tags))))))
  13275. (quit (setq tg "")))
  13276. (when (string-match "\\S-" tg)
  13277. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13278. (if (member tg current)
  13279. (setq current (delete tg current))
  13280. (push tg current)))
  13281. (when exit-after-next (setq exit-after-next 'now)))
  13282. ((setq e (rassoc c todo-table) tg (car e))
  13283. (with-current-buffer buf
  13284. (save-excursion (org-todo tg)))
  13285. (when exit-after-next (setq exit-after-next 'now)))
  13286. ((setq e (rassoc c ntable) tg (car e))
  13287. (if (member tg current)
  13288. (setq current (delete tg current))
  13289. (cl-loop for g in groups do
  13290. (when (member tg g)
  13291. (dolist (x g) (setq current (delete x current)))))
  13292. (push tg current))
  13293. (when exit-after-next (setq exit-after-next 'now))))
  13294. ;; Create a sorted list
  13295. (setq current
  13296. (sort current
  13297. (lambda (a b)
  13298. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13299. (when (eq exit-after-next 'now) (throw 'exit t))
  13300. (goto-char (point-min))
  13301. (beginning-of-line 2)
  13302. (delete-region (point) (point-at-eol))
  13303. (org-fast-tag-insert "Current" current c-face)
  13304. (org-set-current-tags-overlay current ov-prefix)
  13305. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  13306. (while (re-search-forward tag-re nil t)
  13307. (let ((tag (match-string 1)))
  13308. (add-text-properties
  13309. (match-beginning 1) (match-end 1)
  13310. (list 'face
  13311. (cond
  13312. ((member tag current) c-face)
  13313. ((member tag inherited) i-face)
  13314. (t (get-text-property (match-beginning 1) '
  13315. face))))))))
  13316. (goto-char (point-min)))))
  13317. (delete-overlay org-tags-overlay)
  13318. (if rtn
  13319. (mapconcat 'identity current ":")
  13320. nil))))
  13321. (defun org-make-tag-string (tags)
  13322. "Return string associated to TAGS.
  13323. TAGS is a list of strings."
  13324. (if (null tags) ""
  13325. (format ":%s:" (mapconcat #'identity tags ":"))))
  13326. (defun org--get-local-tags ()
  13327. "Return list of tags for the current headline.
  13328. Assume point is at the beginning of the headline."
  13329. (and (looking-at org-tag-line-re)
  13330. (split-string (match-string-no-properties 2) ":" t)))
  13331. (defun org-get-tags (&optional pos local)
  13332. "Get the list of tags specified in the current headline.
  13333. When argument POS is non-nil, retrieve tags for headline at POS.
  13334. Accoring to `org-use-tags-inheritance', tags may be inherited
  13335. from parent headlines, and from the whole document, through
  13336. `org-file-tags'. However, when optional argument LOCAL is
  13337. non-nil, only return tags really specified in the considered
  13338. headline.
  13339. Inherited tags have the `inherited' text property."
  13340. (if (and org-trust-scanner-tags
  13341. (or (not pos) (eq pos (point)))
  13342. (not local))
  13343. org-scanner-tags
  13344. (org-with-point-at (or pos (point))
  13345. (unless (org-before-first-heading-p)
  13346. (org-back-to-heading t)
  13347. (let ((tags (org--get-local-tags)))
  13348. (if (or local (not org-use-tag-inheritance)) tags
  13349. (while (org-up-heading-safe)
  13350. (setq tags (append (mapcar #'org-add-prop-inherited
  13351. (org--get-local-tags))
  13352. tags)))
  13353. (org-remove-uninherited-tags
  13354. (delete-dups (append org-file-tags tags)))))))))
  13355. (defun org-get-buffer-tags ()
  13356. "Get a table of all tags used in the buffer, for completion."
  13357. (org-with-point-at 1
  13358. (let (tags)
  13359. (while (re-search-forward org-tag-line-re nil t)
  13360. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  13361. tags)))
  13362. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  13363. ;;;; The mapping API
  13364. (defvar org-agenda-skip-comment-trees)
  13365. (defvar org-agenda-skip-function)
  13366. (defun org-map-entries (func &optional match scope &rest skip)
  13367. "Call FUNC at each headline selected by MATCH in SCOPE.
  13368. FUNC is a function or a lisp form. The function will be called without
  13369. arguments, with the cursor positioned at the beginning of the headline.
  13370. The return values of all calls to the function will be collected and
  13371. returned as a list.
  13372. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13373. does not need to preserve point. After evaluation, the cursor will be
  13374. moved to the end of the line (presumably of the headline of the
  13375. processed entry) and search continues from there. Under some
  13376. circumstances, this may not produce the wanted results. For example,
  13377. if you have removed (e.g. archived) the current (sub)tree it could
  13378. mean that the next entry will be skipped entirely. In such cases, you
  13379. can specify the position from where search should continue by making
  13380. FUNC set the variable `org-map-continue-from' to the desired buffer
  13381. position.
  13382. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13383. Only headlines that are matched by this query will be considered during
  13384. the iteration. When MATCH is nil or t, all headlines will be
  13385. visited by the iteration.
  13386. SCOPE determines the scope of this command. It can be any of:
  13387. nil The current buffer, respecting the restriction if any
  13388. tree The subtree started with the entry at point
  13389. region The entries within the active region, if any
  13390. region-start-level
  13391. The entries within the active region, but only those at
  13392. the same level than the first one.
  13393. file The current buffer, without restriction
  13394. file-with-archives
  13395. The current buffer, and any archives associated with it
  13396. agenda All agenda files
  13397. agenda-with-archives
  13398. All agenda files with any archive files associated with them
  13399. \(file1 file2 ...)
  13400. If this is a list, all files in the list will be scanned
  13401. The remaining args are treated as settings for the skipping facilities of
  13402. the scanner. The following items can be given here:
  13403. archive skip trees with the archive tag
  13404. comment skip trees with the COMMENT keyword
  13405. function or Emacs Lisp form:
  13406. will be used as value for `org-agenda-skip-function', so
  13407. whenever the function returns a position, FUNC will not be
  13408. called for that entry and search will continue from the
  13409. position returned
  13410. If your function needs to retrieve the tags including inherited tags
  13411. at the *current* entry, you can use the value of the variable
  13412. `org-scanner-tags' which will be much faster than getting the value
  13413. with `org-get-tags'. If your function gets properties with
  13414. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  13415. to t around the call to `org-entry-properties' to get the same speedup.
  13416. Note that if your function moves around to retrieve tags and properties at
  13417. a *different* entry, you cannot use these techniques."
  13418. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  13419. (not (org-region-active-p)))
  13420. (let* ((org-agenda-archives-mode nil) ; just to make sure
  13421. (org-agenda-skip-archived-trees (memq 'archive skip))
  13422. (org-agenda-skip-comment-trees (memq 'comment skip))
  13423. (org-agenda-skip-function
  13424. (car (org-delete-all '(comment archive) skip)))
  13425. (org-tags-match-list-sublevels t)
  13426. (start-level (eq scope 'region-start-level))
  13427. matcher res
  13428. org-todo-keywords-for-agenda
  13429. org-done-keywords-for-agenda
  13430. org-todo-keyword-alist-for-agenda
  13431. org-tag-alist-for-agenda
  13432. org--matcher-tags-todo-only)
  13433. (cond
  13434. ((eq match t) (setq matcher t))
  13435. ((eq match nil) (setq matcher t))
  13436. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  13437. (save-excursion
  13438. (save-restriction
  13439. (cond ((eq scope 'tree)
  13440. (org-back-to-heading t)
  13441. (org-narrow-to-subtree)
  13442. (setq scope nil))
  13443. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  13444. (org-region-active-p))
  13445. ;; If needed, set start-level to a string like "2"
  13446. (when start-level
  13447. (save-excursion
  13448. (goto-char (region-beginning))
  13449. (unless (org-at-heading-p) (outline-next-heading))
  13450. (setq start-level (org-current-level))))
  13451. (narrow-to-region (region-beginning)
  13452. (save-excursion
  13453. (goto-char (region-end))
  13454. (unless (and (bolp) (org-at-heading-p))
  13455. (outline-next-heading))
  13456. (point)))
  13457. (setq scope nil)))
  13458. (if (not scope)
  13459. (progn
  13460. (org-agenda-prepare-buffers
  13461. (and buffer-file-name (list buffer-file-name)))
  13462. (setq res
  13463. (org-scan-tags
  13464. func matcher org--matcher-tags-todo-only start-level)))
  13465. ;; Get the right scope
  13466. (cond
  13467. ((and scope (listp scope) (symbolp (car scope)))
  13468. (setq scope (eval scope)))
  13469. ((eq scope 'agenda)
  13470. (setq scope (org-agenda-files t)))
  13471. ((eq scope 'agenda-with-archives)
  13472. (setq scope (org-agenda-files t))
  13473. (setq scope (org-add-archive-files scope)))
  13474. ((eq scope 'file)
  13475. (setq scope (and buffer-file-name (list buffer-file-name))))
  13476. ((eq scope 'file-with-archives)
  13477. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  13478. (org-agenda-prepare-buffers scope)
  13479. (dolist (file scope)
  13480. (with-current-buffer (org-find-base-buffer-visiting file)
  13481. (org-with-wide-buffer
  13482. (goto-char (point-min))
  13483. (setq res
  13484. (append
  13485. res
  13486. (org-scan-tags
  13487. func matcher org--matcher-tags-todo-only)))))))))
  13488. res)))
  13489. ;;; Properties API
  13490. (defconst org-special-properties
  13491. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  13492. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  13493. "The special properties valid in Org mode.
  13494. These are properties that are not defined in the property drawer,
  13495. but in some other way.")
  13496. (defconst org-default-properties
  13497. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  13498. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  13499. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  13500. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  13501. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  13502. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  13503. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  13504. "Some properties that are used by Org mode for various purposes.
  13505. Being in this list makes sure that they are offered for completion.")
  13506. (defun org--valid-property-p (property)
  13507. "Non nil when string PROPERTY is a valid property name."
  13508. (not
  13509. (or (equal property "")
  13510. (string-match-p "\\s-" property))))
  13511. (defun org--update-property-plist (key val props)
  13512. "Associate KEY to VAL in alist PROPS.
  13513. Modifications are made by side-effect. Return new alist."
  13514. (let* ((appending (string= (substring key -1) "+"))
  13515. (key (if appending (substring key 0 -1) key))
  13516. (old (assoc-string key props t)))
  13517. (if (not old) (cons (cons key val) props)
  13518. (setcdr old (if appending (concat (cdr old) " " val) val))
  13519. props)))
  13520. (defun org-get-property-block (&optional beg force)
  13521. "Return the (beg . end) range of the body of the property drawer.
  13522. BEG is the beginning of the current subtree, or of the part
  13523. before the first headline. If it is not given, it will be found.
  13524. If the drawer does not exist, create it if FORCE is non-nil, or
  13525. return nil."
  13526. (org-with-wide-buffer
  13527. (when beg (goto-char beg))
  13528. (unless (org-before-first-heading-p)
  13529. (let ((beg (cond (beg)
  13530. ((or (not (featurep 'org-inlinetask))
  13531. (org-inlinetask-in-task-p))
  13532. (org-back-to-heading t))
  13533. (t (org-with-limited-levels (org-back-to-heading t))))))
  13534. (forward-line)
  13535. (when (looking-at-p org-planning-line-re) (forward-line))
  13536. (cond ((looking-at org-property-drawer-re)
  13537. (forward-line)
  13538. (cons (point) (progn (goto-char (match-end 0))
  13539. (line-beginning-position))))
  13540. (force
  13541. (goto-char beg)
  13542. (org-insert-property-drawer)
  13543. (let ((pos (save-excursion (search-forward ":END:")
  13544. (line-beginning-position))))
  13545. (cons pos pos))))))))
  13546. (defun org-at-property-p ()
  13547. "Non-nil when point is inside a property drawer.
  13548. See `org-property-re' for match data, if applicable."
  13549. (save-excursion
  13550. (beginning-of-line)
  13551. (and (looking-at org-property-re)
  13552. (let ((property-drawer (save-match-data (org-get-property-block))))
  13553. (and property-drawer
  13554. (>= (point) (car property-drawer))
  13555. (< (point) (cdr property-drawer)))))))
  13556. (defun org-property-action ()
  13557. "Do an action on properties."
  13558. (interactive)
  13559. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  13560. (let ((c (read-char-exclusive)))
  13561. (cl-case c
  13562. (?s (call-interactively #'org-set-property))
  13563. (?d (call-interactively #'org-delete-property))
  13564. (?D (call-interactively #'org-delete-property-globally))
  13565. (?c (call-interactively #'org-compute-property-at-point))
  13566. (otherwise (user-error "No such property action %c" c)))))
  13567. (defun org-inc-effort ()
  13568. "Increment the value of the effort property in the current entry."
  13569. (interactive)
  13570. (org-set-effort t))
  13571. (defvar org-clock-effort) ; Defined in org-clock.el.
  13572. (defvar org-clock-current-task) ; Defined in org-clock.el.
  13573. (defun org-set-effort (&optional increment value)
  13574. "Set the effort property of the current entry.
  13575. If INCREMENT is non-nil, set the property to the next allowed
  13576. value. Otherwise, if optional argument VALUE is provided, use
  13577. it. Eventually, prompt for the new value if none of the previous
  13578. variables is set."
  13579. (interactive "P")
  13580. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  13581. (current (org-entry-get nil org-effort-property))
  13582. (value
  13583. (cond
  13584. (increment
  13585. (unless allowed (user-error "Allowed effort values are not set"))
  13586. (or (cl-caadr (member (list current) allowed))
  13587. (user-error "Unknown value %S among allowed values" current)))
  13588. (value
  13589. (if (stringp value) value
  13590. (error "Invalid effort value: %S" value)))
  13591. (t
  13592. (let ((must-match
  13593. (and allowed
  13594. (not (get-text-property 0 'org-unrestricted
  13595. (caar allowed))))))
  13596. (completing-read "Effort: " allowed nil must-match))))))
  13597. (unless (equal current value)
  13598. (org-entry-put nil org-effort-property value))
  13599. (org-refresh-property '((effort . identity)
  13600. (effort-minutes . org-duration-to-minutes))
  13601. value)
  13602. (when (equal (org-get-heading t t t t)
  13603. (bound-and-true-p org-clock-current-task))
  13604. (setq org-clock-effort (org-get-at-bol 'effort))
  13605. (org-clock-update-mode-line))
  13606. (message "%s is now %s" org-effort-property value)))
  13607. (defun org-entry-properties (&optional pom which)
  13608. "Get all properties of the current entry.
  13609. When POM is a buffer position, get all properties from the entry
  13610. there instead.
  13611. This includes the TODO keyword, the tags, time strings for
  13612. deadline, scheduled, and clocking, and any additional properties
  13613. defined in the entry.
  13614. If WHICH is nil or `all', get all properties. If WHICH is
  13615. `special' or `standard', only get that subclass. If WHICH is
  13616. a string, only get that property.
  13617. Return value is an alist. Keys are properties, as upcased
  13618. strings."
  13619. (org-with-point-at pom
  13620. (when (and (derived-mode-p 'org-mode)
  13621. (ignore-errors (org-back-to-heading t)))
  13622. (catch 'exit
  13623. (let* ((beg (point))
  13624. (specific (and (stringp which) (upcase which)))
  13625. (which (cond ((not specific) which)
  13626. ((member specific org-special-properties) 'special)
  13627. (t 'standard)))
  13628. props)
  13629. ;; Get the special properties, like TODO and TAGS.
  13630. (when (memq which '(nil all special))
  13631. (when (or (not specific) (string= specific "CLOCKSUM"))
  13632. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  13633. (when clocksum
  13634. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  13635. props)))
  13636. (when specific (throw 'exit props)))
  13637. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  13638. (let ((clocksumt (get-text-property (point)
  13639. :org-clock-minutes-today)))
  13640. (when clocksumt
  13641. (push (cons "CLOCKSUM_T"
  13642. (org-duration-from-minutes clocksumt))
  13643. props)))
  13644. (when specific (throw 'exit props)))
  13645. (when (or (not specific) (string= specific "ITEM"))
  13646. (let ((case-fold-search nil))
  13647. (when (looking-at org-complex-heading-regexp)
  13648. (push (cons "ITEM"
  13649. (let ((title (match-string-no-properties 4)))
  13650. (if (org-string-nw-p title)
  13651. (org-remove-tabs title)
  13652. "")))
  13653. props)))
  13654. (when specific (throw 'exit props)))
  13655. (when (or (not specific) (string= specific "TODO"))
  13656. (let ((case-fold-search nil))
  13657. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  13658. (push (cons "TODO" (match-string-no-properties 2)) props)))
  13659. (when specific (throw 'exit props)))
  13660. (when (or (not specific) (string= specific "PRIORITY"))
  13661. (push (cons "PRIORITY"
  13662. (if (looking-at org-priority-regexp)
  13663. (match-string-no-properties 2)
  13664. (char-to-string org-default-priority)))
  13665. props)
  13666. (when specific (throw 'exit props)))
  13667. (when (or (not specific) (string= specific "FILE"))
  13668. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  13669. props)
  13670. (when specific (throw 'exit props)))
  13671. (when (or (not specific) (string= specific "TAGS"))
  13672. (let ((tags (org-get-tags nil t)))
  13673. (when tags
  13674. (push (cons "TAGS" (org-make-tag-string tags))
  13675. props)))
  13676. (when specific (throw 'exit props)))
  13677. (when (or (not specific) (string= specific "ALLTAGS"))
  13678. (let ((tags (org-get-tags)))
  13679. (when tags
  13680. (push (cons "ALLTAGS" (org-make-tag-string tags))
  13681. props)))
  13682. (when specific (throw 'exit props)))
  13683. (when (or (not specific) (string= specific "BLOCKED"))
  13684. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  13685. (when specific (throw 'exit props)))
  13686. (when (or (not specific)
  13687. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  13688. (forward-line)
  13689. (when (looking-at-p org-planning-line-re)
  13690. (end-of-line)
  13691. (let ((bol (line-beginning-position))
  13692. ;; Backward compatibility: time keywords used to
  13693. ;; be configurable (before 8.3). Make sure we
  13694. ;; get the correct keyword.
  13695. (key-assoc `(("CLOSED" . ,org-closed-string)
  13696. ("DEADLINE" . ,org-deadline-string)
  13697. ("SCHEDULED" . ,org-scheduled-string))))
  13698. (dolist (pair (if specific (list (assoc specific key-assoc))
  13699. key-assoc))
  13700. (save-excursion
  13701. (when (search-backward (cdr pair) bol t)
  13702. (goto-char (match-end 0))
  13703. (skip-chars-forward " \t")
  13704. (and (looking-at org-ts-regexp-both)
  13705. (push (cons (car pair)
  13706. (match-string-no-properties 0))
  13707. props)))))))
  13708. (when specific (throw 'exit props)))
  13709. (when (or (not specific)
  13710. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  13711. (let ((find-ts
  13712. (lambda (end ts)
  13713. ;; Fix next time-stamp before END. TS is the
  13714. ;; list of time-stamps found so far.
  13715. (let ((ts ts)
  13716. (regexp (cond
  13717. ((string= specific "TIMESTAMP")
  13718. org-ts-regexp)
  13719. ((string= specific "TIMESTAMP_IA")
  13720. org-ts-regexp-inactive)
  13721. ((assoc "TIMESTAMP_IA" ts)
  13722. org-ts-regexp)
  13723. ((assoc "TIMESTAMP" ts)
  13724. org-ts-regexp-inactive)
  13725. (t org-ts-regexp-both))))
  13726. (catch 'next
  13727. (while (re-search-forward regexp end t)
  13728. (backward-char)
  13729. (let ((object (org-element-context)))
  13730. ;; Accept to match timestamps in node
  13731. ;; properties, too.
  13732. (when (memq (org-element-type object)
  13733. '(node-property timestamp))
  13734. (let ((type
  13735. (org-element-property :type object)))
  13736. (cond
  13737. ((and (memq type '(active active-range))
  13738. (not (equal specific "TIMESTAMP_IA")))
  13739. (unless (assoc "TIMESTAMP" ts)
  13740. (push (cons "TIMESTAMP"
  13741. (org-element-property
  13742. :raw-value object))
  13743. ts)
  13744. (when specific (throw 'exit ts))))
  13745. ((and (memq type '(inactive inactive-range))
  13746. (not (string= specific "TIMESTAMP")))
  13747. (unless (assoc "TIMESTAMP_IA" ts)
  13748. (push (cons "TIMESTAMP_IA"
  13749. (org-element-property
  13750. :raw-value object))
  13751. ts)
  13752. (when specific (throw 'exit ts))))))
  13753. ;; Both timestamp types are found,
  13754. ;; move to next part.
  13755. (when (= (length ts) 2) (throw 'next ts)))))
  13756. ts)))))
  13757. (goto-char beg)
  13758. ;; First look for timestamps within headline.
  13759. (let ((ts (funcall find-ts (line-end-position) nil)))
  13760. (if (= (length ts) 2) (setq props (nconc ts props))
  13761. ;; Then find timestamps in the section, skipping
  13762. ;; planning line.
  13763. (let ((end (save-excursion (outline-next-heading))))
  13764. (forward-line)
  13765. (when (looking-at-p org-planning-line-re) (forward-line))
  13766. (setq props (nconc (funcall find-ts end ts) props))))))))
  13767. ;; Get the standard properties, like :PROP:.
  13768. (when (memq which '(nil all standard))
  13769. ;; If we are looking after a specific property, delegate
  13770. ;; to `org-entry-get', which is faster. However, make an
  13771. ;; exception for "CATEGORY", since it can be also set
  13772. ;; through keywords (i.e. #+CATEGORY).
  13773. (if (and specific (not (equal specific "CATEGORY")))
  13774. (let ((value (org-entry-get beg specific nil t)))
  13775. (throw 'exit (and value (list (cons specific value)))))
  13776. (let ((range (org-get-property-block beg)))
  13777. (when range
  13778. (let ((end (cdr range)) seen-base)
  13779. (goto-char (car range))
  13780. ;; Unlike to `org--update-property-plist', we
  13781. ;; handle the case where base values is found
  13782. ;; after its extension. We also forbid standard
  13783. ;; properties to be named as special properties.
  13784. (while (re-search-forward org-property-re end t)
  13785. (let* ((key (upcase (match-string-no-properties 2)))
  13786. (extendp (string-match-p "\\+\\'" key))
  13787. (key-base (if extendp (substring key 0 -1) key))
  13788. (value (match-string-no-properties 3)))
  13789. (cond
  13790. ((member-ignore-case key-base org-special-properties))
  13791. (extendp
  13792. (setq props
  13793. (org--update-property-plist key value props)))
  13794. ((member key seen-base))
  13795. (t (push key seen-base)
  13796. (let ((p (assoc-string key props t)))
  13797. (if p (setcdr p (concat value " " (cdr p)))
  13798. (push (cons key value) props))))))))))))
  13799. (unless (assoc "CATEGORY" props)
  13800. (push (cons "CATEGORY" (org-get-category beg)) props)
  13801. (when (string= specific "CATEGORY") (throw 'exit props)))
  13802. ;; Return value.
  13803. props)))))
  13804. (defun org--property-local-values (property literal-nil)
  13805. "Return value for PROPERTY in current entry.
  13806. Value is a list whose car is the base value for PROPERTY and cdr
  13807. a list of accumulated values. Return nil if neither is found in
  13808. the entry. Also return nil when PROPERTY is set to \"nil\",
  13809. unless LITERAL-NIL is non-nil."
  13810. (let ((range (org-get-property-block)))
  13811. (when range
  13812. (goto-char (car range))
  13813. (let* ((case-fold-search t)
  13814. (end (cdr range))
  13815. (value
  13816. ;; Base value.
  13817. (save-excursion
  13818. (let ((v (and (re-search-forward
  13819. (org-re-property property nil t) end t)
  13820. (match-string-no-properties 3))))
  13821. (list (if literal-nil v (org-not-nil v)))))))
  13822. ;; Find additional values.
  13823. (let* ((property+ (org-re-property (concat property "+") nil t)))
  13824. (while (re-search-forward property+ end t)
  13825. (push (match-string-no-properties 3) value)))
  13826. ;; Return final values.
  13827. (and (not (equal value '(nil))) (nreverse value))))))
  13828. (defun org--property-global-value (property literal-nil)
  13829. "Return value for PROPERTY in current buffer.
  13830. Return value is a string. Return nil if property is not set
  13831. globally. Also return nil when PROPERTY is set to \"nil\",
  13832. unless LITERAL-NIL is non-nil."
  13833. (let ((global
  13834. (cdr (or (assoc-string property org-file-properties t)
  13835. (assoc-string property org-global-properties t)
  13836. (assoc-string property org-global-properties-fixed t)))))
  13837. (if literal-nil global (org-not-nil global))))
  13838. (defun org-entry-get (pom property &optional inherit literal-nil)
  13839. "Get value of PROPERTY for entry or content at point-or-marker POM.
  13840. If INHERIT is non-nil and the entry does not have the property,
  13841. then also check higher levels of the hierarchy. If INHERIT is
  13842. the symbol `selective', use inheritance only if the setting in
  13843. `org-use-property-inheritance' selects PROPERTY for inheritance.
  13844. If the property is present but empty, the return value is the
  13845. empty string. If the property is not present at all, nil is
  13846. returned. In any other case, return the value as a string.
  13847. Search is case-insensitive.
  13848. If LITERAL-NIL is set, return the string value \"nil\" as
  13849. a string, do not interpret it as the list atom nil. This is used
  13850. for inheritance when a \"nil\" value can supersede a non-nil
  13851. value higher up the hierarchy."
  13852. (org-with-point-at pom
  13853. (cond
  13854. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  13855. ;; We need a special property. Use `org-entry-properties' to
  13856. ;; retrieve it, but specify the wanted property.
  13857. (cdr (assoc-string property (org-entry-properties nil property))))
  13858. ((and inherit
  13859. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  13860. (org-entry-get-with-inheritance property literal-nil))
  13861. (t
  13862. (let* ((local (org--property-local-values property literal-nil))
  13863. (value (and local (mapconcat #'identity (delq nil local) " "))))
  13864. (if literal-nil value (org-not-nil value)))))))
  13865. (defun org-property-or-variable-value (var &optional inherit)
  13866. "Check if there is a property fixing the value of VAR.
  13867. If yes, return this value. If not, return the current value of the variable."
  13868. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  13869. (if (and prop (stringp prop) (string-match "\\S-" prop))
  13870. (read prop)
  13871. (symbol-value var))))
  13872. (defun org-entry-delete (pom property)
  13873. "Delete PROPERTY from entry at point-or-marker POM.
  13874. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  13875. non-nil when a property was removed."
  13876. (org-with-point-at pom
  13877. (pcase (org-get-property-block)
  13878. (`(,begin . ,origin)
  13879. (let* ((end (copy-marker origin))
  13880. (re (org-re-property
  13881. (concat (regexp-quote property) "\\+?") t t)))
  13882. (goto-char begin)
  13883. (while (re-search-forward re end t)
  13884. (delete-region (match-beginning 0) (line-beginning-position 2)))
  13885. ;; If drawer is empty, remove it altogether.
  13886. (when (= begin end)
  13887. (delete-region (line-beginning-position 0)
  13888. (line-beginning-position 2)))
  13889. ;; Return non-nil if some property was removed.
  13890. (prog1 (/= end origin) (set-marker end nil))))
  13891. (_ nil))))
  13892. ;; Multi-values properties are properties that contain multiple values
  13893. ;; These values are assumed to be single words, separated by whitespace.
  13894. (defun org-entry-add-to-multivalued-property (pom property value)
  13895. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  13896. (let* ((old (org-entry-get pom property))
  13897. (values (and old (split-string old))))
  13898. (setq value (org-entry-protect-space value))
  13899. (unless (member value values)
  13900. (setq values (append values (list value)))
  13901. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13902. (defun org-entry-remove-from-multivalued-property (pom property value)
  13903. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  13904. (let* ((old (org-entry-get pom property))
  13905. (values (and old (split-string old))))
  13906. (setq value (org-entry-protect-space value))
  13907. (when (member value values)
  13908. (setq values (delete value values))
  13909. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13910. (defun org-entry-member-in-multivalued-property (pom property value)
  13911. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  13912. (let* ((old (org-entry-get pom property))
  13913. (values (and old (split-string old))))
  13914. (setq value (org-entry-protect-space value))
  13915. (member value values)))
  13916. (defun org-entry-get-multivalued-property (pom property)
  13917. "Return a list of values in a multivalued property."
  13918. (let* ((value (org-entry-get pom property))
  13919. (values (and value (split-string value))))
  13920. (mapcar #'org-entry-restore-space values)))
  13921. (defun org-entry-put-multivalued-property (pom property &rest values)
  13922. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  13923. VALUES should be a list of strings. Spaces will be protected."
  13924. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  13925. (let* ((value (org-entry-get pom property))
  13926. (values (and value (split-string value))))
  13927. (mapcar #'org-entry-restore-space values)))
  13928. (defun org-entry-protect-space (s)
  13929. "Protect spaces and newline in string S."
  13930. (while (string-match " " s)
  13931. (setq s (replace-match "%20" t t s)))
  13932. (while (string-match "\n" s)
  13933. (setq s (replace-match "%0A" t t s)))
  13934. s)
  13935. (defun org-entry-restore-space (s)
  13936. "Restore spaces and newline in string S."
  13937. (while (string-match "%20" s)
  13938. (setq s (replace-match " " t t s)))
  13939. (while (string-match "%0A" s)
  13940. (setq s (replace-match "\n" t t s)))
  13941. s)
  13942. (defvar org-entry-property-inherited-from (make-marker)
  13943. "Marker pointing to the entry from where a property was inherited.
  13944. Each call to `org-entry-get-with-inheritance' will set this marker to the
  13945. location of the entry where the inheritance search matched. If there was
  13946. no match, the marker will point nowhere.
  13947. Note that also `org-entry-get' calls this function, if the INHERIT flag
  13948. is set.")
  13949. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  13950. "Get PROPERTY of entry or content at point, search higher levels if needed.
  13951. The search will stop at the first ancestor which has the property defined.
  13952. If the value found is \"nil\", return nil to show that the property
  13953. should be considered as undefined (this is the meaning of nil here).
  13954. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  13955. (move-marker org-entry-property-inherited-from nil)
  13956. (org-with-wide-buffer
  13957. (let (value)
  13958. (catch 'exit
  13959. (while t
  13960. (let ((v (org--property-local-values property literal-nil)))
  13961. (when v
  13962. (setq value
  13963. (concat (mapconcat #'identity (delq nil v) " ")
  13964. (and value " ")
  13965. value)))
  13966. (cond
  13967. ((car v)
  13968. (org-back-to-heading t)
  13969. (move-marker org-entry-property-inherited-from (point))
  13970. (throw 'exit nil))
  13971. ((org-up-heading-safe))
  13972. (t
  13973. (let ((global (org--property-global-value property literal-nil)))
  13974. (cond ((not global))
  13975. (value (setq value (concat global " " value)))
  13976. (t (setq value global))))
  13977. (throw 'exit nil))))))
  13978. (if literal-nil value (org-not-nil value)))))
  13979. (defvar org-property-changed-functions nil
  13980. "Hook called when the value of a property has changed.
  13981. Each hook function should accept two arguments, the name of the property
  13982. and the new value.")
  13983. (defun org-entry-put (pom property value)
  13984. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  13985. If the value is nil, it is converted to the empty string. If it
  13986. is not a string, an error is raised. Also raise an error on
  13987. invalid property names.
  13988. PROPERTY can be any regular property (see
  13989. `org-special-properties'). It can also be \"TODO\",
  13990. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  13991. For the last two properties, VALUE may have any of the special
  13992. values \"earlier\" and \"later\". The function then increases or
  13993. decreases scheduled or deadline date by one day."
  13994. (cond ((null value) (setq value ""))
  13995. ((not (stringp value)) (error "Properties values should be strings"))
  13996. ((not (org--valid-property-p property))
  13997. (user-error "Invalid property name: \"%s\"" property)))
  13998. (org-with-point-at pom
  13999. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14000. (org-back-to-heading t)
  14001. (org-with-limited-levels (org-back-to-heading t)))
  14002. (let ((beg (point)))
  14003. (cond
  14004. ((equal property "TODO")
  14005. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14006. ((not (member value org-todo-keywords-1))
  14007. (user-error "\"%s\" is not a valid TODO state" value)))
  14008. (org-todo value)
  14009. (org-align-tags))
  14010. ((equal property "PRIORITY")
  14011. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14012. (org-align-tags))
  14013. ((equal property "SCHEDULED")
  14014. (forward-line)
  14015. (if (and (looking-at-p org-planning-line-re)
  14016. (re-search-forward
  14017. org-scheduled-time-regexp (line-end-position) t))
  14018. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14019. ((string= value "later") (org-timestamp-change 1 'day))
  14020. ((string= value "") (org-schedule '(4)))
  14021. (t (org-schedule nil value)))
  14022. (if (member value '("earlier" "later" ""))
  14023. (call-interactively #'org-schedule)
  14024. (org-schedule nil value))))
  14025. ((equal property "DEADLINE")
  14026. (forward-line)
  14027. (if (and (looking-at-p org-planning-line-re)
  14028. (re-search-forward
  14029. org-deadline-time-regexp (line-end-position) t))
  14030. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14031. ((string= value "later") (org-timestamp-change 1 'day))
  14032. ((string= value "") (org-deadline '(4)))
  14033. (t (org-deadline nil value)))
  14034. (if (member value '("earlier" "later" ""))
  14035. (call-interactively #'org-deadline)
  14036. (org-deadline nil value))))
  14037. ((member property org-special-properties)
  14038. (error "The %s property cannot be set with `org-entry-put'" property))
  14039. (t
  14040. (let* ((range (org-get-property-block beg 'force))
  14041. (end (cdr range))
  14042. (case-fold-search t))
  14043. (goto-char (car range))
  14044. (if (re-search-forward (org-re-property property nil t) end t)
  14045. (progn (delete-region (match-beginning 0) (match-end 0))
  14046. (goto-char (match-beginning 0)))
  14047. (goto-char end)
  14048. (insert "\n")
  14049. (backward-char))
  14050. (insert ":" property ":")
  14051. (when value (insert " " value))
  14052. (org-indent-line)))))
  14053. (run-hook-with-args 'org-property-changed-functions property value)))
  14054. (defun org-buffer-property-keys (&optional specials defaults columns)
  14055. "Get all property keys in the current buffer.
  14056. When SPECIALS is non-nil, also list the special properties that
  14057. reflect things like tags and TODO state.
  14058. When DEFAULTS is non-nil, also include properties that has
  14059. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14060. DESCRIPTION, LOCATION, and LOGGING and others.
  14061. When COLUMNS in non-nil, also include property names given in
  14062. COLUMN formats in the current buffer."
  14063. (let ((case-fold-search t)
  14064. (props (append
  14065. (and specials org-special-properties)
  14066. (and defaults (cons org-effort-property org-default-properties))
  14067. nil)))
  14068. (org-with-wide-buffer
  14069. (goto-char (point-min))
  14070. (while (re-search-forward org-property-start-re nil t)
  14071. (catch :skip
  14072. (let ((range (org-get-property-block)))
  14073. (unless range (throw :skip nil))
  14074. (goto-char (car range))
  14075. (let ((begin (car range))
  14076. (end (cdr range)))
  14077. ;; Make sure that found property block is not located
  14078. ;; before current point, as it would generate an infloop.
  14079. ;; It can happen, for example, in the following
  14080. ;; situation:
  14081. ;;
  14082. ;; * Headline
  14083. ;; :PROPERTIES:
  14084. ;; ...
  14085. ;; :END:
  14086. ;; *************** Inlinetask
  14087. ;; #+BEGIN_EXAMPLE
  14088. ;; :PROPERTIES:
  14089. ;; #+END_EXAMPLE
  14090. ;;
  14091. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  14092. (while (< (point) end)
  14093. (let ((p (progn (looking-at org-property-re)
  14094. (match-string-no-properties 2))))
  14095. ;; Only add true property name, not extension symbol.
  14096. (push (if (not (string-match-p "\\+\\'" p)) p
  14097. (substring p 0 -1))
  14098. props))
  14099. (forward-line))))
  14100. (outline-next-heading)))
  14101. (when columns
  14102. (goto-char (point-min))
  14103. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14104. (let ((element (org-element-at-point)))
  14105. (when (memq (org-element-type element) '(keyword node-property))
  14106. (let ((value (org-element-property :value element))
  14107. (start 0))
  14108. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  14109. \\(?:{[^}]+}\\)?"
  14110. value start)
  14111. (setq start (match-end 0))
  14112. (let ((p (match-string-no-properties 1 value)))
  14113. (unless (member-ignore-case p org-special-properties)
  14114. (push p props))))))))))
  14115. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14116. (defun org-property-values (key)
  14117. "List all non-nil values of property KEY in current buffer."
  14118. (org-with-wide-buffer
  14119. (goto-char (point-min))
  14120. (let ((case-fold-search t)
  14121. (re (org-re-property key))
  14122. values)
  14123. (while (re-search-forward re nil t)
  14124. (push (org-entry-get (point) key) values))
  14125. (delete-dups values))))
  14126. (defun org-insert-property-drawer ()
  14127. "Insert a property drawer into the current entry."
  14128. (org-with-wide-buffer
  14129. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14130. (org-back-to-heading t)
  14131. (org-with-limited-levels (org-back-to-heading t)))
  14132. (forward-line)
  14133. (when (looking-at-p org-planning-line-re) (forward-line))
  14134. (unless (looking-at-p org-property-drawer-re)
  14135. ;; Make sure we start editing a line from current entry, not from
  14136. ;; next one. It prevents extending text properties or overlays
  14137. ;; belonging to the latter.
  14138. (when (bolp) (backward-char))
  14139. (let ((begin (1+ (point)))
  14140. (inhibit-read-only t))
  14141. (insert "\n:PROPERTIES:\n:END:")
  14142. (when (eobp) (insert "\n"))
  14143. (org-indent-region begin (point))))))
  14144. (defun org-insert-drawer (&optional arg drawer)
  14145. "Insert a drawer at point.
  14146. When optional argument ARG is non-nil, insert a property drawer.
  14147. Optional argument DRAWER, when non-nil, is a string representing
  14148. drawer's name. Otherwise, the user is prompted for a name.
  14149. If a region is active, insert the drawer around that region
  14150. instead.
  14151. Point is left between drawer's boundaries."
  14152. (interactive "P")
  14153. (let* ((drawer (if arg "PROPERTIES"
  14154. (or drawer (read-from-minibuffer "Drawer: ")))))
  14155. (cond
  14156. ;; With C-u, fall back on `org-insert-property-drawer'
  14157. (arg (org-insert-property-drawer))
  14158. ;; Check validity of suggested drawer's name.
  14159. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14160. (user-error "Invalid drawer name"))
  14161. ;; With an active region, insert a drawer at point.
  14162. ((not (org-region-active-p))
  14163. (progn
  14164. (unless (bolp) (insert "\n"))
  14165. (insert (format ":%s:\n\n:END:\n" drawer))
  14166. (forward-line -2)))
  14167. ;; Otherwise, insert the drawer at point
  14168. (t
  14169. (let ((rbeg (region-beginning))
  14170. (rend (copy-marker (region-end))))
  14171. (unwind-protect
  14172. (progn
  14173. (goto-char rbeg)
  14174. (beginning-of-line)
  14175. (when (save-excursion
  14176. (re-search-forward org-outline-regexp-bol rend t))
  14177. (user-error "Drawers cannot contain headlines"))
  14178. ;; Position point at the beginning of the first
  14179. ;; non-blank line in region. Insert drawer's opening
  14180. ;; there, then indent it.
  14181. (org-skip-whitespace)
  14182. (beginning-of-line)
  14183. (insert ":" drawer ":\n")
  14184. (forward-line -1)
  14185. (indent-for-tab-command)
  14186. ;; Move point to the beginning of the first blank line
  14187. ;; after the last non-blank line in region. Insert
  14188. ;; drawer's closing, then indent it.
  14189. (goto-char rend)
  14190. (skip-chars-backward " \r\t\n")
  14191. (insert "\n:END:")
  14192. (deactivate-mark t)
  14193. (indent-for-tab-command)
  14194. (unless (eolp) (insert "\n")))
  14195. ;; Clear marker, whatever the outcome of insertion is.
  14196. (set-marker rend nil)))))))
  14197. (defvar org-property-set-functions-alist nil
  14198. "Property set function alist.
  14199. Each entry should have the following format:
  14200. (PROPERTY . READ-FUNCTION)
  14201. The read function will be called with the same argument as
  14202. `org-completing-read'.")
  14203. (defun org-set-property-function (property)
  14204. "Get the function that should be used to set PROPERTY.
  14205. This is computed according to `org-property-set-functions-alist'."
  14206. (or (cdr (assoc property org-property-set-functions-alist))
  14207. 'org-completing-read))
  14208. (defun org-read-property-value (property)
  14209. "Read PROPERTY value from user."
  14210. (let* ((completion-ignore-case t)
  14211. (allowed (org-property-get-allowed-values nil property 'table))
  14212. (cur (org-entry-get nil property))
  14213. (prompt (concat property " value"
  14214. (if (and cur (string-match "\\S-" cur))
  14215. (concat " [" cur "]") "") ": "))
  14216. (set-function (org-set-property-function property))
  14217. (val (if allowed
  14218. (funcall set-function prompt allowed nil
  14219. (not (get-text-property 0 'org-unrestricted
  14220. (caar allowed))))
  14221. (funcall set-function prompt
  14222. (mapcar 'list (org-property-values property))
  14223. nil nil "" nil cur))))
  14224. (org-trim val)))
  14225. (defvar org-last-set-property nil)
  14226. (defvar org-last-set-property-value nil)
  14227. (defun org-read-property-name ()
  14228. "Read a property name."
  14229. (let ((completion-ignore-case t)
  14230. (default-prop (or (and (org-at-property-p)
  14231. (match-string-no-properties 2))
  14232. org-last-set-property)))
  14233. (org-completing-read
  14234. (concat "Property"
  14235. (if default-prop (concat " [" default-prop "]") "")
  14236. ": ")
  14237. (mapcar #'list (org-buffer-property-keys nil t t))
  14238. nil nil nil nil default-prop)))
  14239. (defun org-set-property-and-value (use-last)
  14240. "Allow to set [PROPERTY]: [value] direction from prompt.
  14241. When use-default, don't even ask, just use the last
  14242. \"[PROPERTY]: [value]\" string from the history."
  14243. (interactive "P")
  14244. (let* ((completion-ignore-case t)
  14245. (pv (or (and use-last org-last-set-property-value)
  14246. (org-completing-read
  14247. "Enter a \"[Property]: [value]\" pair: "
  14248. nil nil nil nil nil
  14249. org-last-set-property-value)))
  14250. prop val)
  14251. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14252. (setq prop (match-string 1 pv)
  14253. val (match-string 2 pv))
  14254. (org-set-property prop val))))
  14255. (defun org-set-property (property value)
  14256. "In the current entry, set PROPERTY to VALUE.
  14257. When called interactively, this will prompt for a property name, offering
  14258. completion on existing and default properties. And then it will prompt
  14259. for a value, offering completion either on allowed values (via an inherited
  14260. xxx_ALL property) or on existing values in other instances of this property
  14261. in the current file.
  14262. Throw an error when trying to set a property with an invalid name."
  14263. (interactive (list nil nil))
  14264. (let ((property (or property (org-read-property-name))))
  14265. ;; `org-entry-put' also makes the following check, but this one
  14266. ;; avoids polluting `org-last-set-property' and
  14267. ;; `org-last-set-property-value' needlessly.
  14268. (unless (org--valid-property-p property)
  14269. (user-error "Invalid property name: \"%s\"" property))
  14270. (let ((value (or value (org-read-property-value property)))
  14271. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14272. (setq org-last-set-property property)
  14273. (setq org-last-set-property-value (concat property ": " value))
  14274. ;; Possibly postprocess the inserted value:
  14275. (when fn (setq value (funcall fn value)))
  14276. (unless (equal (org-entry-get nil property) value)
  14277. (org-entry-put nil property value)))))
  14278. (defun org-find-property (property &optional value)
  14279. "Find first entry in buffer that sets PROPERTY.
  14280. When optional argument VALUE is non-nil, only consider an entry
  14281. if it contains PROPERTY set to this value. If PROPERTY should be
  14282. explicitly set to nil, use string \"nil\" for VALUE.
  14283. Return position where the entry begins, or nil if there is no
  14284. such entry. If narrowing is in effect, only search the visible
  14285. part of the buffer."
  14286. (save-excursion
  14287. (goto-char (point-min))
  14288. (let ((case-fold-search t)
  14289. (re (org-re-property property nil (not value) value)))
  14290. (catch 'exit
  14291. (while (re-search-forward re nil t)
  14292. (when (if value (org-at-property-p)
  14293. (org-entry-get (point) property nil t))
  14294. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14295. (defun org-delete-property (property)
  14296. "In the current entry, delete PROPERTY."
  14297. (interactive
  14298. (let* ((completion-ignore-case t)
  14299. (cat (org-entry-get (point) "CATEGORY"))
  14300. (props0 (org-entry-properties nil 'standard))
  14301. (props (if cat props0
  14302. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14303. (prop (if (< 1 (length props))
  14304. (completing-read "Property: " props nil t)
  14305. (caar props))))
  14306. (list prop)))
  14307. (if (not property)
  14308. (message "No property to delete in this entry")
  14309. (org-entry-delete nil property)
  14310. (message "Property \"%s\" deleted" property)))
  14311. (defun org-delete-property-globally (property)
  14312. "Remove PROPERTY globally, from all entries.
  14313. This function ignores narrowing, if any."
  14314. (interactive
  14315. (let* ((completion-ignore-case t)
  14316. (prop (completing-read
  14317. "Globally remove property: "
  14318. (mapcar #'list (org-buffer-property-keys)))))
  14319. (list prop)))
  14320. (org-with-wide-buffer
  14321. (goto-char (point-min))
  14322. (let ((count 0)
  14323. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14324. (while (re-search-forward re nil t)
  14325. (when (org-entry-delete (point) property) (cl-incf count)))
  14326. (message "Property \"%s\" removed from %d entries" property count))))
  14327. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14328. (defun org-compute-property-at-point ()
  14329. "Compute the property at point.
  14330. This looks for an enclosing column format, extracts the operator and
  14331. then applies it to the property in the column format's scope."
  14332. (interactive)
  14333. (unless (org-at-property-p)
  14334. (user-error "Not at a property"))
  14335. (let ((prop (match-string-no-properties 2)))
  14336. (org-columns-get-format-and-top-level)
  14337. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14338. (user-error "No operator defined for property %s" prop))
  14339. (org-columns-compute prop)))
  14340. (defvar org-property-allowed-value-functions nil
  14341. "Hook for functions supplying allowed values for a specific property.
  14342. The functions must take a single argument, the name of the property, and
  14343. return a flat list of allowed values. If \":ETC\" is one of
  14344. the values, this means that these values are intended as defaults for
  14345. completion, but that other values should be allowed too.
  14346. The functions must return nil if they are not responsible for this
  14347. property.")
  14348. (defun org-property-get-allowed-values (pom property &optional table)
  14349. "Get allowed values for the property PROPERTY.
  14350. When TABLE is non-nil, return an alist that can directly be used for
  14351. completion."
  14352. (let (vals)
  14353. (cond
  14354. ((equal property "TODO")
  14355. (setq vals (org-with-point-at pom
  14356. (append org-todo-keywords-1 '("")))))
  14357. ((equal property "PRIORITY")
  14358. (let ((n org-lowest-priority))
  14359. (while (>= n org-highest-priority)
  14360. (push (char-to-string n) vals)
  14361. (setq n (1- n)))))
  14362. ((equal property "CATEGORY"))
  14363. ((member property org-special-properties))
  14364. ((setq vals (run-hook-with-args-until-success
  14365. 'org-property-allowed-value-functions property)))
  14366. (t
  14367. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14368. (when (and vals (string-match "\\S-" vals))
  14369. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14370. (setq vals (mapcar (lambda (x)
  14371. (cond ((stringp x) x)
  14372. ((numberp x) (number-to-string x))
  14373. ((symbolp x) (symbol-name x))
  14374. (t "???")))
  14375. vals)))))
  14376. (when (member ":ETC" vals)
  14377. (setq vals (remove ":ETC" vals))
  14378. (org-add-props (car vals) '(org-unrestricted t)))
  14379. (if table (mapcar 'list vals) vals)))
  14380. (defun org-property-previous-allowed-value (&optional _previous)
  14381. "Switch to the next allowed value for this property."
  14382. (interactive)
  14383. (org-property-next-allowed-value t))
  14384. (defun org-property-next-allowed-value (&optional previous)
  14385. "Switch to the next allowed value for this property."
  14386. (interactive)
  14387. (unless (org-at-property-p)
  14388. (user-error "Not at a property"))
  14389. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14390. (key (match-string 2))
  14391. (value (match-string 3))
  14392. (allowed (or (org-property-get-allowed-values (point) key)
  14393. (and (member value '("[ ]" "[-]" "[X]"))
  14394. '("[ ]" "[X]"))))
  14395. (heading (save-match-data (nth 4 (org-heading-components))))
  14396. nval)
  14397. (unless allowed
  14398. (user-error "Allowed values for this property have not been defined"))
  14399. (when previous (setq allowed (reverse allowed)))
  14400. (when (member value allowed)
  14401. (setq nval (car (cdr (member value allowed)))))
  14402. (setq nval (or nval (car allowed)))
  14403. (when (equal nval value)
  14404. (user-error "Only one allowed value for this property"))
  14405. (org-at-property-p)
  14406. (replace-match (concat " :" key ": " nval) t t)
  14407. (org-indent-line)
  14408. (beginning-of-line 1)
  14409. (skip-chars-forward " \t")
  14410. (when (equal prop org-effort-property)
  14411. (org-refresh-property
  14412. '((effort . identity)
  14413. (effort-minutes . org-duration-to-minutes))
  14414. nval)
  14415. (when (string= org-clock-current-task heading)
  14416. (setq org-clock-effort nval)
  14417. (org-clock-update-mode-line)))
  14418. (run-hook-with-args 'org-property-changed-functions key nval)))
  14419. (defun org-find-olp (path &optional this-buffer)
  14420. "Return a marker pointing to the entry at outline path OLP.
  14421. If anything goes wrong, throw an error.
  14422. You can wrap this call to catch the error like this:
  14423. (condition-case msg
  14424. (org-mobile-locate-entry (match-string 4))
  14425. (error (nth 1 msg)))
  14426. The return value will then be either a string with the error message,
  14427. or a marker if everything is OK.
  14428. If THIS-BUFFER is set, the outline path does not contain a file,
  14429. only headings."
  14430. (let* ((file (if this-buffer buffer-file-name (pop path)))
  14431. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  14432. (level 1)
  14433. (lmin 1)
  14434. (lmax 1)
  14435. end found flevel)
  14436. (unless buffer (error "File not found :%s" file))
  14437. (with-current-buffer buffer
  14438. (unless (derived-mode-p 'org-mode)
  14439. (error "Buffer %s needs to be in Org mode" buffer))
  14440. (org-with-wide-buffer
  14441. (goto-char (point-min))
  14442. (dolist (heading path)
  14443. (let ((re (format org-complex-heading-regexp-format
  14444. (regexp-quote heading)))
  14445. (cnt 0))
  14446. (while (re-search-forward re end t)
  14447. (setq level (- (match-end 1) (match-beginning 1)))
  14448. (when (and (>= level lmin) (<= level lmax))
  14449. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  14450. (when (= cnt 0)
  14451. (error "Heading not found on level %d: %s" lmax heading))
  14452. (when (> cnt 1)
  14453. (error "Heading not unique on level %d: %s" lmax heading))
  14454. (goto-char found)
  14455. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  14456. (setq end (save-excursion (org-end-of-subtree t t)))))
  14457. (when (org-at-heading-p)
  14458. (point-marker))))))
  14459. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  14460. "Find node HEADING in BUFFER.
  14461. Return a marker to the heading if it was found, or nil if not.
  14462. If POS-ONLY is set, return just the position instead of a marker.
  14463. The heading text must match exact, but it may have a TODO keyword,
  14464. a priority cookie and tags in the standard locations."
  14465. (with-current-buffer (or buffer (current-buffer))
  14466. (org-with-wide-buffer
  14467. (goto-char (point-min))
  14468. (let (case-fold-search)
  14469. (when (re-search-forward
  14470. (format org-complex-heading-regexp-format
  14471. (regexp-quote heading)) nil t)
  14472. (if pos-only
  14473. (match-beginning 0)
  14474. (move-marker (make-marker) (match-beginning 0))))))))
  14475. (defun org-find-exact-heading-in-directory (heading &optional dir)
  14476. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  14477. When the target headline is found, return a marker to this location."
  14478. (let ((files (directory-files (or dir default-directory)
  14479. t "\\`[^.#].*\\.org\\'"))
  14480. visiting m buffer)
  14481. (catch 'found
  14482. (dolist (file files)
  14483. (message "trying %s" file)
  14484. (setq visiting (org-find-base-buffer-visiting file))
  14485. (setq buffer (or visiting (find-file-noselect file)))
  14486. (setq m (org-find-exact-headline-in-buffer
  14487. heading buffer))
  14488. (when (and (not m) (not visiting)) (kill-buffer buffer))
  14489. (and m (throw 'found m))))))
  14490. (defun org-find-entry-with-id (ident)
  14491. "Locate the entry that contains the ID property with exact value IDENT.
  14492. IDENT can be a string, a symbol or a number, this function will search for
  14493. the string representation of it.
  14494. Return the position where this entry starts, or nil if there is no such entry."
  14495. (interactive "sID: ")
  14496. (let ((id (cond
  14497. ((stringp ident) ident)
  14498. ((symbolp ident) (symbol-name ident))
  14499. ((numberp ident) (number-to-string ident))
  14500. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  14501. (org-with-wide-buffer (org-find-property "ID" id))))
  14502. ;;;; Timestamps
  14503. (defvar org-last-changed-timestamp nil)
  14504. (defvar org-last-inserted-timestamp nil
  14505. "The last time stamp inserted with `org-insert-time-stamp'.")
  14506. (defun org-time-stamp (arg &optional inactive)
  14507. "Prompt for a date/time and insert a time stamp.
  14508. If the user specifies a time like HH:MM or if this command is
  14509. called with at least one prefix argument, the time stamp contains
  14510. the date and the time. Otherwise, only the date is included.
  14511. All parts of a date not specified by the user are filled in from
  14512. the timestamp at point, if any, or the current date/time
  14513. otherwise.
  14514. If there is already a timestamp at the cursor, it is replaced.
  14515. With two universal prefix arguments, insert an active timestamp
  14516. with the current time without prompting the user.
  14517. When called from lisp, the timestamp is inactive if INACTIVE is
  14518. non-nil."
  14519. (interactive "P")
  14520. (let* ((ts (cond
  14521. ((org-at-date-range-p t)
  14522. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  14523. ((org-at-timestamp-p 'lax) (match-string 0))))
  14524. ;; Default time is either the timestamp at point or today.
  14525. ;; When entering a range, only the range start is considered.
  14526. (default-time (if (not ts) (current-time)
  14527. (apply #'encode-time (org-parse-time-string ts))))
  14528. (default-input (and ts (org-get-compact-tod ts)))
  14529. (repeater (and ts
  14530. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  14531. (match-string 0 ts)))
  14532. org-time-was-given
  14533. org-end-time-was-given
  14534. (time
  14535. (and (if (equal arg '(16)) (current-time)
  14536. ;; Preserve `this-command' and `last-command'.
  14537. (let ((this-command this-command)
  14538. (last-command last-command))
  14539. (org-read-date
  14540. arg 'totime nil nil default-time default-input
  14541. inactive))))))
  14542. (cond
  14543. ((and ts
  14544. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  14545. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  14546. (insert "--")
  14547. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  14548. (ts
  14549. ;; Make sure we're on a timestamp. When in the middle of a date
  14550. ;; range, move arbitrarily to range end.
  14551. (unless (org-at-timestamp-p 'lax)
  14552. (skip-chars-forward "-")
  14553. (org-at-timestamp-p 'lax))
  14554. (replace-match "")
  14555. (setq org-last-changed-timestamp
  14556. (org-insert-time-stamp
  14557. time (or org-time-was-given arg)
  14558. inactive nil nil (list org-end-time-was-given)))
  14559. (when repeater
  14560. (backward-char)
  14561. (insert " " repeater)
  14562. (setq org-last-changed-timestamp
  14563. (concat (substring org-last-inserted-timestamp 0 -1)
  14564. " " repeater ">")))
  14565. (message "Timestamp updated"))
  14566. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  14567. (t (org-insert-time-stamp
  14568. time (or org-time-was-given arg) inactive nil nil
  14569. (list org-end-time-was-given))))))
  14570. ;; FIXME: can we use this for something else, like computing time differences?
  14571. (defun org-get-compact-tod (s)
  14572. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  14573. (let* ((t1 (match-string 1 s))
  14574. (h1 (string-to-number (match-string 2 s)))
  14575. (m1 (string-to-number (match-string 3 s)))
  14576. (t2 (and (match-end 4) (match-string 5 s)))
  14577. (h2 (and t2 (string-to-number (match-string 6 s))))
  14578. (m2 (and t2 (string-to-number (match-string 7 s))))
  14579. dh dm)
  14580. (if (not t2)
  14581. t1
  14582. (setq dh (- h2 h1) dm (- m2 m1))
  14583. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  14584. (concat t1 "+" (number-to-string dh)
  14585. (and (/= 0 dm) (format ":%02d" dm)))))))
  14586. (defun org-time-stamp-inactive (&optional arg)
  14587. "Insert an inactive time stamp.
  14588. An inactive time stamp is enclosed in square brackets instead of angle
  14589. brackets. It is inactive in the sense that it does not trigger agenda entries,
  14590. does not link to the calendar and cannot be changed with the S-cursor keys.
  14591. So these are more for recording a certain time/date.
  14592. If the user specifies a time like HH:MM or if this command is called with
  14593. at least one prefix argument, the time stamp contains the date and the time.
  14594. Otherwise, only the date is included.
  14595. When called with two universal prefix arguments, insert an active time stamp
  14596. with the current time without prompting the user."
  14597. (interactive "P")
  14598. (org-time-stamp arg 'inactive))
  14599. (defvar org-date-ovl (make-overlay 1 1))
  14600. (overlay-put org-date-ovl 'face 'org-date-selected)
  14601. (delete-overlay org-date-ovl)
  14602. (defvar org-ans1) ; dynamically scoped parameter
  14603. (defvar org-ans2) ; dynamically scoped parameter
  14604. (defvar org-plain-time-of-day-regexp) ; defined below
  14605. (defvar org-overriding-default-time nil) ; dynamically scoped
  14606. (defvar org-read-date-overlay nil)
  14607. (defvar org-dcst nil) ; dynamically scoped
  14608. (defvar org-read-date-history nil)
  14609. (defvar org-read-date-final-answer nil)
  14610. (defvar org-read-date-analyze-futurep nil)
  14611. (defvar org-read-date-analyze-forced-year nil)
  14612. (defvar org-read-date-inactive)
  14613. (defvar org-read-date-minibuffer-local-map
  14614. (let* ((map (make-sparse-keymap)))
  14615. (set-keymap-parent map minibuffer-local-map)
  14616. (org-defkey map (kbd ".")
  14617. (lambda () (interactive)
  14618. ;; Are we at the beginning of the prompt?
  14619. (if (looking-back "^[^:]+: "
  14620. (let ((inhibit-field-text-motion t))
  14621. (line-beginning-position)))
  14622. (org-eval-in-calendar '(calendar-goto-today))
  14623. (insert "."))))
  14624. (org-defkey map (kbd "C-.")
  14625. (lambda () (interactive)
  14626. (org-eval-in-calendar '(calendar-goto-today))))
  14627. (org-defkey map (kbd "M-S-<left>")
  14628. (lambda () (interactive)
  14629. (org-eval-in-calendar '(calendar-backward-month 1))))
  14630. (org-defkey map (kbd "ESC S-<left>")
  14631. (lambda () (interactive)
  14632. (org-eval-in-calendar '(calendar-backward-month 1))))
  14633. (org-defkey map (kbd "M-S-<right>")
  14634. (lambda () (interactive)
  14635. (org-eval-in-calendar '(calendar-forward-month 1))))
  14636. (org-defkey map (kbd "ESC S-<right>")
  14637. (lambda () (interactive)
  14638. (org-eval-in-calendar '(calendar-forward-month 1))))
  14639. (org-defkey map (kbd "M-S-<up>")
  14640. (lambda () (interactive)
  14641. (org-eval-in-calendar '(calendar-backward-year 1))))
  14642. (org-defkey map (kbd "ESC S-<up>")
  14643. (lambda () (interactive)
  14644. (org-eval-in-calendar '(calendar-backward-year 1))))
  14645. (org-defkey map (kbd "M-S-<down>")
  14646. (lambda () (interactive)
  14647. (org-eval-in-calendar '(calendar-forward-year 1))))
  14648. (org-defkey map (kbd "ESC S-<down>")
  14649. (lambda () (interactive)
  14650. (org-eval-in-calendar '(calendar-forward-year 1))))
  14651. (org-defkey map (kbd "S-<up>")
  14652. (lambda () (interactive)
  14653. (org-eval-in-calendar '(calendar-backward-week 1))))
  14654. (org-defkey map (kbd "S-<down>")
  14655. (lambda () (interactive)
  14656. (org-eval-in-calendar '(calendar-forward-week 1))))
  14657. (org-defkey map (kbd "S-<left>")
  14658. (lambda () (interactive)
  14659. (org-eval-in-calendar '(calendar-backward-day 1))))
  14660. (org-defkey map (kbd "S-<right>")
  14661. (lambda () (interactive)
  14662. (org-eval-in-calendar '(calendar-forward-day 1))))
  14663. (org-defkey map (kbd "!")
  14664. (lambda () (interactive)
  14665. (org-eval-in-calendar '(diary-view-entries))
  14666. (message "")))
  14667. (org-defkey map (kbd ">")
  14668. (lambda () (interactive)
  14669. (org-eval-in-calendar '(calendar-scroll-left 1))))
  14670. (org-defkey map (kbd "<")
  14671. (lambda () (interactive)
  14672. (org-eval-in-calendar '(calendar-scroll-right 1))))
  14673. (org-defkey map (kbd "C-v")
  14674. (lambda () (interactive)
  14675. (org-eval-in-calendar
  14676. '(calendar-scroll-left-three-months 1))))
  14677. (org-defkey map (kbd "M-v")
  14678. (lambda () (interactive)
  14679. (org-eval-in-calendar
  14680. '(calendar-scroll-right-three-months 1))))
  14681. map)
  14682. "Keymap for minibuffer commands when using `org-read-date'.")
  14683. (defvar org-def)
  14684. (defvar org-defdecode)
  14685. (defvar org-with-time)
  14686. (defvar calendar-setup) ; Dynamically scoped.
  14687. (defun org-read-date (&optional with-time to-time from-string prompt
  14688. default-time default-input inactive)
  14689. "Read a date, possibly a time, and make things smooth for the user.
  14690. The prompt will suggest to enter an ISO date, but you can also enter anything
  14691. which will at least partially be understood by `parse-time-string'.
  14692. Unrecognized parts of the date will default to the current day, month, year,
  14693. hour and minute. If this command is called to replace a timestamp at point,
  14694. or to enter the second timestamp of a range, the default time is taken
  14695. from the existing stamp. Furthermore, the command prefers the future,
  14696. so if you are giving a date where the year is not given, and the day-month
  14697. combination is already past in the current year, it will assume you
  14698. mean next year. For details, see the manual. A few examples:
  14699. 3-2-5 --> 2003-02-05
  14700. feb 15 --> currentyear-02-15
  14701. 2/15 --> currentyear-02-15
  14702. sep 12 9 --> 2009-09-12
  14703. 12:45 --> today 12:45
  14704. 22 sept 0:34 --> currentyear-09-22 0:34
  14705. 12 --> currentyear-currentmonth-12
  14706. Fri --> nearest Friday after today
  14707. -Tue --> last Tuesday
  14708. etc.
  14709. Furthermore you can specify a relative date by giving, as the *first* thing
  14710. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  14711. change in days weeks, months, years.
  14712. With a single plus or minus, the date is relative to today. With a double
  14713. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  14714. +4d --> four days from today
  14715. +4 --> same as above
  14716. +2w --> two weeks from today
  14717. ++5 --> five days from default date
  14718. The function understands only English month and weekday abbreviations.
  14719. While prompting, a calendar is popped up - you can also select the
  14720. date with the mouse (button 1). The calendar shows a period of three
  14721. months. To scroll it to other months, use the keys `>' and `<'.
  14722. If you don't like the calendar, turn it off with
  14723. (setq org-read-date-popup-calendar nil)
  14724. With optional argument TO-TIME, the date will immediately be converted
  14725. to an internal time.
  14726. With an optional argument WITH-TIME, the prompt will suggest to
  14727. also insert a time. Note that when WITH-TIME is not set, you can
  14728. still enter a time, and this function will inform the calling routine
  14729. about this change. The calling routine may then choose to change the
  14730. format used to insert the time stamp into the buffer to include the time.
  14731. With optional argument FROM-STRING, read from this string instead from
  14732. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  14733. the time/date that is used for everything that is not specified by the
  14734. user."
  14735. (require 'parse-time)
  14736. (let* ((org-with-time with-time)
  14737. (org-time-stamp-rounding-minutes
  14738. (if (equal org-with-time '(16))
  14739. '(0 0)
  14740. org-time-stamp-rounding-minutes))
  14741. (org-dcst org-display-custom-times)
  14742. (ct (org-current-time))
  14743. (org-def (or org-overriding-default-time default-time ct))
  14744. (org-defdecode (decode-time org-def))
  14745. (cur-frame (selected-frame))
  14746. (mouse-autoselect-window nil) ; Don't let the mouse jump
  14747. (calendar-setup
  14748. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  14749. (calendar-move-hook nil)
  14750. (calendar-view-diary-initially-flag nil)
  14751. (calendar-view-holidays-initially-flag nil)
  14752. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  14753. ;; Rationalize `org-def' and `org-defdecode', if required.
  14754. (when (< (nth 2 org-defdecode) org-extend-today-until)
  14755. (setf (nth 2 org-defdecode) -1)
  14756. (setf (nth 1 org-defdecode) 59)
  14757. (setq org-def (apply #'encode-time org-defdecode))
  14758. (setq org-defdecode (decode-time org-def)))
  14759. (let* ((timestr (format-time-string
  14760. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  14761. org-def))
  14762. (prompt (concat (if prompt (concat prompt " ") "")
  14763. (format "Date+time [%s]: " timestr))))
  14764. (cond
  14765. (from-string (setq ans from-string))
  14766. (org-read-date-popup-calendar
  14767. (save-excursion
  14768. (save-window-excursion
  14769. (calendar)
  14770. (when (eq calendar-setup 'calendar-only)
  14771. (setq cal-frame
  14772. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  14773. (select-frame cal-frame))
  14774. (org-eval-in-calendar '(setq cursor-type nil) t)
  14775. (unwind-protect
  14776. (progn
  14777. (calendar-forward-day (- (time-to-days org-def)
  14778. (calendar-absolute-from-gregorian
  14779. (calendar-current-date))))
  14780. (org-eval-in-calendar nil t)
  14781. (let* ((old-map (current-local-map))
  14782. (map (copy-keymap calendar-mode-map))
  14783. (minibuffer-local-map
  14784. (copy-keymap org-read-date-minibuffer-local-map)))
  14785. (org-defkey map (kbd "RET") 'org-calendar-select)
  14786. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  14787. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  14788. (unwind-protect
  14789. (progn
  14790. (use-local-map map)
  14791. (setq org-read-date-inactive inactive)
  14792. (add-hook 'post-command-hook 'org-read-date-display)
  14793. (setq org-ans0
  14794. (read-string prompt
  14795. default-input
  14796. 'org-read-date-history
  14797. nil))
  14798. ;; org-ans0: from prompt
  14799. ;; org-ans1: from mouse click
  14800. ;; org-ans2: from calendar motion
  14801. (setq ans
  14802. (concat org-ans0 " " (or org-ans1 org-ans2))))
  14803. (remove-hook 'post-command-hook 'org-read-date-display)
  14804. (use-local-map old-map)
  14805. (when org-read-date-overlay
  14806. (delete-overlay org-read-date-overlay)
  14807. (setq org-read-date-overlay nil)))))
  14808. (bury-buffer "*Calendar*")
  14809. (when cal-frame
  14810. (delete-frame cal-frame)
  14811. (select-frame-set-input-focus cur-frame))))))
  14812. (t ; Naked prompt only
  14813. (unwind-protect
  14814. (setq ans (read-string prompt default-input
  14815. 'org-read-date-history timestr))
  14816. (when org-read-date-overlay
  14817. (delete-overlay org-read-date-overlay)
  14818. (setq org-read-date-overlay nil))))))
  14819. (setq final (org-read-date-analyze ans org-def org-defdecode))
  14820. (when org-read-date-analyze-forced-year
  14821. (message "Year was forced into %s"
  14822. (if org-read-date-force-compatible-dates
  14823. "compatible range (1970-2037)"
  14824. "range representable on this machine"))
  14825. (ding))
  14826. ;; One round trip to get rid of 34th of August and stuff like that....
  14827. (setq final (decode-time (apply 'encode-time final)))
  14828. (setq org-read-date-final-answer ans)
  14829. (if to-time
  14830. (apply 'encode-time final)
  14831. (if (and (boundp 'org-time-was-given) org-time-was-given)
  14832. (format "%04d-%02d-%02d %02d:%02d"
  14833. (nth 5 final) (nth 4 final) (nth 3 final)
  14834. (nth 2 final) (nth 1 final))
  14835. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  14836. (defun org-read-date-display ()
  14837. "Display the current date prompt interpretation in the minibuffer."
  14838. (when org-read-date-display-live
  14839. (when org-read-date-overlay
  14840. (delete-overlay org-read-date-overlay))
  14841. (when (minibufferp (current-buffer))
  14842. (save-excursion
  14843. (end-of-line 1)
  14844. (while (not (equal (buffer-substring
  14845. (max (point-min) (- (point) 4)) (point))
  14846. " "))
  14847. (insert " ")))
  14848. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  14849. " " (or org-ans1 org-ans2)))
  14850. (org-end-time-was-given nil)
  14851. (f (org-read-date-analyze ans org-def org-defdecode))
  14852. (fmts (if org-dcst
  14853. org-time-stamp-custom-formats
  14854. org-time-stamp-formats))
  14855. (fmt (if (or org-with-time
  14856. (and (boundp 'org-time-was-given) org-time-was-given))
  14857. (cdr fmts)
  14858. (car fmts)))
  14859. (txt (format-time-string fmt (apply 'encode-time f)))
  14860. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  14861. (txt (concat "=> " txt)))
  14862. (when (and org-end-time-was-given
  14863. (string-match org-plain-time-of-day-regexp txt))
  14864. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  14865. org-end-time-was-given
  14866. (substring txt (match-end 0)))))
  14867. (when org-read-date-analyze-futurep
  14868. (setq txt (concat txt " (=>F)")))
  14869. (setq org-read-date-overlay
  14870. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  14871. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  14872. (defun org-read-date-analyze (ans def defdecode)
  14873. "Analyze the combined answer of the date prompt."
  14874. ;; FIXME: cleanup and comment
  14875. ;; Pass `current-time' result to `decode-time' (instead of calling
  14876. ;; without arguments) so that only `current-time' has to be
  14877. ;; overridden in tests.
  14878. (let ((org-def def)
  14879. (org-defdecode defdecode)
  14880. (nowdecode (decode-time (current-time)))
  14881. delta deltan deltaw deltadef year month day
  14882. hour minute second wday pm h2 m2 tl wday1
  14883. iso-year iso-weekday iso-week iso-date futurep kill-year)
  14884. (setq org-read-date-analyze-futurep nil
  14885. org-read-date-analyze-forced-year nil)
  14886. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  14887. (setq ans "+0"))
  14888. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  14889. (setq ans (replace-match "" t t ans)
  14890. deltan (car delta)
  14891. deltaw (nth 1 delta)
  14892. deltadef (nth 2 delta)))
  14893. ;; Check if there is an iso week date in there. If yes, store the
  14894. ;; info and postpone interpreting it until the rest of the parsing
  14895. ;; is done.
  14896. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  14897. (setq iso-year (when (match-end 1)
  14898. (org-small-year-to-year
  14899. (string-to-number (match-string 1 ans))))
  14900. iso-weekday (when (match-end 3)
  14901. (string-to-number (match-string 3 ans)))
  14902. iso-week (string-to-number (match-string 2 ans)))
  14903. (setq ans (replace-match "" t t ans)))
  14904. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  14905. (when (string-match
  14906. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  14907. (setq year (if (match-end 2)
  14908. (string-to-number (match-string 2 ans))
  14909. (progn (setq kill-year t)
  14910. (string-to-number (format-time-string "%Y"))))
  14911. month (string-to-number (match-string 3 ans))
  14912. day (string-to-number (match-string 4 ans)))
  14913. (setq year (org-small-year-to-year year))
  14914. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14915. t nil ans)))
  14916. ;; Help matching dotted european dates
  14917. (when (string-match
  14918. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  14919. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  14920. (setq kill-year t)
  14921. (string-to-number (format-time-string "%Y")))
  14922. day (string-to-number (match-string 1 ans))
  14923. month (string-to-number (match-string 2 ans))
  14924. ans (replace-match (format "%04d-%02d-%02d" year month day)
  14925. t nil ans)))
  14926. ;; Help matching american dates, like 5/30 or 5/30/7
  14927. (when (string-match
  14928. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  14929. (setq year (if (match-end 4)
  14930. (string-to-number (match-string 4 ans))
  14931. (progn (setq kill-year t)
  14932. (string-to-number (format-time-string "%Y"))))
  14933. month (string-to-number (match-string 1 ans))
  14934. day (string-to-number (match-string 2 ans)))
  14935. (setq year (org-small-year-to-year year))
  14936. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14937. t nil ans)))
  14938. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  14939. ;; If there is a time with am/pm, and *no* time without it, we convert
  14940. ;; so that matching will be successful.
  14941. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  14942. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  14943. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  14944. (setq hour (string-to-number (match-string 1 ans))
  14945. minute (if (match-end 3)
  14946. (string-to-number (match-string 3 ans))
  14947. 0)
  14948. pm (equal ?p
  14949. (string-to-char (downcase (match-string 4 ans)))))
  14950. (if (and (= hour 12) (not pm))
  14951. (setq hour 0)
  14952. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  14953. (setq ans (replace-match (format "%02d:%02d" hour minute)
  14954. t t ans))))
  14955. ;; Check if a time range is given as a duration
  14956. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  14957. (setq hour (string-to-number (match-string 1 ans))
  14958. h2 (+ hour (string-to-number (match-string 3 ans)))
  14959. minute (string-to-number (match-string 2 ans))
  14960. m2 (+ minute (if (match-end 5) (string-to-number
  14961. (match-string 5 ans))0)))
  14962. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  14963. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  14964. t t ans)))
  14965. ;; Check if there is a time range
  14966. (when (boundp 'org-end-time-was-given)
  14967. (setq org-time-was-given nil)
  14968. (when (and (string-match org-plain-time-of-day-regexp ans)
  14969. (match-end 8))
  14970. (setq org-end-time-was-given (match-string 8 ans))
  14971. (setq ans (concat (substring ans 0 (match-beginning 7))
  14972. (substring ans (match-end 7))))))
  14973. (setq tl (parse-time-string ans)
  14974. day (or (nth 3 tl) (nth 3 org-defdecode))
  14975. month
  14976. (cond ((nth 4 tl))
  14977. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  14978. ;; Day was specified. Make sure DAY+MONTH
  14979. ;; combination happens in the future.
  14980. ((nth 3 tl)
  14981. (setq futurep t)
  14982. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  14983. (nth 4 nowdecode)))
  14984. (t (nth 4 org-defdecode)))
  14985. year
  14986. (cond ((and (not kill-year) (nth 5 tl)))
  14987. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  14988. ;; Month was guessed in the future and is at least
  14989. ;; equal to NOWDECODE's. Fix year accordingly.
  14990. (futurep
  14991. (if (or (> month (nth 4 nowdecode))
  14992. (>= day (nth 3 nowdecode)))
  14993. (nth 5 nowdecode)
  14994. (1+ (nth 5 nowdecode))))
  14995. ;; Month was specified. Make sure MONTH+YEAR
  14996. ;; combination happens in the future.
  14997. ((nth 4 tl)
  14998. (setq futurep t)
  14999. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15000. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15001. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15002. (t (nth 5 nowdecode))))
  15003. (t (nth 5 org-defdecode)))
  15004. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15005. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15006. second (or (nth 0 tl) 0)
  15007. wday (nth 6 tl))
  15008. (when (and (eq org-read-date-prefer-future 'time)
  15009. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15010. (equal day (nth 3 nowdecode))
  15011. (equal month (nth 4 nowdecode))
  15012. (equal year (nth 5 nowdecode))
  15013. (nth 2 tl)
  15014. (or (< (nth 2 tl) (nth 2 nowdecode))
  15015. (and (= (nth 2 tl) (nth 2 nowdecode))
  15016. (nth 1 tl)
  15017. (< (nth 1 tl) (nth 1 nowdecode)))))
  15018. (setq day (1+ day)
  15019. futurep t))
  15020. ;; Special date definitions below
  15021. (cond
  15022. (iso-week
  15023. ;; There was an iso week
  15024. (require 'cal-iso)
  15025. (setq futurep nil)
  15026. (setq year (or iso-year year)
  15027. day (or iso-weekday wday 1)
  15028. wday nil ; to make sure that the trigger below does not match
  15029. iso-date (calendar-gregorian-from-absolute
  15030. (calendar-iso-to-absolute
  15031. (list iso-week day year))))
  15032. ; FIXME: Should we also push ISO weeks into the future?
  15033. ; (when (and org-read-date-prefer-future
  15034. ; (not iso-year)
  15035. ; (< (calendar-absolute-from-gregorian iso-date)
  15036. ; (time-to-days (current-time))))
  15037. ; (setq year (1+ year)
  15038. ; iso-date (calendar-gregorian-from-absolute
  15039. ; (calendar-iso-to-absolute
  15040. ; (list iso-week day year)))))
  15041. (setq month (car iso-date)
  15042. year (nth 2 iso-date)
  15043. day (nth 1 iso-date)))
  15044. (deltan
  15045. (setq futurep nil)
  15046. (unless deltadef
  15047. ;; Pass `current-time' result to `decode-time' (instead of
  15048. ;; calling without arguments) so that only `current-time' has
  15049. ;; to be overridden in tests.
  15050. (let ((now (decode-time (current-time))))
  15051. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15052. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15053. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15054. ((equal deltaw "m") (setq month (+ month deltan)))
  15055. ((equal deltaw "y") (setq year (+ year deltan)))))
  15056. ((and wday (not (nth 3 tl)))
  15057. ;; Weekday was given, but no day, so pick that day in the week
  15058. ;; on or after the derived date.
  15059. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15060. (unless (equal wday wday1)
  15061. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15062. (when (and (boundp 'org-time-was-given)
  15063. (nth 2 tl))
  15064. (setq org-time-was-given t))
  15065. (when (< year 100) (setq year (+ 2000 year)))
  15066. ;; Check of the date is representable
  15067. (if org-read-date-force-compatible-dates
  15068. (progn
  15069. (when (< year 1970)
  15070. (setq year 1970 org-read-date-analyze-forced-year t))
  15071. (when (> year 2037)
  15072. (setq year 2037 org-read-date-analyze-forced-year t)))
  15073. (condition-case nil
  15074. (ignore (encode-time second minute hour day month year))
  15075. (error
  15076. (setq year (nth 5 org-defdecode))
  15077. (setq org-read-date-analyze-forced-year t))))
  15078. (setq org-read-date-analyze-futurep futurep)
  15079. (list second minute hour day month year)))
  15080. (defvar parse-time-weekdays)
  15081. (defun org-read-date-get-relative (s today default)
  15082. "Check string S for special relative date string.
  15083. TODAY and DEFAULT are internal times, for today and for a default.
  15084. Return shift list (N what def-flag)
  15085. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15086. N is the number of WHATs to shift.
  15087. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15088. the DEFAULT date rather than TODAY."
  15089. (require 'parse-time)
  15090. (when (and
  15091. (string-match
  15092. (concat
  15093. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15094. "\\([0-9]+\\)?"
  15095. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15096. "\\([ \t]\\|$\\)") s)
  15097. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15098. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15099. (string-to-char (substring (match-string 1 s) -1))
  15100. ?+))
  15101. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15102. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15103. (what (if (match-end 3) (match-string 3 s) "d"))
  15104. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15105. (date (if rel default today))
  15106. (wday (nth 6 (decode-time date)))
  15107. delta)
  15108. (if wday1
  15109. (progn
  15110. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15111. (when (= delta 0) (setq delta 7))
  15112. (when (= dir ?-)
  15113. (setq delta (- delta 7))
  15114. (when (= delta 0) (setq delta -7)))
  15115. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15116. (list delta "d" rel))
  15117. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15118. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15119. "Turn a user-specified date into the internal representation.
  15120. The internal representation needed by the calendar is (month day year).
  15121. This is a wrapper to handle the brain-dead convention in calendar that
  15122. user function argument order change dependent on argument order."
  15123. (pcase calendar-date-style
  15124. (`american (list arg1 arg2 arg3))
  15125. (`european (list arg2 arg1 arg3))
  15126. (`iso (list arg2 arg3 arg1))))
  15127. (defun org-eval-in-calendar (form &optional keepdate)
  15128. "Eval FORM in the calendar window and return to current window.
  15129. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15130. (let ((sf (selected-frame))
  15131. (sw (selected-window)))
  15132. (select-window (get-buffer-window "*Calendar*" t))
  15133. (eval form)
  15134. (when (and (not keepdate) (calendar-cursor-to-date))
  15135. (let* ((date (calendar-cursor-to-date))
  15136. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15137. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15138. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15139. (select-window sw)
  15140. (select-frame-set-input-focus sf)))
  15141. (defun org-calendar-select ()
  15142. "Return to `org-read-date' with the date currently selected.
  15143. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15144. (interactive)
  15145. (when (calendar-cursor-to-date)
  15146. (let* ((date (calendar-cursor-to-date))
  15147. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15148. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15149. (when (active-minibuffer-window) (exit-minibuffer))))
  15150. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15151. "Insert a date stamp for the date given by the internal TIME.
  15152. See `format-time-string' for the format of TIME.
  15153. WITH-HM means use the stamp format that includes the time of the day.
  15154. INACTIVE means use square brackets instead of angular ones, so that the
  15155. stamp will not contribute to the agenda.
  15156. PRE and POST are optional strings to be inserted before and after the
  15157. stamp.
  15158. The command returns the inserted time stamp."
  15159. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15160. stamp)
  15161. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15162. (insert-before-markers (or pre ""))
  15163. (when (listp extra)
  15164. (setq extra (car extra))
  15165. (if (and (stringp extra)
  15166. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15167. (setq extra (format "-%02d:%02d"
  15168. (string-to-number (match-string 1 extra))
  15169. (string-to-number (match-string 2 extra))))
  15170. (setq extra nil)))
  15171. (when extra
  15172. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15173. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15174. (insert-before-markers (or post ""))
  15175. (setq org-last-inserted-timestamp stamp)))
  15176. (defun org-toggle-time-stamp-overlays ()
  15177. "Toggle the use of custom time stamp formats."
  15178. (interactive)
  15179. (setq org-display-custom-times (not org-display-custom-times))
  15180. (unless org-display-custom-times
  15181. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15182. (while (setq p (next-single-property-change p 'display))
  15183. (when (and (get-text-property p 'display)
  15184. (eq (get-text-property p 'face) 'org-date))
  15185. (remove-text-properties
  15186. p (setq p (next-single-property-change p 'display))
  15187. '(display t))))
  15188. (set-buffer-modified-p bmp)))
  15189. (org-restart-font-lock)
  15190. (setq org-table-may-need-update t)
  15191. (if org-display-custom-times
  15192. (message "Time stamps are overlaid with custom format")
  15193. (message "Time stamp overlays removed")))
  15194. (defun org-display-custom-time (beg end)
  15195. "Overlay modified time stamp format over timestamp between BEG and END."
  15196. (let* ((ts (buffer-substring beg end))
  15197. t1 with-hm tf time str (off 0))
  15198. (save-match-data
  15199. (setq t1 (org-parse-time-string ts t))
  15200. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15201. (setq off (- (match-end 0) (match-beginning 0)))))
  15202. (setq end (- end off))
  15203. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  15204. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15205. time (org-fix-decoded-time t1)
  15206. str (org-add-props
  15207. (format-time-string
  15208. (substring tf 1 -1) (apply 'encode-time time))
  15209. nil 'mouse-face 'highlight))
  15210. (put-text-property beg end 'display str)))
  15211. (defun org-fix-decoded-time (time)
  15212. "Set 0 instead of nil for the first 6 elements of time.
  15213. Don't touch the rest."
  15214. (let ((n 0))
  15215. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15216. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15217. "Difference between TIMESTAMP-STRING and now in days.
  15218. If SECONDS is non-nil, return the difference in seconds."
  15219. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15220. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15221. (funcall fdiff (current-time)))))
  15222. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15223. "Is the time in TIMESTAMP-STRING close to the current date?"
  15224. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15225. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15226. (not (org-entry-is-done-p))))
  15227. (defun org-get-wdays (ts &optional delay zero-delay)
  15228. "Get the deadline lead time appropriate for timestring TS.
  15229. When DELAY is non-nil, get the delay time for scheduled items
  15230. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15231. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15232. don't try to find the delay cookie in the scheduled timestamp."
  15233. (let ((tv (if delay org-scheduled-delay-days
  15234. org-deadline-warning-days)))
  15235. (cond
  15236. ((or (and delay (< tv 0))
  15237. (and delay zero-delay (<= tv 0))
  15238. (and (not delay) (<= tv 0)))
  15239. ;; Enforce this value no matter what
  15240. (- tv))
  15241. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15242. ;; lead time is specified.
  15243. (floor (* (string-to-number (match-string 1 ts))
  15244. (cdr (assoc (match-string 2 ts)
  15245. '(("d" . 1) ("w" . 7)
  15246. ("m" . 30.4) ("y" . 365.25)
  15247. ("h" . 0.041667)))))))
  15248. ;; go for the default.
  15249. (t tv))))
  15250. (defun org-calendar-select-mouse (ev)
  15251. "Return to `org-read-date' with the date currently selected.
  15252. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15253. (interactive "e")
  15254. (mouse-set-point ev)
  15255. (when (calendar-cursor-to-date)
  15256. (let* ((date (calendar-cursor-to-date))
  15257. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15258. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15259. (when (active-minibuffer-window) (exit-minibuffer))))
  15260. (defun org-check-deadlines (ndays)
  15261. "Check if there are any deadlines due or past due.
  15262. A deadline is considered due if it happens within `org-deadline-warning-days'
  15263. days from today's date. If the deadline appears in an entry marked DONE,
  15264. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15265. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15266. are shown."
  15267. (interactive "P")
  15268. (let* ((org-warn-days
  15269. (cond
  15270. ((equal ndays '(4)) 100000)
  15271. (ndays (prefix-numeric-value ndays))
  15272. (t (abs org-deadline-warning-days))))
  15273. (case-fold-search nil)
  15274. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15275. (callback
  15276. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15277. (message "%d deadlines past-due or due within %d days"
  15278. (org-occur regexp nil callback)
  15279. org-warn-days)))
  15280. (defsubst org-re-timestamp (type)
  15281. "Return a regexp for timestamp TYPE.
  15282. Allowed values for TYPE are:
  15283. all: all timestamps
  15284. active: only active timestamps (<...>)
  15285. inactive: only inactive timestamps ([...])
  15286. scheduled: only scheduled timestamps
  15287. deadline: only deadline timestamps
  15288. closed: only closed time-stamps
  15289. When TYPE is nil, fall back on returning a regexp that matches
  15290. both scheduled and deadline timestamps."
  15291. (cl-case type
  15292. (all org-ts-regexp-both)
  15293. (active org-ts-regexp)
  15294. (inactive org-ts-regexp-inactive)
  15295. (scheduled org-scheduled-time-regexp)
  15296. (deadline org-deadline-time-regexp)
  15297. (closed org-closed-time-regexp)
  15298. (otherwise
  15299. (concat "\\<"
  15300. (regexp-opt (list org-deadline-string org-scheduled-string))
  15301. " *<\\([^>]+\\)>"))))
  15302. (defun org-check-before-date (d)
  15303. "Check if there are deadlines or scheduled entries before date D."
  15304. (interactive (list (org-read-date)))
  15305. (let* ((case-fold-search nil)
  15306. (regexp (org-re-timestamp org-ts-type))
  15307. (ts-type org-ts-type)
  15308. (callback
  15309. (lambda ()
  15310. (let ((match (match-string 1)))
  15311. (and (if (memq ts-type '(active inactive all))
  15312. (eq (org-element-type (save-excursion
  15313. (backward-char)
  15314. (org-element-context)))
  15315. 'timestamp)
  15316. (org-at-planning-p))
  15317. (time-less-p
  15318. (org-time-string-to-time match)
  15319. (org-time-string-to-time d)))))))
  15320. (message "%d entries before %s"
  15321. (org-occur regexp nil callback)
  15322. d)))
  15323. (defun org-check-after-date (d)
  15324. "Check if there are deadlines or scheduled entries after date D."
  15325. (interactive (list (org-read-date)))
  15326. (let* ((case-fold-search nil)
  15327. (regexp (org-re-timestamp org-ts-type))
  15328. (ts-type org-ts-type)
  15329. (callback
  15330. (lambda ()
  15331. (let ((match (match-string 1)))
  15332. (and (if (memq ts-type '(active inactive all))
  15333. (eq (org-element-type (save-excursion
  15334. (backward-char)
  15335. (org-element-context)))
  15336. 'timestamp)
  15337. (org-at-planning-p))
  15338. (not (time-less-p
  15339. (org-time-string-to-time match)
  15340. (org-time-string-to-time d))))))))
  15341. (message "%d entries after %s"
  15342. (org-occur regexp nil callback)
  15343. d)))
  15344. (defun org-check-dates-range (start-date end-date)
  15345. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15346. (interactive (list (org-read-date nil nil nil "Range starts")
  15347. (org-read-date nil nil nil "Range end")))
  15348. (let ((case-fold-search nil)
  15349. (regexp (org-re-timestamp org-ts-type))
  15350. (callback
  15351. (let ((type org-ts-type))
  15352. (lambda ()
  15353. (let ((match (match-string 1)))
  15354. (and
  15355. (if (memq type '(active inactive all))
  15356. (eq (org-element-type (save-excursion
  15357. (backward-char)
  15358. (org-element-context)))
  15359. 'timestamp)
  15360. (org-at-planning-p))
  15361. (not (time-less-p
  15362. (org-time-string-to-time match)
  15363. (org-time-string-to-time start-date)))
  15364. (time-less-p
  15365. (org-time-string-to-time match)
  15366. (org-time-string-to-time end-date))))))))
  15367. (message "%d entries between %s and %s"
  15368. (org-occur regexp nil callback) start-date end-date)))
  15369. (defun org-evaluate-time-range (&optional to-buffer)
  15370. "Evaluate a time range by computing the difference between start and end.
  15371. Normally the result is just printed in the echo area, but with prefix arg
  15372. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15373. If the time range is actually in a table, the result is inserted into the
  15374. next column.
  15375. For time difference computation, a year is assumed to be exactly 365
  15376. days in order to avoid rounding problems."
  15377. (interactive "P")
  15378. (or
  15379. (org-clock-update-time-maybe)
  15380. (save-excursion
  15381. (unless (org-at-date-range-p t)
  15382. (goto-char (point-at-bol))
  15383. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15384. (unless (org-at-date-range-p t)
  15385. (user-error "Not at a time-stamp range, and none found in current line")))
  15386. (let* ((ts1 (match-string 1))
  15387. (ts2 (match-string 2))
  15388. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15389. (match-end (match-end 0))
  15390. (time1 (org-time-string-to-time ts1))
  15391. (time2 (org-time-string-to-time ts2))
  15392. (t1 (float-time time1))
  15393. (t2 (float-time time2))
  15394. (diff (abs (- t2 t1)))
  15395. (negative (< (- t2 t1) 0))
  15396. ;; (ys (floor (* 365 24 60 60)))
  15397. (ds (* 24 60 60))
  15398. (hs (* 60 60))
  15399. (fy "%dy %dd %02d:%02d")
  15400. (fy1 "%dy %dd")
  15401. (fd "%dd %02d:%02d")
  15402. (fd1 "%dd")
  15403. (fh "%02d:%02d")
  15404. y d h m align)
  15405. (if havetime
  15406. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15407. y 0
  15408. d (floor (/ diff ds)) diff (mod diff ds)
  15409. h (floor (/ diff hs)) diff (mod diff hs)
  15410. m (floor (/ diff 60)))
  15411. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15412. y 0
  15413. d (floor (+ (/ diff ds) 0.5))
  15414. h 0 m 0))
  15415. (if (not to-buffer)
  15416. (message "%s" (org-make-tdiff-string y d h m))
  15417. (if (org-at-table-p)
  15418. (progn
  15419. (goto-char match-end)
  15420. (setq align t)
  15421. (and (looking-at " *|") (goto-char (match-end 0))))
  15422. (goto-char match-end))
  15423. (when (looking-at
  15424. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  15425. (replace-match ""))
  15426. (when negative (insert " -"))
  15427. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  15428. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  15429. (insert " " (format fh h m))))
  15430. (when align (org-table-align))
  15431. (message "Time difference inserted")))))
  15432. (defun org-make-tdiff-string (y d h m)
  15433. (let ((fmt "")
  15434. (l nil))
  15435. (when (> y 0)
  15436. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  15437. (push y l))
  15438. (when (> d 0)
  15439. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  15440. (push d l))
  15441. (when (> h 0)
  15442. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  15443. (push h l))
  15444. (when (> m 0)
  15445. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  15446. (push m l))
  15447. (apply 'format fmt (nreverse l))))
  15448. (defun org-time-string-to-time (s)
  15449. "Convert timestamp string S into internal time."
  15450. (apply #'encode-time (org-parse-time-string s)))
  15451. (defun org-time-string-to-seconds (s)
  15452. "Convert a timestamp string S into a number of seconds."
  15453. (float-time (org-time-string-to-time s)))
  15454. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  15455. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  15456. "Convert time stamp S to an absolute day number.
  15457. If DAYNR in non-nil, and there is a specifier for a cyclic time
  15458. stamp, get the closest date to DAYNR. If PREFER is
  15459. `past' (respectively `future') return a date past (respectively
  15460. after) or equal to DAYNR.
  15461. POS is the location of time stamp S, as a buffer position in
  15462. BUFFER.
  15463. Diary sexp timestamps are matched against DAYNR, when non-nil.
  15464. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  15465. signaled."
  15466. (cond
  15467. ((string-match "\\`%%\\((.*)\\)" s)
  15468. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  15469. ;; only able to match individual dates. If it fails, raise an
  15470. ;; error.
  15471. (if (and daynr
  15472. (org-diary-sexp-entry
  15473. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  15474. daynr
  15475. (signal 'org-diary-sexp-no-match (list s))))
  15476. (daynr (org-closest-date s daynr prefer))
  15477. (t (time-to-days
  15478. (condition-case errdata
  15479. (apply #'encode-time (org-parse-time-string s))
  15480. (error (error "Bad timestamp `%s'%s\nError was: %s"
  15481. s
  15482. (if (not (and buffer pos)) ""
  15483. (format-message " at %d in buffer `%s'" pos buffer))
  15484. (cdr errdata))))))))
  15485. (defun org-days-to-iso-week (days)
  15486. "Return the iso week number."
  15487. (require 'cal-iso)
  15488. (car (calendar-iso-from-absolute days)))
  15489. (defun org-small-year-to-year (year)
  15490. "Convert 2-digit years into 4-digit years.
  15491. YEAR is expanded into one of the 30 next years, if possible, or
  15492. into a past one. Any year larger than 99 is returned unchanged."
  15493. (if (>= year 100) year
  15494. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  15495. (century (/ current 100))
  15496. (offset (- year (% current 100))))
  15497. (cond ((> offset 30) (+ (* (1- century) 100) year))
  15498. ((> offset -70) (+ (* century 100) year))
  15499. (t (+ (* (1+ century) 100) year))))))
  15500. (defun org-time-from-absolute (d)
  15501. "Return the time corresponding to date D.
  15502. D may be an absolute day number, or a calendar-type list (month day year)."
  15503. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  15504. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  15505. (defvar org-agenda-current-date)
  15506. (defun org-calendar-holiday ()
  15507. "List of holidays, for Diary display in Org mode."
  15508. (require 'holidays)
  15509. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  15510. (and hl (mapconcat #'identity hl "; "))))
  15511. (defun org-diary-sexp-entry (sexp entry d)
  15512. "Process a SEXP diary ENTRY for date D."
  15513. (require 'diary-lib)
  15514. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  15515. ;; dynamically.
  15516. (let* ((sexp `(let ((entry ,entry)
  15517. (date ',d))
  15518. ,(car (read-from-string sexp))))
  15519. (result (if calendar-debug-sexp (eval sexp)
  15520. (condition-case nil
  15521. (eval sexp)
  15522. (error
  15523. (beep)
  15524. (message "Bad sexp at line %d in %s: %s"
  15525. (org-current-line)
  15526. (buffer-file-name) sexp)
  15527. (sleep-for 2))))))
  15528. (cond ((stringp result) (split-string result "; "))
  15529. ((and (consp result)
  15530. (not (consp (cdr result)))
  15531. (stringp (cdr result))) (cdr result))
  15532. ((and (consp result)
  15533. (stringp (car result))) result)
  15534. (result entry))))
  15535. (defun org-diary-to-ical-string (frombuf)
  15536. "Get iCalendar entries from diary entries in buffer FROMBUF.
  15537. This uses the icalendar.el library."
  15538. (let* ((tmpdir temporary-file-directory)
  15539. (tmpfile (make-temp-name
  15540. (expand-file-name "orgics" tmpdir)))
  15541. buf rtn b e)
  15542. (with-current-buffer frombuf
  15543. (icalendar-export-region (point-min) (point-max) tmpfile)
  15544. (setq buf (find-buffer-visiting tmpfile))
  15545. (set-buffer buf)
  15546. (goto-char (point-min))
  15547. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  15548. (setq b (match-beginning 0)))
  15549. (goto-char (point-max))
  15550. (when (re-search-backward "^END:VEVENT" nil t)
  15551. (setq e (match-end 0)))
  15552. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  15553. (kill-buffer buf)
  15554. (delete-file tmpfile)
  15555. rtn))
  15556. (defun org-closest-date (start current prefer)
  15557. "Return closest date to CURRENT starting from START.
  15558. CURRENT and START are both time stamps.
  15559. When PREFER is `past', return a date that is either CURRENT or
  15560. past. When PREFER is `future', return a date that is either
  15561. CURRENT or future.
  15562. Only time stamps with a repeater are modified. Any other time
  15563. stamp stay unchanged. In any case, return value is an absolute
  15564. day number."
  15565. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  15566. ;; No repeater. Do not shift time stamp.
  15567. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15568. (let ((value (string-to-number (match-string 1 start)))
  15569. (type (match-string 2 start)))
  15570. (if (= 0 value)
  15571. ;; Repeater with a 0-value is considered as void.
  15572. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15573. (let* ((base (org-date-to-gregorian start))
  15574. (target (org-date-to-gregorian current))
  15575. (sday (calendar-absolute-from-gregorian base))
  15576. (cday (calendar-absolute-from-gregorian target))
  15577. n1 n2)
  15578. ;; If START is already past CURRENT, just return START.
  15579. (if (<= cday sday) sday
  15580. ;; Compute closest date before (N1) and closest date past
  15581. ;; (N2) CURRENT.
  15582. (pcase type
  15583. ("h"
  15584. (let ((missing-hours
  15585. (mod (+ (- (* 24 (- cday sday))
  15586. (nth 2 (org-parse-time-string start)))
  15587. org-extend-today-until)
  15588. value)))
  15589. (setf n1 (if (= missing-hours 0) cday
  15590. (- cday (1+ (/ missing-hours 24)))))
  15591. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  15592. ((or "d" "w")
  15593. (let ((value (if (equal type "w") (* 7 value) value)))
  15594. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  15595. (setf n2 (+ n1 value))))
  15596. ("m"
  15597. (let* ((add-months
  15598. (lambda (d n)
  15599. ;; Add N months to gregorian date D, i.e.,
  15600. ;; a list (MONTH DAY YEAR). Return a valid
  15601. ;; gregorian date.
  15602. (let ((m (+ (nth 0 d) n)))
  15603. (list (mod m 12)
  15604. (nth 1 d)
  15605. (+ (/ m 12) (nth 2 d))))))
  15606. (months ; Complete months to TARGET.
  15607. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  15608. (- (nth 0 target) (nth 0 base))
  15609. ;; If START's day is greater than
  15610. ;; TARGET's, remove incomplete month.
  15611. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  15612. value)
  15613. value))
  15614. (before (funcall add-months base months)))
  15615. (setf n1 (calendar-absolute-from-gregorian before))
  15616. (setf n2
  15617. (calendar-absolute-from-gregorian
  15618. (funcall add-months before value)))))
  15619. (_
  15620. (let* ((d (nth 1 base))
  15621. (m (nth 0 base))
  15622. (y (nth 2 base))
  15623. (years ; Complete years to TARGET.
  15624. (* (/ (- (nth 2 target)
  15625. y
  15626. ;; If START's month and day are
  15627. ;; greater than TARGET's, remove
  15628. ;; incomplete year.
  15629. (if (or (> (nth 0 target) m)
  15630. (and (= (nth 0 target) m)
  15631. (> (nth 1 target) d)))
  15632. 0
  15633. 1))
  15634. value)
  15635. value))
  15636. (before (list m d (+ y years))))
  15637. (setf n1 (calendar-absolute-from-gregorian before))
  15638. (setf n2 (calendar-absolute-from-gregorian
  15639. (list m d (+ (nth 2 before) value)))))))
  15640. ;; Handle PREFER parameter, if any.
  15641. (cond
  15642. ((eq prefer 'past) (if (= cday n2) n2 n1))
  15643. ((eq prefer 'future) (if (= cday n1) n1 n2))
  15644. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  15645. (defun org-date-to-gregorian (d)
  15646. "Turn any specification of date D into a Gregorian date for the calendar."
  15647. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  15648. ((and (listp d) (= (length d) 3)) d)
  15649. ((stringp d)
  15650. (let ((d (org-parse-time-string d)))
  15651. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  15652. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  15653. (defun org-timestamp-up (&optional arg)
  15654. "Increase the date item at the cursor by one.
  15655. If the cursor is on the year, change the year. If it is on the month,
  15656. the day or the time, change that. If the cursor is on the enclosing
  15657. bracket, change the timestamp type.
  15658. With prefix ARG, change by that many units."
  15659. (interactive "p")
  15660. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  15661. (defun org-timestamp-down (&optional arg)
  15662. "Decrease the date item at the cursor by one.
  15663. If the cursor is on the year, change the year. If it is on the month,
  15664. the day or the time, change that. If the cursor is on the enclosing
  15665. bracket, change the timestamp type.
  15666. With prefix ARG, change by that many units."
  15667. (interactive "p")
  15668. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  15669. (defun org-timestamp-up-day (&optional arg)
  15670. "Increase the date in the time stamp by one day.
  15671. With prefix ARG, change that many days."
  15672. (interactive "p")
  15673. (if (and (not (org-at-timestamp-p 'lax))
  15674. (org-at-heading-p))
  15675. (org-todo 'up)
  15676. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  15677. (defun org-timestamp-down-day (&optional arg)
  15678. "Decrease the date in the time stamp by one day.
  15679. With prefix ARG, change that many days."
  15680. (interactive "p")
  15681. (if (and (not (org-at-timestamp-p 'lax))
  15682. (org-at-heading-p))
  15683. (org-todo 'down)
  15684. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  15685. (defun org-at-timestamp-p (&optional extended)
  15686. "Non-nil if point is inside a timestamp.
  15687. By default, the function only consider syntactically valid active
  15688. timestamps. However, the caller may have a broader definition
  15689. for timestamps. As a consequence, optional argument EXTENDED can
  15690. be set to the following values
  15691. `inactive'
  15692. Include also syntactically valid inactive timestamps.
  15693. `agenda'
  15694. Include timestamps allowed in Agenda, i.e., those in
  15695. properties drawers, planning lines and clock lines.
  15696. `lax'
  15697. Ignore context. The function matches any part of the
  15698. document looking like a timestamp. This includes comments,
  15699. example blocks...
  15700. For backward-compatibility with Org 9.0, every other non-nil
  15701. value is equivalent to `inactive'.
  15702. When at a timestamp, return the position of the point as a symbol
  15703. among `bracket', `after', `year', `month', `hour', `minute',
  15704. `day' or a number of character from the last know part of the
  15705. time stamp.
  15706. When matching, the match groups are the following:
  15707. group 1: year
  15708. group 2: month
  15709. group 3: day number
  15710. group 4: day name
  15711. group 5: hours, if any
  15712. group 6: minutes, if any"
  15713. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  15714. (pos (point))
  15715. (match?
  15716. (let ((boundaries (org-in-regexp regexp)))
  15717. (save-match-data
  15718. (cond ((null boundaries) nil)
  15719. ((eq extended 'lax) t)
  15720. (t
  15721. (or (and (eq extended 'agenda)
  15722. (or (org-at-planning-p)
  15723. (org-at-property-p)
  15724. (and (bound-and-true-p
  15725. org-agenda-include-inactive-timestamps)
  15726. (org-at-clock-log-p))))
  15727. (eq 'timestamp
  15728. (save-excursion
  15729. (when (= pos (cdr boundaries)) (forward-char -1))
  15730. (org-element-type (org-element-context)))))))))))
  15731. (cond
  15732. ((not match?) nil)
  15733. ((= pos (match-beginning 0)) 'bracket)
  15734. ;; Distinguish location right before the closing bracket from
  15735. ;; right after it.
  15736. ((= pos (1- (match-end 0))) 'bracket)
  15737. ((= pos (match-end 0)) 'after)
  15738. ((org-pos-in-match-range pos 2) 'year)
  15739. ((org-pos-in-match-range pos 3) 'month)
  15740. ((org-pos-in-match-range pos 7) 'hour)
  15741. ((org-pos-in-match-range pos 8) 'minute)
  15742. ((or (org-pos-in-match-range pos 4)
  15743. (org-pos-in-match-range pos 5)) 'day)
  15744. ((and (> pos (or (match-end 8) (match-end 5)))
  15745. (< pos (match-end 0)))
  15746. (- pos (or (match-end 8) (match-end 5))))
  15747. (t 'day))))
  15748. (defun org-toggle-timestamp-type ()
  15749. "Toggle the type (<active> or [inactive]) of a time stamp."
  15750. (interactive)
  15751. (when (org-at-timestamp-p 'lax)
  15752. (let ((beg (match-beginning 0)) (end (match-end 0))
  15753. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  15754. (save-excursion
  15755. (goto-char beg)
  15756. (while (re-search-forward "[][<>]" end t)
  15757. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  15758. t t)))
  15759. (message "Timestamp is now %sactive"
  15760. (if (equal (char-after beg) ?<) "" "in")))))
  15761. (defun org-at-clock-log-p ()
  15762. "Non-nil if point is on a clock log line."
  15763. (and (org-match-line org-clock-line-re)
  15764. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  15765. (defvar org-clock-history) ; defined in org-clock.el
  15766. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  15767. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  15768. "Change the date in the time stamp at point.
  15769. The date will be changed by N times WHAT. WHAT can be `day', `month',
  15770. `year', `minute', `second'. If WHAT is not given, the cursor position
  15771. in the timestamp determines what will be changed.
  15772. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  15773. (let ((origin (point))
  15774. (timestamp? (org-at-timestamp-p 'lax))
  15775. origin-cat
  15776. with-hm inactive
  15777. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  15778. extra rem
  15779. ts time time0 fixnext clrgx)
  15780. (unless timestamp? (user-error "Not at a timestamp"))
  15781. (if (and (not what) (eq timestamp? 'bracket))
  15782. (org-toggle-timestamp-type)
  15783. ;; Point isn't on brackets. Remember the part of the time-stamp
  15784. ;; the point was in. Indeed, size of time-stamps may change,
  15785. ;; but point must be kept in the same category nonetheless.
  15786. (setq origin-cat timestamp?)
  15787. (when (and (not what) (not (eq timestamp? 'day))
  15788. org-display-custom-times
  15789. (get-text-property (point) 'display)
  15790. (not (get-text-property (1- (point)) 'display)))
  15791. (setq timestamp? 'day))
  15792. (setq timestamp? (or what timestamp?)
  15793. inactive (= (char-after (match-beginning 0)) ?\[)
  15794. ts (match-string 0))
  15795. (replace-match "")
  15796. (when (string-match
  15797. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  15798. ts)
  15799. (setq extra (match-string 1 ts))
  15800. (when suppress-tmp-delay
  15801. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  15802. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  15803. (setq with-hm t))
  15804. (setq time0 (org-parse-time-string ts))
  15805. (when (and updown
  15806. (eq timestamp? 'minute)
  15807. (not current-prefix-arg))
  15808. ;; This looks like s-up and s-down. Change by one rounding step.
  15809. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  15810. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  15811. (setcar (cdr time0) (+ (nth 1 time0)
  15812. (if (> n 0) (- rem) (- dm rem))))))
  15813. (setq time
  15814. (apply #'encode-time
  15815. (or (car time0) 0)
  15816. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  15817. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  15818. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  15819. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  15820. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  15821. (nthcdr 6 time0)))
  15822. (when (and (memq timestamp? '(hour minute))
  15823. extra
  15824. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  15825. (setq extra (org-modify-ts-extra
  15826. extra
  15827. (if (eq timestamp? 'hour) 2 5)
  15828. n dm)))
  15829. (when (integerp timestamp?)
  15830. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  15831. (when (eq what 'calendar)
  15832. (let ((cal-date (org-get-date-from-calendar)))
  15833. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  15834. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  15835. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  15836. (setcar time0 (or (car time0) 0))
  15837. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  15838. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  15839. (setq time (apply 'encode-time time0))))
  15840. ;; Insert the new time-stamp, and ensure point stays in the same
  15841. ;; category as before (i.e. not after the last position in that
  15842. ;; category).
  15843. (let ((pos (point)))
  15844. ;; Stay before inserted string. `save-excursion' is of no use.
  15845. (setq org-last-changed-timestamp
  15846. (org-insert-time-stamp time with-hm inactive nil nil extra))
  15847. (goto-char pos))
  15848. (save-match-data
  15849. (looking-at org-ts-regexp3)
  15850. (goto-char
  15851. (pcase origin-cat
  15852. ;; `day' category ends before `hour' if any, or at the end
  15853. ;; of the day name.
  15854. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  15855. (`hour (min (match-end 7) origin))
  15856. (`minute (min (1- (match-end 8)) origin))
  15857. ((pred integerp) (min (1- (match-end 0)) origin))
  15858. ;; Point was right after the time-stamp. However, the
  15859. ;; time-stamp length might have changed, so refer to
  15860. ;; (match-end 0) instead.
  15861. (`after (match-end 0))
  15862. ;; `year' and `month' have both fixed size: point couldn't
  15863. ;; have moved into another part.
  15864. (_ origin))))
  15865. ;; Update clock if on a CLOCK line.
  15866. (org-clock-update-time-maybe)
  15867. ;; Maybe adjust the closest clock in `org-clock-history'
  15868. (when org-clock-adjust-closest
  15869. (if (not (and (org-at-clock-log-p)
  15870. (< 1 (length (delq nil (mapcar 'marker-position
  15871. org-clock-history))))))
  15872. (message "No clock to adjust")
  15873. (cond ((save-excursion ; fix previous clock?
  15874. (re-search-backward org-ts-regexp0 nil t)
  15875. (looking-back (concat org-clock-string " \\[")
  15876. (line-beginning-position)))
  15877. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  15878. ((save-excursion ; fix next clock?
  15879. (re-search-backward org-ts-regexp0 nil t)
  15880. (looking-at (concat org-ts-regexp0 "\\] =>")))
  15881. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  15882. (save-window-excursion
  15883. ;; Find closest clock to point, adjust the previous/next one in history
  15884. (let* ((p (save-excursion (org-back-to-heading t)))
  15885. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  15886. (clfixnth
  15887. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  15888. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  15889. (if (not clfixpos)
  15890. (message "No clock to adjust")
  15891. (save-excursion
  15892. (org-goto-marker-or-bmk clfixpos)
  15893. (org-show-subtree)
  15894. (when (re-search-forward clrgx nil t)
  15895. (goto-char (match-beginning 1))
  15896. (let (org-clock-adjust-closest)
  15897. (org-timestamp-change n timestamp? updown))
  15898. (message "Clock adjusted in %s for heading: %s"
  15899. (file-name-nondirectory (buffer-file-name))
  15900. (org-get-heading t t)))))))))
  15901. ;; Try to recenter the calendar window, if any.
  15902. (when (and org-calendar-follow-timestamp-change
  15903. (get-buffer-window "*Calendar*" t)
  15904. (memq timestamp? '(day month year)))
  15905. (org-recenter-calendar (time-to-days time))))))
  15906. (defun org-modify-ts-extra (s pos n dm)
  15907. "Change the different parts of the lead-time and repeat fields in timestamp."
  15908. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  15909. ng h m new rem)
  15910. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  15911. (cond
  15912. ((or (org-pos-in-match-range pos 2)
  15913. (org-pos-in-match-range pos 3))
  15914. (setq m (string-to-number (match-string 3 s))
  15915. h (string-to-number (match-string 2 s)))
  15916. (if (org-pos-in-match-range pos 2)
  15917. (setq h (+ h n))
  15918. (setq n (* dm (with-no-warnings (signum n))))
  15919. (unless (= 0 (setq rem (% m dm)))
  15920. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  15921. (setq m (+ m n)))
  15922. (when (< m 0) (setq m (+ m 60) h (1- h)))
  15923. (when (> m 59) (setq m (- m 60) h (1+ h)))
  15924. (setq h (mod h 24))
  15925. (setq ng 1 new (format "-%02d:%02d" h m)))
  15926. ((org-pos-in-match-range pos 6)
  15927. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  15928. ((org-pos-in-match-range pos 5)
  15929. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  15930. ((org-pos-in-match-range pos 9)
  15931. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  15932. ((org-pos-in-match-range pos 8)
  15933. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  15934. (when ng
  15935. (setq s (concat
  15936. (substring s 0 (match-beginning ng))
  15937. new
  15938. (substring s (match-end ng))))))
  15939. s))
  15940. (defun org-recenter-calendar (d)
  15941. "If the calendar is visible, recenter it to date D."
  15942. (let ((cwin (get-buffer-window "*Calendar*" t)))
  15943. (when cwin
  15944. (let ((calendar-move-hook nil))
  15945. (with-selected-window cwin
  15946. (calendar-goto-date
  15947. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  15948. (defun org-goto-calendar (&optional arg)
  15949. "Go to the Emacs calendar at the current date.
  15950. If there is a time stamp in the current line, go to that date.
  15951. A prefix ARG can be used to force the current date."
  15952. (interactive "P")
  15953. (let ((calendar-move-hook nil)
  15954. (calendar-view-holidays-initially-flag nil)
  15955. (calendar-view-diary-initially-flag nil)
  15956. diff)
  15957. (when (or (org-at-timestamp-p 'lax)
  15958. (org-match-line (concat ".*" org-ts-regexp)))
  15959. (let ((d1 (time-to-days (current-time)))
  15960. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  15961. (setq diff (- d2 d1))))
  15962. (calendar)
  15963. (calendar-goto-today)
  15964. (when (and diff (not arg)) (calendar-forward-day diff))))
  15965. (defun org-get-date-from-calendar ()
  15966. "Return a list (month day year) of date at point in calendar."
  15967. (with-current-buffer "*Calendar*"
  15968. (save-match-data
  15969. (calendar-cursor-to-date))))
  15970. (defun org-date-from-calendar ()
  15971. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  15972. If there is already a time stamp at the cursor position, update it."
  15973. (interactive)
  15974. (if (org-at-timestamp-p 'lax)
  15975. (org-timestamp-change 0 'calendar)
  15976. (let ((cal-date (org-get-date-from-calendar)))
  15977. (org-insert-time-stamp
  15978. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  15979. (defcustom org-effort-durations
  15980. `(("min" . 1)
  15981. ("h" . 60)
  15982. ("d" . ,(* 60 8))
  15983. ("w" . ,(* 60 8 5))
  15984. ("m" . ,(* 60 8 5 4))
  15985. ("y" . ,(* 60 8 5 40)))
  15986. "Conversion factor to minutes for an effort modifier.
  15987. Each entry has the form (MODIFIER . MINUTES).
  15988. In an effort string, a number followed by MODIFIER is multiplied
  15989. by the specified number of MINUTES to obtain an effort in
  15990. minutes.
  15991. For example, if the value of this variable is ((\"hours\" . 60)), then an
  15992. effort string \"2hours\" is equivalent to 120 minutes."
  15993. :group 'org-agenda
  15994. :version "26.1"
  15995. :package-version '(Org . "8.3")
  15996. :type '(alist :key-type (string :tag "Modifier")
  15997. :value-type (number :tag "Minutes")))
  15998. (defcustom org-image-actual-width t
  15999. "Should we use the actual width of images when inlining them?
  16000. When set to t, always use the image width.
  16001. When set to a number, use imagemagick (when available) to set
  16002. the image's width to this value.
  16003. When set to a number in a list, try to get the width from any
  16004. #+ATTR.* keyword if it matches a width specification like
  16005. #+ATTR_HTML: :width 300px
  16006. and fall back on that number if none is found.
  16007. When set to nil, try to get the width from an #+ATTR.* keyword
  16008. and fall back on the original width if none is found.
  16009. This requires Emacs >= 24.1, build with imagemagick support."
  16010. :group 'org-appearance
  16011. :version "24.4"
  16012. :package-version '(Org . "8.0")
  16013. :type '(choice
  16014. (const :tag "Use the image width" t)
  16015. (integer :tag "Use a number of pixels")
  16016. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16017. (const :tag "Use #+ATTR* or don't resize" nil)))
  16018. (defcustom org-agenda-inhibit-startup nil
  16019. "Inhibit startup when preparing agenda buffers.
  16020. When this variable is t, the initialization of the Org agenda
  16021. buffers is inhibited: e.g. the visibility state is not set, the
  16022. tables are not re-aligned, etc."
  16023. :type 'boolean
  16024. :version "24.3"
  16025. :group 'org-agenda)
  16026. (defcustom org-agenda-ignore-properties nil
  16027. "Avoid updating text properties when building the agenda.
  16028. Properties are used to prepare buffers for effort estimates,
  16029. appointments, statistics and subtree-local categories.
  16030. If you don't use these in the agenda, you can add them to this
  16031. list and agenda building will be a bit faster.
  16032. The value is a list, with zero or more of the symbols `effort', `appt',
  16033. `stats' or `category'."
  16034. :type '(set :greedy t
  16035. (const effort)
  16036. (const appt)
  16037. (const stats)
  16038. (const category))
  16039. :version "26.1"
  16040. :package-version '(Org . "8.3")
  16041. :group 'org-agenda)
  16042. ;;;; Files
  16043. (defun org-save-all-org-buffers ()
  16044. "Save all Org buffers without user confirmation."
  16045. (interactive)
  16046. (message "Saving all Org buffers...")
  16047. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16048. (when (featurep 'org-id) (org-id-locations-save))
  16049. (message "Saving all Org buffers... done"))
  16050. (defun org-revert-all-org-buffers ()
  16051. "Revert all Org buffers.
  16052. Prompt for confirmation when there are unsaved changes.
  16053. Be sure you know what you are doing before letting this function
  16054. overwrite your changes.
  16055. This function is useful in a setup where one tracks Org files
  16056. with a version control system, to revert on one machine after pulling
  16057. changes from another. I believe the procedure must be like this:
  16058. 1. M-x org-save-all-org-buffers
  16059. 2. Pull changes from the other machine, resolve conflicts
  16060. 3. M-x org-revert-all-org-buffers"
  16061. (interactive)
  16062. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16063. (user-error "Abort"))
  16064. (save-excursion
  16065. (save-window-excursion
  16066. (dolist (b (buffer-list))
  16067. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16068. (with-current-buffer b buffer-file-name))
  16069. (pop-to-buffer-same-window b)
  16070. (revert-buffer t 'no-confirm)))
  16071. (when (and (featurep 'org-id) org-id-track-globally)
  16072. (org-id-locations-load)))))
  16073. ;;;; Agenda files
  16074. ;;;###autoload
  16075. (defun org-switchb (&optional arg)
  16076. "Switch between Org buffers.
  16077. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16078. With `\\[universal-argument] \\[universal-argument]' \
  16079. prefix, restrict available buffers to agenda files."
  16080. (interactive "P")
  16081. (let ((blist (org-buffer-list
  16082. (cond ((equal arg '(4)) 'files)
  16083. ((equal arg '(16)) 'agenda)))))
  16084. (pop-to-buffer-same-window
  16085. (completing-read "Org buffer: "
  16086. (mapcar #'list (mapcar #'buffer-name blist))
  16087. nil t))))
  16088. (defun org-buffer-list (&optional predicate exclude-tmp)
  16089. "Return a list of Org buffers.
  16090. PREDICATE can be `export', `files' or `agenda'.
  16091. export restrict the list to Export buffers.
  16092. files restrict the list to buffers visiting Org files.
  16093. agenda restrict the list to buffers visiting agenda files.
  16094. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16095. (let* ((bfn nil)
  16096. (agenda-files (and (eq predicate 'agenda)
  16097. (mapcar 'file-truename (org-agenda-files t))))
  16098. (filter
  16099. (cond
  16100. ((eq predicate 'files)
  16101. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16102. ((eq predicate 'export)
  16103. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16104. ((eq predicate 'agenda)
  16105. (lambda (b)
  16106. (with-current-buffer b
  16107. (and (derived-mode-p 'org-mode)
  16108. (setq bfn (buffer-file-name b))
  16109. (member (file-truename bfn) agenda-files)))))
  16110. (t (lambda (b) (with-current-buffer b
  16111. (or (derived-mode-p 'org-mode)
  16112. (string-match "\\*Org .*Export"
  16113. (buffer-name b)))))))))
  16114. (delq nil
  16115. (mapcar
  16116. (lambda(b)
  16117. (if (and (funcall filter b)
  16118. (or (not exclude-tmp)
  16119. (not (string-match "tmp" (buffer-name b)))))
  16120. b
  16121. nil))
  16122. (buffer-list)))))
  16123. (defun org-agenda-files (&optional unrestricted archives)
  16124. "Get the list of agenda files.
  16125. Optional UNRESTRICTED means return the full list even if a restriction
  16126. is currently in place.
  16127. When ARCHIVES is t, include all archive files that are really being
  16128. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16129. `org-agenda-archives-mode' is t."
  16130. (let ((files
  16131. (cond
  16132. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16133. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16134. ((listp org-agenda-files) org-agenda-files)
  16135. (t (error "Invalid value of `org-agenda-files'")))))
  16136. (setq files (apply 'append
  16137. (mapcar (lambda (f)
  16138. (if (file-directory-p f)
  16139. (directory-files
  16140. f t org-agenda-file-regexp)
  16141. (list f)))
  16142. files)))
  16143. (when org-agenda-skip-unavailable-files
  16144. (setq files (delq nil
  16145. (mapcar (function
  16146. (lambda (file)
  16147. (and (file-readable-p file) file)))
  16148. files))))
  16149. (when (or (eq archives t)
  16150. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16151. (setq files (org-add-archive-files files)))
  16152. files))
  16153. (defun org-agenda-file-p (&optional file)
  16154. "Return non-nil, if FILE is an agenda file.
  16155. If FILE is omitted, use the file associated with the current
  16156. buffer."
  16157. (let ((fname (or file (buffer-file-name))))
  16158. (and fname
  16159. (member (file-truename fname)
  16160. (mapcar #'file-truename (org-agenda-files t))))))
  16161. (defun org-edit-agenda-file-list ()
  16162. "Edit the list of agenda files.
  16163. Depending on setup, this either uses customize to edit the variable
  16164. `org-agenda-files', or it visits the file that is holding the list. In the
  16165. latter case, the buffer is set up in a way that saving it automatically kills
  16166. the buffer and restores the previous window configuration."
  16167. (interactive)
  16168. (if (stringp org-agenda-files)
  16169. (let ((cw (current-window-configuration)))
  16170. (find-file org-agenda-files)
  16171. (setq-local org-window-configuration cw)
  16172. (add-hook 'after-save-hook
  16173. (lambda ()
  16174. (set-window-configuration
  16175. (prog1 org-window-configuration
  16176. (kill-buffer (current-buffer))))
  16177. (org-install-agenda-files-menu)
  16178. (message "New agenda file list installed"))
  16179. nil 'local)
  16180. (message "%s" (substitute-command-keys
  16181. "Edit list and finish with \\[save-buffer]")))
  16182. (customize-variable 'org-agenda-files)))
  16183. (defun org-store-new-agenda-file-list (list)
  16184. "Set new value for the agenda file list and save it correctly."
  16185. (if (stringp org-agenda-files)
  16186. (let ((fe (org-read-agenda-file-list t)) b u)
  16187. (while (setq b (find-buffer-visiting org-agenda-files))
  16188. (kill-buffer b))
  16189. (with-temp-file org-agenda-files
  16190. (insert
  16191. (mapconcat
  16192. (lambda (f) ;; Keep un-expanded entries.
  16193. (if (setq u (assoc f fe))
  16194. (cdr u)
  16195. f))
  16196. list "\n")
  16197. "\n")))
  16198. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16199. (org-insert-mode-line-in-empty-file nil))
  16200. (setq org-agenda-files list)
  16201. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16202. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16203. "Read the list of agenda files from a file.
  16204. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16205. filenames, used by `org-store-new-agenda-file-list' to write back
  16206. un-expanded file names."
  16207. (when (file-directory-p org-agenda-files)
  16208. (error "`org-agenda-files' cannot be a single directory"))
  16209. (when (stringp org-agenda-files)
  16210. (with-temp-buffer
  16211. (insert-file-contents org-agenda-files)
  16212. (mapcar
  16213. (lambda (f)
  16214. (let ((e (expand-file-name (substitute-in-file-name f)
  16215. org-directory)))
  16216. (if pair-with-expansion
  16217. (cons e f)
  16218. e)))
  16219. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16220. ;;;###autoload
  16221. (defun org-cycle-agenda-files ()
  16222. "Cycle through the files in `org-agenda-files'.
  16223. If the current buffer visits an agenda file, find the next one in the list.
  16224. If the current buffer does not, find the first agenda file."
  16225. (interactive)
  16226. (let* ((fs (or (org-agenda-files t)
  16227. (user-error "No agenda files")))
  16228. (files (copy-sequence fs))
  16229. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16230. file)
  16231. (when tcf
  16232. (while (and (setq file (pop files))
  16233. (not (equal (file-truename file) tcf)))))
  16234. (find-file (car (or files fs)))
  16235. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16236. (defun org-agenda-file-to-front (&optional to-end)
  16237. "Move/add the current file to the top of the agenda file list.
  16238. If the file is not present in the list, it is added to the front. If it is
  16239. present, it is moved there. With optional argument TO-END, add/move to the
  16240. end of the list."
  16241. (interactive "P")
  16242. (let ((org-agenda-skip-unavailable-files nil)
  16243. (file-alist (mapcar (lambda (x)
  16244. (cons (file-truename x) x))
  16245. (org-agenda-files t)))
  16246. (ctf (file-truename
  16247. (or buffer-file-name
  16248. (user-error "Please save the current buffer to a file"))))
  16249. x had)
  16250. (setq x (assoc ctf file-alist) had x)
  16251. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16252. (if to-end
  16253. (setq file-alist (append (delq x file-alist) (list x)))
  16254. (setq file-alist (cons x (delq x file-alist))))
  16255. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16256. (org-install-agenda-files-menu)
  16257. (message "File %s to %s of agenda file list"
  16258. (if had "moved" "added") (if to-end "end" "front"))))
  16259. (defun org-remove-file (&optional file)
  16260. "Remove current file from the list of files in variable `org-agenda-files'.
  16261. These are the files which are being checked for agenda entries.
  16262. Optional argument FILE means use this file instead of the current."
  16263. (interactive)
  16264. (let* ((org-agenda-skip-unavailable-files nil)
  16265. (file (or file buffer-file-name
  16266. (user-error "Current buffer does not visit a file")))
  16267. (true-file (file-truename file))
  16268. (afile (abbreviate-file-name file))
  16269. (files (delq nil (mapcar
  16270. (lambda (x)
  16271. (unless (equal true-file
  16272. (file-truename x))
  16273. x))
  16274. (org-agenda-files t)))))
  16275. (if (not (= (length files) (length (org-agenda-files t))))
  16276. (progn
  16277. (org-store-new-agenda-file-list files)
  16278. (org-install-agenda-files-menu)
  16279. (message "Removed from Org Agenda list: %s" afile))
  16280. (message "File was not in list: %s (not removed)" afile))))
  16281. (defun org-file-menu-entry (file)
  16282. (vector file (list 'find-file file) t))
  16283. (defun org-check-agenda-file (file)
  16284. "Make sure FILE exists. If not, ask user what to do."
  16285. (unless (file-exists-p file)
  16286. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16287. (abbreviate-file-name file))
  16288. (let ((r (downcase (read-char-exclusive))))
  16289. (cond
  16290. ((equal r ?r)
  16291. (org-remove-file file)
  16292. (throw 'nextfile t))
  16293. (t (user-error "Abort"))))))
  16294. (defun org-get-agenda-file-buffer (file)
  16295. "Get an agenda buffer visiting FILE.
  16296. If the buffer needs to be created, add it to the list of buffers
  16297. which might be released later."
  16298. (let ((buf (org-find-base-buffer-visiting file)))
  16299. (if buf
  16300. buf ; just return it
  16301. ;; Make a new buffer and remember it
  16302. (setq buf (find-file-noselect file))
  16303. (when buf (push buf org-agenda-new-buffers))
  16304. buf)))
  16305. (defun org-release-buffers (blist)
  16306. "Release all buffers in list, asking the user for confirmation when needed.
  16307. When a buffer is unmodified, it is just killed. When modified, it is saved
  16308. \(if the user agrees) and then killed."
  16309. (let (file)
  16310. (dolist (buf blist)
  16311. (setq file (buffer-file-name buf))
  16312. (when (and (buffer-modified-p buf)
  16313. file
  16314. (y-or-n-p (format "Save file %s? " file)))
  16315. (with-current-buffer buf (save-buffer)))
  16316. (kill-buffer buf))))
  16317. (defun org-agenda-prepare-buffers (files)
  16318. "Create buffers for all agenda files, protect archived trees and comments."
  16319. (interactive)
  16320. (let ((pa '(:org-archived t))
  16321. (pc '(:org-comment t))
  16322. (pall '(:org-archived t :org-comment t))
  16323. (inhibit-read-only t)
  16324. (org-inhibit-startup org-agenda-inhibit-startup)
  16325. (rea (org-make-tag-string (list org-archive-tag)))
  16326. re pos)
  16327. (setq org-tag-alist-for-agenda nil
  16328. org-tag-groups-alist-for-agenda nil)
  16329. (save-excursion
  16330. (save-restriction
  16331. (dolist (file files)
  16332. (catch 'nextfile
  16333. (if (bufferp file)
  16334. (set-buffer file)
  16335. (org-check-agenda-file file)
  16336. (set-buffer (org-get-agenda-file-buffer file)))
  16337. (widen)
  16338. (org-set-regexps-and-options 'tags-only)
  16339. (setq pos (point))
  16340. (or (memq 'category org-agenda-ignore-properties)
  16341. (org-refresh-category-properties))
  16342. (or (memq 'stats org-agenda-ignore-properties)
  16343. (org-refresh-stats-properties))
  16344. (or (memq 'effort org-agenda-ignore-properties)
  16345. (org-refresh-effort-properties))
  16346. (or (memq 'appt org-agenda-ignore-properties)
  16347. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16348. (setq org-todo-keywords-for-agenda
  16349. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16350. (setq org-done-keywords-for-agenda
  16351. (append org-done-keywords-for-agenda org-done-keywords))
  16352. (setq org-todo-keyword-alist-for-agenda
  16353. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16354. (setq org-tag-alist-for-agenda
  16355. (org--tag-add-to-alist
  16356. org-tag-alist-for-agenda
  16357. org-current-tag-alist))
  16358. ;; Merge current file's tag groups into global
  16359. ;; `org-tag-groups-alist-for-agenda'.
  16360. (when org-group-tags
  16361. (dolist (alist org-tag-groups-alist)
  16362. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16363. (if old
  16364. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16365. (push alist org-tag-groups-alist-for-agenda)))))
  16366. (with-silent-modifications
  16367. (save-excursion
  16368. (remove-text-properties (point-min) (point-max) pall)
  16369. (when org-agenda-skip-archived-trees
  16370. (goto-char (point-min))
  16371. (while (re-search-forward rea nil t)
  16372. (when (org-at-heading-p t)
  16373. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16374. (goto-char (point-min))
  16375. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16376. (while (re-search-forward re nil t)
  16377. (when (save-match-data (org-in-commented-heading-p t))
  16378. (add-text-properties
  16379. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16380. (goto-char pos)))))
  16381. (setq org-todo-keywords-for-agenda
  16382. (org-uniquify org-todo-keywords-for-agenda))
  16383. (setq org-todo-keyword-alist-for-agenda
  16384. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16385. ;;;; CDLaTeX minor mode
  16386. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16387. "Keymap for the minor `org-cdlatex-mode'.")
  16388. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  16389. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  16390. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  16391. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  16392. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  16393. (defvar org-cdlatex-texmathp-advice-is-done nil
  16394. "Flag remembering if we have applied the advice to texmathp already.")
  16395. (define-minor-mode org-cdlatex-mode
  16396. "Toggle the minor `org-cdlatex-mode'.
  16397. This mode supports entering LaTeX environment and math in LaTeX fragments
  16398. in Org mode.
  16399. \\{org-cdlatex-mode-map}"
  16400. nil " OCDL" nil
  16401. (when org-cdlatex-mode
  16402. (require 'cdlatex)
  16403. (run-hooks 'cdlatex-mode-hook)
  16404. (cdlatex-compute-tables))
  16405. (unless org-cdlatex-texmathp-advice-is-done
  16406. (setq org-cdlatex-texmathp-advice-is-done t)
  16407. (defadvice texmathp (around org-math-always-on activate)
  16408. "Always return t in Org buffers.
  16409. This is because we want to insert math symbols without dollars even outside
  16410. the LaTeX math segments. If Org mode thinks that point is actually inside
  16411. an embedded LaTeX fragment, let `texmathp' do its job.
  16412. `\\[org-cdlatex-mode-map]'"
  16413. (interactive)
  16414. (let (p)
  16415. (cond
  16416. ((not (derived-mode-p 'org-mode)) ad-do-it)
  16417. ((eq this-command 'cdlatex-math-symbol)
  16418. (setq ad-return-value t
  16419. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  16420. (t
  16421. (let ((p (org-inside-LaTeX-fragment-p)))
  16422. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  16423. (setq ad-return-value t
  16424. texmathp-why '("Org mode embedded math" . 0))
  16425. (when p ad-do-it)))))))))
  16426. (defun turn-on-org-cdlatex ()
  16427. "Unconditionally turn on `org-cdlatex-mode'."
  16428. (org-cdlatex-mode 1))
  16429. (defun org-try-cdlatex-tab ()
  16430. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  16431. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  16432. - inside a LaTeX fragment, or
  16433. - after the first word in a line, where an abbreviation expansion could
  16434. insert a LaTeX environment."
  16435. (when org-cdlatex-mode
  16436. (cond
  16437. ;; Before any word on the line: No expansion possible.
  16438. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  16439. ;; Just after first word on the line: Expand it. Make sure it
  16440. ;; cannot happen on headlines, though.
  16441. ((save-excursion
  16442. (skip-chars-backward "a-zA-Z0-9*")
  16443. (skip-chars-backward " \t")
  16444. (and (bolp) (not (org-at-heading-p))))
  16445. (cdlatex-tab) t)
  16446. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  16447. (defun org-cdlatex-underscore-caret (&optional _arg)
  16448. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  16449. Revert to the normal definition outside of these fragments."
  16450. (interactive "P")
  16451. (if (org-inside-LaTeX-fragment-p)
  16452. (call-interactively 'cdlatex-sub-superscript)
  16453. (let (org-cdlatex-mode)
  16454. (call-interactively (key-binding (vector last-input-event))))))
  16455. (defun org-cdlatex-math-modify (&optional _arg)
  16456. "Execute `cdlatex-math-modify' in LaTeX fragments.
  16457. Revert to the normal definition outside of these fragments."
  16458. (interactive "P")
  16459. (if (org-inside-LaTeX-fragment-p)
  16460. (call-interactively 'cdlatex-math-modify)
  16461. (let (org-cdlatex-mode)
  16462. (call-interactively (key-binding (vector last-input-event))))))
  16463. (defun org-cdlatex-environment-indent (&optional environment item)
  16464. "Execute `cdlatex-environment' and indent the inserted environment.
  16465. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  16466. The inserted environment is indented to current indentation
  16467. unless point is at the beginning of the line, in which the
  16468. environment remains unintended."
  16469. (interactive)
  16470. ;; cdlatex-environment always return nil. Therefore, capture output
  16471. ;; first and determine if an environment was selected.
  16472. (let* ((beg (point-marker))
  16473. (end (copy-marker (point) t))
  16474. (inserted (progn
  16475. (ignore-errors (cdlatex-environment environment item))
  16476. (< beg end)))
  16477. ;; Figure out how many lines to move forward after the
  16478. ;; environment has been inserted.
  16479. (lines (when inserted
  16480. (save-excursion
  16481. (- (cl-loop while (< beg (point))
  16482. with x = 0
  16483. do (forward-line -1)
  16484. (cl-incf x)
  16485. finally return x)
  16486. (if (progn (goto-char beg)
  16487. (and (progn (skip-chars-forward " \t") (eolp))
  16488. (progn (skip-chars-backward " \t") (bolp))))
  16489. 1 0)))))
  16490. (env (org-trim (delete-and-extract-region beg end))))
  16491. (when inserted
  16492. ;; Get indentation of next line unless at column 0.
  16493. (let ((ind (if (bolp) 0
  16494. (save-excursion
  16495. (org-return-indent)
  16496. (prog1 (current-indentation)
  16497. (when (progn (skip-chars-forward " \t") (eolp))
  16498. (delete-region beg (point)))))))
  16499. (bol (progn (skip-chars-backward " \t") (bolp))))
  16500. ;; Insert a newline before environment unless at column zero
  16501. ;; to "escape" the current line. Insert a newline if
  16502. ;; something is one the same line as \end{ENVIRONMENT}.
  16503. (insert
  16504. (concat (unless bol "\n") env
  16505. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  16506. (unless (zerop ind)
  16507. (save-excursion
  16508. (goto-char beg)
  16509. (while (< (point) end)
  16510. (unless (eolp) (indent-line-to ind))
  16511. (forward-line))))
  16512. (goto-char beg)
  16513. (forward-line lines)
  16514. (indent-line-to ind)))
  16515. (set-marker beg nil)
  16516. (set-marker end nil)))
  16517. ;;;; LaTeX fragments
  16518. (defun org-inside-LaTeX-fragment-p ()
  16519. "Test if point is inside a LaTeX fragment.
  16520. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  16521. sequence appearing also before point.
  16522. Even though the matchers for math are configurable, this function assumes
  16523. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  16524. delimiters are skipped when they have been removed by customization.
  16525. The return value is nil, or a cons cell with the delimiter and the
  16526. position of this delimiter.
  16527. This function does a reasonably good job, but can locally be fooled by
  16528. for example currency specifications. For example it will assume being in
  16529. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  16530. fragments that are properly closed, but during editing, we have to live
  16531. with the uncertainty caused by missing closing delimiters. This function
  16532. looks only before point, not after."
  16533. (catch 'exit
  16534. (let ((pos (point))
  16535. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  16536. (lim (save-excursion (org-backward-paragraph) (point)))
  16537. dd-on str (start 0) m re)
  16538. (goto-char pos)
  16539. (when dodollar
  16540. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  16541. re (nth 1 (assoc "$" org-latex-regexps)))
  16542. (while (string-match re str start)
  16543. (cond
  16544. ((= (match-end 0) (length str))
  16545. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  16546. ((= (match-end 0) (- (length str) 5))
  16547. (throw 'exit nil))
  16548. (t (setq start (match-end 0))))))
  16549. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  16550. (goto-char pos)
  16551. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  16552. (and (match-beginning 2) (throw 'exit nil))
  16553. ;; count $$
  16554. (while (re-search-backward "\\$\\$" lim t)
  16555. (setq dd-on (not dd-on)))
  16556. (goto-char pos)
  16557. (when dd-on (cons "$$" m))))))
  16558. (defun org-inside-latex-macro-p ()
  16559. "Is point inside a LaTeX macro or its arguments?"
  16560. (save-match-data
  16561. (org-in-regexp
  16562. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  16563. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  16564. "Build an overlay between BEG and END using IMAGE file.
  16565. Argument IMAGETYPE is the extension of the displayed image,
  16566. as a string. It defaults to \"png\"."
  16567. (let ((ov (make-overlay beg end))
  16568. (imagetype (or (intern imagetype) 'png)))
  16569. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  16570. (overlay-put ov 'evaporate t)
  16571. (overlay-put ov
  16572. 'modification-hooks
  16573. (list (lambda (o _flag _beg _end &optional _l)
  16574. (delete-overlay o))))
  16575. (overlay-put ov
  16576. 'display
  16577. (list 'image :type imagetype :file image :ascent 'center))))
  16578. (defun org--list-latex-overlays (&optional beg end)
  16579. "List all Org LaTeX overlays in current buffer.
  16580. Limit to overlays between BEG and END when those are provided."
  16581. (cl-remove-if-not
  16582. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  16583. (overlays-in (or beg (point-min)) (or end (point-max)))))
  16584. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  16585. "Remove all overlays with LaTeX fragment images in current buffer.
  16586. When optional arguments BEG and END are non-nil, remove all
  16587. overlays between them instead. Return a non-nil value when some
  16588. overlays were removed, nil otherwise."
  16589. (let ((overlays (org--list-latex-overlays beg end)))
  16590. (mapc #'delete-overlay overlays)
  16591. overlays))
  16592. (defun org-toggle-latex-fragment (&optional arg)
  16593. "Preview the LaTeX fragment at point, or all locally or globally.
  16594. If the cursor is on a LaTeX fragment, create the image and overlay
  16595. it over the source code, if there is none. Remove it otherwise.
  16596. If there is no fragment at point, display all fragments in the
  16597. current section.
  16598. With prefix ARG, preview or clear image for all fragments in the
  16599. current subtree or in the whole buffer when used before the first
  16600. headline. With a prefix ARG `\\[universal-argument] \
  16601. \\[universal-argument]' preview or clear images
  16602. for all fragments in the buffer."
  16603. (interactive "P")
  16604. (when (display-graphic-p)
  16605. (catch 'exit
  16606. (save-excursion
  16607. (let (beg end msg)
  16608. (cond
  16609. ((or (equal arg '(16))
  16610. (and (equal arg '(4))
  16611. (org-with-limited-levels (org-before-first-heading-p))))
  16612. (if (org-remove-latex-fragment-image-overlays)
  16613. (progn (message "LaTeX fragments images removed from buffer")
  16614. (throw 'exit nil))
  16615. (setq msg "Creating images for buffer...")))
  16616. ((equal arg '(4))
  16617. (org-with-limited-levels (org-back-to-heading t))
  16618. (setq beg (point))
  16619. (setq end (progn (org-end-of-subtree t) (point)))
  16620. (if (org-remove-latex-fragment-image-overlays beg end)
  16621. (progn
  16622. (message "LaTeX fragment images removed from subtree")
  16623. (throw 'exit nil))
  16624. (setq msg "Creating images for subtree...")))
  16625. ((let ((datum (org-element-context)))
  16626. (when (memq (org-element-type datum)
  16627. '(latex-environment latex-fragment))
  16628. (setq beg (org-element-property :begin datum))
  16629. (setq end (org-element-property :end datum))
  16630. (if (org-remove-latex-fragment-image-overlays beg end)
  16631. (progn (message "LaTeX fragment image removed")
  16632. (throw 'exit nil))
  16633. (setq msg "Creating image...")))))
  16634. (t
  16635. (org-with-limited-levels
  16636. (setq beg (if (org-at-heading-p) (line-beginning-position)
  16637. (outline-previous-heading)
  16638. (point)))
  16639. (setq end (progn (outline-next-heading) (point)))
  16640. (if (org-remove-latex-fragment-image-overlays beg end)
  16641. (progn
  16642. (message "LaTeX fragment images removed from section")
  16643. (throw 'exit nil))
  16644. (setq msg "Creating images for section...")))))
  16645. (let ((file (buffer-file-name (buffer-base-buffer))))
  16646. (org-format-latex
  16647. (concat org-preview-latex-image-directory "org-ltximg")
  16648. beg end
  16649. ;; Emacs cannot overlay images from remote hosts. Create
  16650. ;; it in `temporary-file-directory' instead.
  16651. (if (or (not file) (file-remote-p file))
  16652. temporary-file-directory
  16653. default-directory)
  16654. 'overlays msg 'forbuffer org-preview-latex-default-process))
  16655. (message (concat msg "done")))))))
  16656. (defun org-format-latex
  16657. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  16658. "Replace LaTeX fragments with links to an image.
  16659. The function takes care of creating the replacement image.
  16660. Only consider fragments between BEG and END when those are
  16661. provided.
  16662. When optional argument OVERLAYS is non-nil, display the image on
  16663. top of the fragment instead of replacing it.
  16664. PROCESSING-TYPE is the conversion method to use, as a symbol.
  16665. Some of the options can be changed using the variable
  16666. `org-format-latex-options', which see."
  16667. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  16668. (unless (eq processing-type 'verbatim)
  16669. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  16670. (cnt 0)
  16671. checkdir-flag)
  16672. (goto-char (or beg (point-min)))
  16673. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  16674. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  16675. (overlay-recenter (or end (point-max))))
  16676. (while (re-search-forward math-regexp end t)
  16677. (unless (and overlays
  16678. (eq (get-char-property (point) 'org-overlay-type)
  16679. 'org-latex-overlay))
  16680. (let* ((context (org-element-context))
  16681. (type (org-element-type context)))
  16682. (when (memq type '(latex-environment latex-fragment))
  16683. (let ((block-type (eq type 'latex-environment))
  16684. (value (org-element-property :value context))
  16685. (beg (org-element-property :begin context))
  16686. (end (save-excursion
  16687. (goto-char (org-element-property :end context))
  16688. (skip-chars-backward " \r\t\n")
  16689. (point))))
  16690. (cond
  16691. ((eq processing-type 'mathjax)
  16692. ;; Prepare for MathJax processing.
  16693. (if (not (string-match "\\`\\$\\$?" value))
  16694. (goto-char end)
  16695. (delete-region beg end)
  16696. (if (string= (match-string 0 value) "$$")
  16697. (insert "\\[" (substring value 2 -2) "\\]")
  16698. (insert "\\(" (substring value 1 -1) "\\)"))))
  16699. ((assq processing-type org-preview-latex-process-alist)
  16700. ;; Process to an image.
  16701. (cl-incf cnt)
  16702. (goto-char beg)
  16703. (let* ((processing-info
  16704. (cdr (assq processing-type org-preview-latex-process-alist)))
  16705. (face (face-at-point))
  16706. ;; Get the colors from the face at point.
  16707. (fg
  16708. (let ((color (plist-get org-format-latex-options
  16709. :foreground)))
  16710. (if (and forbuffer (eq color 'auto))
  16711. (face-attribute face :foreground nil 'default)
  16712. color)))
  16713. (bg
  16714. (let ((color (plist-get org-format-latex-options
  16715. :background)))
  16716. (if (and forbuffer (eq color 'auto))
  16717. (face-attribute face :background nil 'default)
  16718. color)))
  16719. (hash (sha1 (prin1-to-string
  16720. (list org-format-latex-header
  16721. org-latex-default-packages-alist
  16722. org-latex-packages-alist
  16723. org-format-latex-options
  16724. forbuffer value fg bg))))
  16725. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  16726. (absprefix (expand-file-name prefix dir))
  16727. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  16728. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  16729. (sep (and block-type "\n\n"))
  16730. (link (concat sep "[[file:" linkfile "]]" sep))
  16731. (options
  16732. (org-combine-plists
  16733. org-format-latex-options
  16734. `(:foreground ,fg :background ,bg))))
  16735. (when msg (message msg cnt))
  16736. (unless checkdir-flag ; Ensure the directory exists.
  16737. (setq checkdir-flag t)
  16738. (let ((todir (file-name-directory absprefix)))
  16739. (unless (file-directory-p todir)
  16740. (make-directory todir t))))
  16741. (unless (file-exists-p movefile)
  16742. (org-create-formula-image
  16743. value movefile options forbuffer processing-type))
  16744. (if overlays
  16745. (progn
  16746. (dolist (o (overlays-in beg end))
  16747. (when (eq (overlay-get o 'org-overlay-type)
  16748. 'org-latex-overlay)
  16749. (delete-overlay o)))
  16750. (org--format-latex-make-overlay beg end movefile imagetype)
  16751. (goto-char end))
  16752. (delete-region beg end)
  16753. (insert
  16754. (org-add-props link
  16755. (list 'org-latex-src
  16756. (replace-regexp-in-string "\"" "" value)
  16757. 'org-latex-src-embed-type
  16758. (if block-type 'paragraph 'character)))))))
  16759. ((eq processing-type 'mathml)
  16760. ;; Process to MathML.
  16761. (unless (org-format-latex-mathml-available-p)
  16762. (user-error "LaTeX to MathML converter not configured"))
  16763. (cl-incf cnt)
  16764. (when msg (message msg cnt))
  16765. (goto-char beg)
  16766. (delete-region beg end)
  16767. (insert (org-format-latex-as-mathml
  16768. value block-type prefix dir)))
  16769. (t
  16770. (error "Unknown conversion process %s for LaTeX fragments"
  16771. processing-type)))))))))))
  16772. (defun org-create-math-formula (latex-frag &optional mathml-file)
  16773. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  16774. Use `org-latex-to-mathml-convert-command'. If the conversion is
  16775. sucessful, return the portion between \"<math...> </math>\"
  16776. elements otherwise return nil. When MATHML-FILE is specified,
  16777. write the results in to that file. When invoked as an
  16778. interactive command, prompt for LATEX-FRAG, with initial value
  16779. set to the current active region and echo the results for user
  16780. inspection."
  16781. (interactive (list (let ((frag (when (org-region-active-p)
  16782. (buffer-substring-no-properties
  16783. (region-beginning) (region-end)))))
  16784. (read-string "LaTeX Fragment: " frag nil frag))))
  16785. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  16786. (let* ((tmp-in-file
  16787. (let ((file (file-relative-name
  16788. (make-temp-name (expand-file-name "ltxmathml-in")))))
  16789. (write-region latex-frag nil file)
  16790. file))
  16791. (tmp-out-file (file-relative-name
  16792. (make-temp-name (expand-file-name "ltxmathml-out"))))
  16793. (cmd (format-spec
  16794. org-latex-to-mathml-convert-command
  16795. `((?j . ,(and org-latex-to-mathml-jar-file
  16796. (shell-quote-argument
  16797. (expand-file-name
  16798. org-latex-to-mathml-jar-file))))
  16799. (?I . ,(shell-quote-argument tmp-in-file))
  16800. (?i . ,latex-frag)
  16801. (?o . ,(shell-quote-argument tmp-out-file)))))
  16802. mathml shell-command-output)
  16803. (when (called-interactively-p 'any)
  16804. (unless (org-format-latex-mathml-available-p)
  16805. (user-error "LaTeX to MathML converter not configured")))
  16806. (message "Running %s" cmd)
  16807. (setq shell-command-output (shell-command-to-string cmd))
  16808. (setq mathml
  16809. (when (file-readable-p tmp-out-file)
  16810. (with-current-buffer (find-file-noselect tmp-out-file t)
  16811. (goto-char (point-min))
  16812. (when (re-search-forward
  16813. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  16814. (regexp-quote
  16815. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  16816. nil t)
  16817. (prog1 (match-string 0) (kill-buffer))))))
  16818. (cond
  16819. (mathml
  16820. (setq mathml
  16821. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  16822. (when mathml-file
  16823. (write-region mathml nil mathml-file))
  16824. (when (called-interactively-p 'any)
  16825. (message mathml)))
  16826. ((message "LaTeX to MathML conversion failed")
  16827. (message shell-command-output)))
  16828. (delete-file tmp-in-file)
  16829. (when (file-exists-p tmp-out-file)
  16830. (delete-file tmp-out-file))
  16831. mathml))
  16832. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  16833. prefix &optional dir)
  16834. "Use `org-create-math-formula' but check local cache first."
  16835. (let* ((absprefix (expand-file-name prefix dir))
  16836. (print-length nil) (print-level nil)
  16837. (formula-id (concat
  16838. "formula-"
  16839. (sha1
  16840. (prin1-to-string
  16841. (list latex-frag
  16842. org-latex-to-mathml-convert-command)))))
  16843. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  16844. (formula-cache-dir (file-name-directory formula-cache)))
  16845. (unless (file-directory-p formula-cache-dir)
  16846. (make-directory formula-cache-dir t))
  16847. (unless (file-exists-p formula-cache)
  16848. (org-create-math-formula latex-frag formula-cache))
  16849. (if (file-exists-p formula-cache)
  16850. ;; Successful conversion. Return the link to MathML file.
  16851. (org-add-props
  16852. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  16853. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  16854. 'org-latex-src-embed-type (if latex-frag-type
  16855. 'paragraph 'character)))
  16856. ;; Failed conversion. Return the LaTeX fragment verbatim
  16857. latex-frag)))
  16858. (defun org--get-display-dpi ()
  16859. "Get the DPI of the display.
  16860. The function assumes that the display has the same pixel width in
  16861. the horizontal and vertical directions."
  16862. (if (display-graphic-p)
  16863. (round (/ (display-pixel-height)
  16864. (/ (display-mm-height) 25.4)))
  16865. (error "Attempt to calculate the dpi of a non-graphic display")))
  16866. (defun org-create-formula-image
  16867. (string tofile options buffer &optional processing-type)
  16868. "Create an image from LaTeX source using external processes.
  16869. The LaTeX STRING is saved to a temporary LaTeX file, then
  16870. converted to an image file by process PROCESSING-TYPE defined in
  16871. `org-preview-latex-process-alist'. A nil value defaults to
  16872. `org-preview-latex-default-process'.
  16873. The generated image file is eventually moved to TOFILE.
  16874. The OPTIONS argument controls the size, foreground color and
  16875. background color of the generated image.
  16876. When BUFFER non-nil, this function is used for LaTeX previewing.
  16877. Otherwise, it is used to deal with LaTeX snippets showed in
  16878. a HTML file."
  16879. (let* ((processing-type (or processing-type
  16880. org-preview-latex-default-process))
  16881. (processing-info
  16882. (cdr (assq processing-type org-preview-latex-process-alist)))
  16883. (programs (plist-get processing-info :programs))
  16884. (error-message (or (plist-get processing-info :message) ""))
  16885. (use-xcolor (plist-get processing-info :use-xcolor))
  16886. (image-input-type (plist-get processing-info :image-input-type))
  16887. (image-output-type (plist-get processing-info :image-output-type))
  16888. (post-clean (or (plist-get processing-info :post-clean)
  16889. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  16890. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  16891. (latex-header
  16892. (or (plist-get processing-info :latex-header)
  16893. (org-latex-make-preamble
  16894. (org-export-get-environment (org-export-get-backend 'latex))
  16895. org-format-latex-header
  16896. 'snippet)))
  16897. (latex-compiler (plist-get processing-info :latex-compiler))
  16898. (image-converter (plist-get processing-info :image-converter))
  16899. (tmpdir temporary-file-directory)
  16900. (texfilebase (make-temp-name
  16901. (expand-file-name "orgtex" tmpdir)))
  16902. (texfile (concat texfilebase ".tex"))
  16903. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  16904. '(1.0 . 1.0)))
  16905. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  16906. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  16907. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  16908. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  16909. "Black"))
  16910. (bg (or (plist-get options (if buffer :background :html-background))
  16911. "Transparent"))
  16912. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  16913. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  16914. (dolist (program programs)
  16915. (org-check-external-command program error-message))
  16916. (if use-xcolor
  16917. (progn (if (eq fg 'default)
  16918. (setq fg (org-latex-color :foreground))
  16919. (setq fg (org-latex-color-format fg)))
  16920. (if (eq bg 'default)
  16921. (setq bg (org-latex-color :background))
  16922. (setq bg (org-latex-color-format
  16923. (if (string= bg "Transparent") "white" bg))))
  16924. (with-temp-file texfile
  16925. (insert latex-header)
  16926. (insert "\n\\begin{document}\n"
  16927. "\\definecolor{fg}{rgb}{" fg "}\n"
  16928. "\\definecolor{bg}{rgb}{" bg "}\n"
  16929. "\n\\pagecolor{bg}\n"
  16930. "\n{\\color{fg}\n"
  16931. string
  16932. "\n}\n"
  16933. "\n\\end{document}\n")))
  16934. (if (eq fg 'default)
  16935. (setq fg (org-dvipng-color :foreground))
  16936. (unless (string= fg "Transparent")
  16937. (setq fg (org-dvipng-color-format fg))))
  16938. (if (eq bg 'default)
  16939. (setq bg (org-dvipng-color :background))
  16940. (unless (string= bg "Transparent")
  16941. (setq bg (org-dvipng-color-format bg))))
  16942. (with-temp-file texfile
  16943. (insert latex-header)
  16944. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  16945. (let* ((err-msg (format "Please adjust `%s' part of \
  16946. `org-preview-latex-process-alist'."
  16947. processing-type))
  16948. (image-input-file
  16949. (org-compile-file
  16950. texfile latex-compiler image-input-type err-msg log-buf))
  16951. (image-output-file
  16952. (org-compile-file
  16953. image-input-file image-converter image-output-type err-msg log-buf
  16954. `((?F . ,(shell-quote-argument fg))
  16955. (?B . ,(shell-quote-argument bg))
  16956. (?D . ,(shell-quote-argument (format "%s" dpi)))
  16957. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  16958. (copy-file image-output-file tofile 'replace)
  16959. (dolist (e post-clean)
  16960. (when (file-exists-p (concat texfilebase e))
  16961. (delete-file (concat texfilebase e))))
  16962. image-output-file)))
  16963. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  16964. "Fill a LaTeX header template TPL.
  16965. In the template, the following place holders will be recognized:
  16966. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  16967. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  16968. [PACKAGES] \\usepackage statements for PKG
  16969. [NO-PACKAGES] do not include PKG
  16970. [EXTRA] the string EXTRA
  16971. [NO-EXTRA] do not include EXTRA
  16972. For backward compatibility, if both the positive and the negative place
  16973. holder is missing, the positive one (without the \"NO-\") will be
  16974. assumed to be present at the end of the template.
  16975. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  16976. EXTRA is a string.
  16977. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  16978. (let (rpl (end ""))
  16979. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  16980. (setq rpl (if (or (match-end 1) (not def-pkg))
  16981. "" (org-latex-packages-to-string def-pkg snippets-p t))
  16982. tpl (replace-match rpl t t tpl))
  16983. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  16984. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  16985. (setq rpl (if (or (match-end 1) (not pkg))
  16986. "" (org-latex-packages-to-string pkg snippets-p t))
  16987. tpl (replace-match rpl t t tpl))
  16988. (when pkg (setq end
  16989. (concat end "\n"
  16990. (org-latex-packages-to-string pkg snippets-p)))))
  16991. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  16992. (setq rpl (if (or (match-end 1) (not extra))
  16993. "" (concat extra "\n"))
  16994. tpl (replace-match rpl t t tpl))
  16995. (when (and extra (string-match "\\S-" extra))
  16996. (setq end (concat end "\n" extra))))
  16997. (if (string-match "\\S-" end)
  16998. (concat tpl "\n" end)
  16999. tpl)))
  17000. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17001. "Turn an alist of packages into a string with the \\usepackage macros."
  17002. (setq pkg (mapconcat (lambda(p)
  17003. (cond
  17004. ((stringp p) p)
  17005. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17006. (format "%% Package %s omitted" (cadr p)))
  17007. ((equal "" (car p))
  17008. (format "\\usepackage{%s}" (cadr p)))
  17009. (t
  17010. (format "\\usepackage[%s]{%s}"
  17011. (car p) (cadr p)))))
  17012. pkg
  17013. "\n"))
  17014. (if newline (concat pkg "\n") pkg))
  17015. (defun org-dvipng-color (attr)
  17016. "Return a RGB color specification for dvipng."
  17017. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17018. (defun org-dvipng-color-format (color-name)
  17019. "Convert COLOR-NAME to a RGB color value for dvipng."
  17020. (apply #'format "rgb %s %s %s"
  17021. (mapcar 'org-normalize-color
  17022. (color-values color-name))))
  17023. (defun org-latex-color (attr)
  17024. "Return a RGB color for the LaTeX color package."
  17025. (org-latex-color-format (face-attribute 'default attr nil)))
  17026. (defun org-latex-color-format (color-name)
  17027. "Convert COLOR-NAME to a RGB color value."
  17028. (apply #'format "%s,%s,%s"
  17029. (mapcar 'org-normalize-color
  17030. (color-values color-name))))
  17031. (defun org-normalize-color (value)
  17032. "Return string to be used as color value for an RGB component."
  17033. (format "%g" (/ value 65535.0)))
  17034. ;; Image display
  17035. (defvar-local org-inline-image-overlays nil)
  17036. (defun org-toggle-inline-images (&optional include-linked)
  17037. "Toggle the display of inline images.
  17038. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17039. (interactive "P")
  17040. (if org-inline-image-overlays
  17041. (progn
  17042. (org-remove-inline-images)
  17043. (when (called-interactively-p 'interactive)
  17044. (message "Inline image display turned off")))
  17045. (org-display-inline-images include-linked)
  17046. (when (called-interactively-p 'interactive)
  17047. (message (if org-inline-image-overlays
  17048. (format "%d images displayed inline"
  17049. (length org-inline-image-overlays))
  17050. "No images to display inline")))))
  17051. (defun org-redisplay-inline-images ()
  17052. "Refresh the display of inline images."
  17053. (interactive)
  17054. (if (not org-inline-image-overlays)
  17055. (org-toggle-inline-images)
  17056. (org-toggle-inline-images)
  17057. (org-toggle-inline-images)))
  17058. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17059. "Display inline images.
  17060. An inline image is a link which follows either of these
  17061. conventions:
  17062. 1. Its path is a file with an extension matching return value
  17063. from `image-file-name-regexp' and it has no contents.
  17064. 2. Its description consists in a single link of the previous
  17065. type.
  17066. When optional argument INCLUDE-LINKED is non-nil, also links with
  17067. a text description part will be inlined. This can be nice for
  17068. a quick look at those images, but it does not reflect what
  17069. exported files will look like.
  17070. When optional argument REFRESH is non-nil, refresh existing
  17071. images between BEG and END. This will create new image displays
  17072. only if necessary. BEG and END default to the buffer
  17073. boundaries."
  17074. (interactive "P")
  17075. (when (display-graphic-p)
  17076. (unless refresh
  17077. (org-remove-inline-images)
  17078. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17079. (org-with-wide-buffer
  17080. (goto-char (or beg (point-min)))
  17081. (let* ((case-fold-search t)
  17082. (file-extension-re (image-file-name-regexp))
  17083. (link-abbrevs (mapcar #'car
  17084. (append org-link-abbrev-alist-local
  17085. org-link-abbrev-alist)))
  17086. ;; Check absolute, relative file names and explicit
  17087. ;; "file:" links. Also check link abbreviations since
  17088. ;; some might expand to "file" links.
  17089. (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
  17090. (if (not link-abbrevs) ""
  17091. (format "\\|\\(?:%s:\\)"
  17092. (regexp-opt link-abbrevs))))))
  17093. (while (re-search-forward file-types-re end t)
  17094. (let ((link (save-match-data (org-element-context))))
  17095. ;; Check if we're at an inline image, i.e., an image file
  17096. ;; link without a description (unless INCLUDE-LINKED is
  17097. ;; non-nil).
  17098. (when (and (equal "file" (org-element-property :type link))
  17099. (or include-linked
  17100. (null (org-element-contents link)))
  17101. (string-match-p file-extension-re
  17102. (org-element-property :path link)))
  17103. (let ((file (expand-file-name
  17104. (org-link-unescape
  17105. (org-element-property :path link)))))
  17106. (when (file-exists-p file)
  17107. (let ((width
  17108. ;; Apply `org-image-actual-width' specifications.
  17109. (cond
  17110. ((not (image-type-available-p 'imagemagick)) nil)
  17111. ((eq org-image-actual-width t) nil)
  17112. ((listp org-image-actual-width)
  17113. (or
  17114. ;; First try to find a width among
  17115. ;; attributes associated to the paragraph
  17116. ;; containing link.
  17117. (let ((paragraph
  17118. (let ((e link))
  17119. (while (and (setq e (org-element-property
  17120. :parent e))
  17121. (not (eq (org-element-type e)
  17122. 'paragraph))))
  17123. e)))
  17124. (when paragraph
  17125. (save-excursion
  17126. (goto-char (org-element-property :begin paragraph))
  17127. (when
  17128. (re-search-forward
  17129. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17130. (org-element-property
  17131. :post-affiliated paragraph)
  17132. t)
  17133. (string-to-number (match-string 1))))))
  17134. ;; Otherwise, fall-back to provided number.
  17135. (car org-image-actual-width)))
  17136. ((numberp org-image-actual-width)
  17137. org-image-actual-width)))
  17138. (old (get-char-property-and-overlay
  17139. (org-element-property :begin link)
  17140. 'org-image-overlay)))
  17141. (if (and (car-safe old) refresh)
  17142. (image-refresh (overlay-get (cdr old) 'display))
  17143. (let ((image (create-image file
  17144. (and width 'imagemagick)
  17145. nil
  17146. :width width)))
  17147. (when image
  17148. (let ((ov (make-overlay
  17149. (org-element-property :begin link)
  17150. (progn
  17151. (goto-char
  17152. (org-element-property :end link))
  17153. (skip-chars-backward " \t")
  17154. (point)))))
  17155. (overlay-put ov 'display image)
  17156. (overlay-put ov 'face 'default)
  17157. (overlay-put ov 'org-image-overlay t)
  17158. (overlay-put
  17159. ov 'modification-hooks
  17160. (list 'org-display-inline-remove-overlay))
  17161. (push ov org-inline-image-overlays)))))))))))))))
  17162. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17163. "Remove inline-display overlay if a corresponding region is modified."
  17164. (let ((inhibit-modification-hooks t))
  17165. (when (and ov after)
  17166. (delete ov org-inline-image-overlays)
  17167. (delete-overlay ov))))
  17168. (defun org-remove-inline-images ()
  17169. "Remove inline display of images."
  17170. (interactive)
  17171. (mapc #'delete-overlay org-inline-image-overlays)
  17172. (setq org-inline-image-overlays nil))
  17173. ;;; Key bindings
  17174. (defun org-remap (map &rest commands)
  17175. "In MAP, remap the functions given in COMMANDS.
  17176. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  17177. (let (new old)
  17178. (while commands
  17179. (setq old (pop commands) new (pop commands))
  17180. (org-defkey map (vector 'remap old) new))))
  17181. ;;;; Outline functions that can be remapped in Org
  17182. (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
  17183. (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
  17184. (define-key org-mode-map [remap outline-forward-same-level]
  17185. #'org-forward-heading-same-level)
  17186. (define-key org-mode-map [remap outline-backward-same-level]
  17187. #'org-backward-heading-same-level)
  17188. (define-key org-mode-map [remap outline-show-branches]
  17189. #'org-kill-note-or-show-branches)
  17190. (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
  17191. (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
  17192. (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
  17193. (define-key org-mode-map [remap outline-next-visible-heading]
  17194. #'org-next-visible-heading)
  17195. (define-key org-mode-map [remap outline-previous-visible-heading]
  17196. #'org-previous-visible-heading)
  17197. (define-key org-mode-map [remap show-children] #'org-show-children)
  17198. ;;;; Make `C-c C-x' a prefix key
  17199. (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
  17200. ;;;; TAB key with modifiers
  17201. (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
  17202. (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
  17203. (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
  17204. (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
  17205. (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
  17206. (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
  17207. (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
  17208. (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
  17209. ;;;; RET key with modifiers
  17210. (org-defkey org-mode-map (kbd "S-<return>") #'org-table-copy-down)
  17211. (org-defkey org-mode-map (kbd "M-S-<return>") #'org-insert-todo-heading)
  17212. (org-defkey org-mode-map (kbd "ESC S-<return>") #'org-insert-todo-heading)
  17213. (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
  17214. (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
  17215. ;;;; Cursor keys with modifiers
  17216. (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
  17217. (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
  17218. (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
  17219. (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
  17220. (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
  17221. (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
  17222. (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
  17223. (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
  17224. (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
  17225. (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
  17226. (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
  17227. (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
  17228. (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
  17229. (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
  17230. (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
  17231. (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
  17232. (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
  17233. (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
  17234. (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
  17235. (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
  17236. (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
  17237. (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
  17238. (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
  17239. (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
  17240. (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
  17241. ;;;; Babel keys
  17242. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  17243. (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
  17244. (define-key org-babel-map key def))
  17245. ;;;; Extra keys for TTY access.
  17246. ;; We only set them when really needed because otherwise the
  17247. ;; menus don't show the simple keys
  17248. (when (or org-use-extra-keys (not window-system))
  17249. (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
  17250. (org-defkey org-mode-map (kbd "C-c C-x m") #'org-meta-return)
  17251. (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
  17252. (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
  17253. (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
  17254. (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
  17255. (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
  17256. (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
  17257. (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
  17258. (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
  17259. (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
  17260. (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
  17261. (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
  17262. (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
  17263. (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
  17264. (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
  17265. (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
  17266. (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
  17267. (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
  17268. (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
  17269. (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
  17270. ;;;; Narrow map
  17271. (org-defkey narrow-map "s" #'org-narrow-to-subtree)
  17272. (org-defkey narrow-map "b" #'org-narrow-to-block)
  17273. (org-defkey narrow-map "e" #'org-narrow-to-element)
  17274. ;;;; Remap usual Emacs bindings
  17275. (org-remap org-mode-map
  17276. 'self-insert-command 'org-self-insert-command
  17277. 'delete-char 'org-delete-char
  17278. 'delete-backward-char 'org-delete-backward-char
  17279. 'kill-line 'org-kill-line
  17280. 'open-line 'org-open-line
  17281. 'yank 'org-yank
  17282. 'comment-dwim 'org-comment-dwim
  17283. 'move-beginning-of-line 'org-beginning-of-line
  17284. 'move-end-of-line 'org-end-of-line
  17285. 'forward-paragraph 'org-forward-paragraph
  17286. 'backward-paragraph 'org-backward-paragraph
  17287. 'backward-sentence 'org-backward-sentence
  17288. 'forward-sentence 'org-forward-sentence
  17289. 'fill-paragraph 'org-fill-paragraph
  17290. 'delete-indentation 'org-delete-indentation
  17291. 'transpose-words 'org-transpose-words)
  17292. ;;;; All the other keys
  17293. (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
  17294. (org-defkey org-mode-map (kbd "C-c C-a") #'org-show-all)
  17295. (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
  17296. (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
  17297. (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
  17298. (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
  17299. (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
  17300. (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
  17301. (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
  17302. (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
  17303. (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
  17304. (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
  17305. (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
  17306. (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
  17307. (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
  17308. (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
  17309. (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
  17310. (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
  17311. (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
  17312. (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
  17313. (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
  17314. (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
  17315. (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
  17316. (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
  17317. (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
  17318. (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
  17319. (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
  17320. (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
  17321. (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
  17322. (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
  17323. (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
  17324. (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
  17325. (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
  17326. (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
  17327. (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
  17328. (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
  17329. (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
  17330. (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
  17331. (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
  17332. (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
  17333. (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
  17334. (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
  17335. (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
  17336. (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
  17337. (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
  17338. (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
  17339. (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
  17340. (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
  17341. (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
  17342. (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
  17343. (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
  17344. (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
  17345. (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
  17346. (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
  17347. (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
  17348. (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
  17349. (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
  17350. (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
  17351. (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
  17352. (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
  17353. (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
  17354. (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
  17355. (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
  17356. (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
  17357. (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
  17358. (org-defkey org-mode-map (kbd "RET") #'org-return)
  17359. (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
  17360. (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
  17361. (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
  17362. (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
  17363. (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
  17364. (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
  17365. (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
  17366. (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
  17367. (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
  17368. (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
  17369. (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
  17370. (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
  17371. (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
  17372. (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
  17373. (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
  17374. (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
  17375. (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
  17376. (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
  17377. (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
  17378. (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
  17379. (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
  17380. (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
  17381. (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
  17382. (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
  17383. (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
  17384. (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
  17385. (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
  17386. (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
  17387. (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
  17388. (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
  17389. (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
  17390. (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
  17391. (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
  17392. (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
  17393. (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
  17394. (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
  17395. (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
  17396. (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
  17397. (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
  17398. (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
  17399. (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
  17400. (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
  17401. (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
  17402. (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
  17403. (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
  17404. (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
  17405. (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
  17406. (org-defkey org-mode-map (kbd "C-c C-,") #'org-insert-structure-template)
  17407. (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
  17408. (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
  17409. (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
  17410. (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
  17411. (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
  17412. (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
  17413. (define-key org-mode-map (kbd "C-c C-x C-c") #'org-columns)
  17414. (define-key org-mode-map (kbd "C-c C-x !") #'org-reload)
  17415. (define-key org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
  17416. (define-key org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
  17417. (define-key org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
  17418. ;;; Speed commands
  17419. (defconst org-speed-commands-default
  17420. '(
  17421. ("Outline Navigation")
  17422. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  17423. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  17424. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  17425. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  17426. ("F" . org-next-block)
  17427. ("B" . org-previous-block)
  17428. ("u" . (org-speed-move-safe 'outline-up-heading))
  17429. ("j" . org-goto)
  17430. ("g" . (org-refile t))
  17431. ("Outline Visibility")
  17432. ("c" . org-cycle)
  17433. ("C" . org-shifttab)
  17434. (" " . org-display-outline-path)
  17435. ("s" . org-toggle-narrow-to-subtree)
  17436. ("k" . org-cut-subtree)
  17437. ("=" . org-columns)
  17438. ("Outline Structure Editing")
  17439. ("U" . org-metaup)
  17440. ("D" . org-metadown)
  17441. ("r" . org-metaright)
  17442. ("l" . org-metaleft)
  17443. ("R" . org-shiftmetaright)
  17444. ("L" . org-shiftmetaleft)
  17445. ("i" . (progn (forward-char 1) (call-interactively
  17446. 'org-insert-heading-respect-content)))
  17447. ("^" . org-sort)
  17448. ("w" . org-refile)
  17449. ("a" . org-archive-subtree-default-with-confirmation)
  17450. ("@" . org-mark-subtree)
  17451. ("#" . org-toggle-comment)
  17452. ("Clock Commands")
  17453. ("I" . org-clock-in)
  17454. ("O" . org-clock-out)
  17455. ("Meta Data Editing")
  17456. ("t" . org-todo)
  17457. ("," . (org-priority))
  17458. ("0" . (org-priority ?\ ))
  17459. ("1" . (org-priority ?A))
  17460. ("2" . (org-priority ?B))
  17461. ("3" . (org-priority ?C))
  17462. (":" . org-set-tags-command)
  17463. ("e" . org-set-effort)
  17464. ("E" . org-inc-effort)
  17465. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  17466. (org-entry-put (point) "APPT_WARNTIME" m)))
  17467. ("Agenda Views etc")
  17468. ("v" . org-agenda)
  17469. ("/" . org-sparse-tree)
  17470. ("Misc")
  17471. ("o" . org-open-at-point)
  17472. ("?" . org-speed-command-help)
  17473. ("<" . (org-agenda-set-restriction-lock 'subtree))
  17474. (">" . (org-agenda-remove-restriction-lock))
  17475. )
  17476. "The default speed commands.")
  17477. (defun org-print-speed-command (e)
  17478. (if (> (length (car e)) 1)
  17479. (progn
  17480. (princ "\n")
  17481. (princ (car e))
  17482. (princ "\n")
  17483. (princ (make-string (length (car e)) ?-))
  17484. (princ "\n"))
  17485. (princ (car e))
  17486. (princ " ")
  17487. (if (symbolp (cdr e))
  17488. (princ (symbol-name (cdr e)))
  17489. (prin1 (cdr e)))
  17490. (princ "\n")))
  17491. (defun org-speed-command-help ()
  17492. "Show the available speed commands."
  17493. (interactive)
  17494. (if (not org-use-speed-commands)
  17495. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  17496. (with-output-to-temp-buffer "*Help*"
  17497. (princ "User-defined Speed commands\n===========================\n")
  17498. (mapc #'org-print-speed-command org-speed-commands-user)
  17499. (princ "\n")
  17500. (princ "Built-in Speed commands\n=======================\n")
  17501. (mapc #'org-print-speed-command org-speed-commands-default))
  17502. (with-current-buffer "*Help*"
  17503. (setq truncate-lines t))))
  17504. (defun org-speed-move-safe (cmd)
  17505. "Execute CMD, but make sure that the cursor always ends up in a headline.
  17506. If not, return to the original position and throw an error."
  17507. (interactive)
  17508. (let ((pos (point)))
  17509. (call-interactively cmd)
  17510. (unless (and (bolp) (org-at-heading-p))
  17511. (goto-char pos)
  17512. (error "Boundary reached while executing %s" cmd))))
  17513. (defvar org-self-insert-command-undo-counter 0)
  17514. (defvar org-table-auto-blank-field) ; defined in org-table.el
  17515. (defvar org-speed-command nil)
  17516. (defun org-speed-command-activate (keys)
  17517. "Hook for activating single-letter speed commands.
  17518. `org-speed-commands-default' specifies a minimal command set.
  17519. Use `org-speed-commands-user' for further customization."
  17520. (when (or (and (bolp) (looking-at org-outline-regexp))
  17521. (and (functionp org-use-speed-commands)
  17522. (funcall org-use-speed-commands)))
  17523. (cdr (assoc keys (append org-speed-commands-user
  17524. org-speed-commands-default)))))
  17525. (defun org-babel-speed-command-activate (keys)
  17526. "Hook for activating single-letter code block commands."
  17527. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  17528. (cdr (assoc keys org-babel-key-bindings))))
  17529. (defcustom org-speed-command-hook
  17530. '(org-speed-command-activate org-babel-speed-command-activate)
  17531. "Hook for activating speed commands at strategic locations.
  17532. Hook functions are called in sequence until a valid handler is
  17533. found.
  17534. Each hook takes a single argument, a user-pressed command key
  17535. which is also a `self-insert-command' from the global map.
  17536. Within the hook, examine the cursor position and the command key
  17537. and return nil or a valid handler as appropriate. Handler could
  17538. be one of an interactive command, a function, or a form.
  17539. Set `org-use-speed-commands' to non-nil value to enable this
  17540. hook. The default setting is `org-speed-command-activate'."
  17541. :group 'org-structure
  17542. :version "24.1"
  17543. :type 'hook)
  17544. (defun org-self-insert-command (N)
  17545. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  17546. If the cursor is in a table looking at whitespace, the whitespace is
  17547. overwritten, and the table is not marked as requiring realignment."
  17548. (interactive "p")
  17549. (org-check-before-invisible-edit 'insert)
  17550. (cond
  17551. ((and org-use-speed-commands
  17552. (let ((kv (this-command-keys-vector)))
  17553. (setq org-speed-command
  17554. (run-hook-with-args-until-success
  17555. 'org-speed-command-hook
  17556. (make-string 1 (aref kv (1- (length kv))))))))
  17557. (cond
  17558. ((commandp org-speed-command)
  17559. (setq this-command org-speed-command)
  17560. (call-interactively org-speed-command))
  17561. ((functionp org-speed-command)
  17562. (funcall org-speed-command))
  17563. ((and org-speed-command (listp org-speed-command))
  17564. (eval org-speed-command))
  17565. (t (let (org-use-speed-commands)
  17566. (call-interactively 'org-self-insert-command)))))
  17567. ((and
  17568. (= N 1)
  17569. (not (org-region-active-p))
  17570. (org-at-table-p)
  17571. (progn
  17572. ;; Check if we blank the field, and if that triggers align.
  17573. (and (featurep 'org-table)
  17574. org-table-auto-blank-field
  17575. (memq last-command
  17576. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  17577. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  17578. ;; Got extra space, this field does not determine
  17579. ;; column width.
  17580. (let (org-table-may-need-update) (org-table-blank-field))
  17581. ;; No extra space, this field may determine column
  17582. ;; width.
  17583. (org-table-blank-field)))
  17584. t)
  17585. (looking-at "[^|\n]* |"))
  17586. ;; There is room for insertion without re-aligning the table.
  17587. (self-insert-command N)
  17588. (org-table-with-shrunk-field
  17589. (save-excursion
  17590. (skip-chars-forward "^|")
  17591. ;; Do not delete last space, which is
  17592. ;; `org-table-separator-space', but the regular space before
  17593. ;; it.
  17594. (delete-region (- (point) 2) (1- (point))))))
  17595. (t
  17596. (setq org-table-may-need-update t)
  17597. (self-insert-command N)
  17598. (org-fix-tags-on-the-fly)
  17599. (when org-self-insert-cluster-for-undo
  17600. (if (not (eq last-command 'org-self-insert-command))
  17601. (setq org-self-insert-command-undo-counter 1)
  17602. (if (>= org-self-insert-command-undo-counter 20)
  17603. (setq org-self-insert-command-undo-counter 1)
  17604. (and (> org-self-insert-command-undo-counter 0)
  17605. buffer-undo-list (listp buffer-undo-list)
  17606. (not (cadr buffer-undo-list)) ; remove nil entry
  17607. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  17608. (setq org-self-insert-command-undo-counter
  17609. (1+ org-self-insert-command-undo-counter))))))))
  17610. (defun org-check-before-invisible-edit (kind)
  17611. "Check is editing if kind KIND would be dangerous with invisible text around.
  17612. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  17613. ;; First, try to get out of here as quickly as possible, to reduce overhead
  17614. (when (and org-catch-invisible-edits
  17615. (or (not (boundp 'visible-mode)) (not visible-mode))
  17616. (or (get-char-property (point) 'invisible)
  17617. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  17618. ;; OK, we need to take a closer look. Do not consider
  17619. ;; invisibility obtained through text properties (e.g., link
  17620. ;; fontification), as it cannot be toggled.
  17621. (let* ((invisible-at-point
  17622. (pcase (get-char-property-and-overlay (point) 'invisible)
  17623. (`(,_ . ,(and (pred overlayp) o)) o)))
  17624. ;; Assume that point cannot land in the middle of an
  17625. ;; overlay, or between two overlays.
  17626. (invisible-before-point
  17627. (and (not invisible-at-point)
  17628. (not (bobp))
  17629. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  17630. (`(,_ . ,(and (pred overlayp) o)) o))))
  17631. (border-and-ok-direction
  17632. (or
  17633. ;; Check if we are acting predictably before invisible
  17634. ;; text.
  17635. (and invisible-at-point
  17636. (memq kind '(insert delete-backward)))
  17637. ;; Check if we are acting predictably after invisible text
  17638. ;; This works not well, and I have turned it off. It seems
  17639. ;; better to always show and stop after invisible text.
  17640. ;; (and (not invisible-at-point) invisible-before-point
  17641. ;; (memq kind '(insert delete)))
  17642. )))
  17643. (when (or invisible-at-point invisible-before-point)
  17644. (when (eq org-catch-invisible-edits 'error)
  17645. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  17646. (if (and org-custom-properties-overlays
  17647. (y-or-n-p "Display invisible properties in this buffer? "))
  17648. (org-toggle-custom-properties-visibility)
  17649. ;; Make the area visible
  17650. (save-excursion
  17651. (when invisible-before-point
  17652. (goto-char
  17653. (previous-single-char-property-change (point) 'invisible)))
  17654. ;; Remove whatever overlay is currently making yet-to-be
  17655. ;; edited text invisible. Also remove nested invisibility
  17656. ;; related overlays.
  17657. (delete-overlay (or invisible-at-point invisible-before-point))
  17658. (let ((origin (if invisible-at-point (point) (1- (point)))))
  17659. (while (pcase (get-char-property-and-overlay origin 'invisible)
  17660. (`(,_ . ,(and (pred overlayp) o))
  17661. (delete-overlay o)
  17662. t)))))
  17663. (cond
  17664. ((eq org-catch-invisible-edits 'show)
  17665. ;; That's it, we do the edit after showing
  17666. (message
  17667. "Unfolding invisible region around point before editing")
  17668. (sit-for 1))
  17669. ((and (eq org-catch-invisible-edits 'smart)
  17670. border-and-ok-direction)
  17671. (message "Unfolding invisible region around point before editing"))
  17672. (t
  17673. ;; Don't do the edit, make the user repeat it in full visibility
  17674. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  17675. (defun org-fix-tags-on-the-fly ()
  17676. "Align tags in headline at point.
  17677. Unlike `org-align-tags', this function does nothing if point is
  17678. either not currently on a tagged headline or on a tag."
  17679. (when (and (org-match-line org-tag-line-re)
  17680. (< (point) (match-beginning 1)))
  17681. (org-align-tags)))
  17682. (defun org-delete-backward-char (N)
  17683. "Like `delete-backward-char', insert whitespace at field end in tables.
  17684. When deleting backwards, in tables this function will insert whitespace in
  17685. front of the next \"|\" separator, to keep the table aligned. The table will
  17686. still be marked for re-alignment if the field did fill the entire column,
  17687. because, in this case the deletion might narrow the column."
  17688. (interactive "p")
  17689. (save-match-data
  17690. (org-check-before-invisible-edit 'delete-backward)
  17691. (if (and (= N 1)
  17692. (not overwrite-mode)
  17693. (not (org-region-active-p))
  17694. (not (eq (char-before) ?|))
  17695. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  17696. (looking-at-p ".*?|")
  17697. (org-at-table-p))
  17698. (progn (forward-char -1) (org-delete-char 1))
  17699. (backward-delete-char N)
  17700. (org-fix-tags-on-the-fly))))
  17701. (defun org-delete-char (N)
  17702. "Like `delete-char', but insert whitespace at field end in tables.
  17703. When deleting characters, in tables this function will insert whitespace in
  17704. front of the next \"|\" separator, to keep the table aligned. The table will
  17705. still be marked for re-alignment if the field did fill the entire column,
  17706. because, in this case the deletion might narrow the column."
  17707. (interactive "p")
  17708. (save-match-data
  17709. (org-check-before-invisible-edit 'delete)
  17710. (cond
  17711. ((or (/= N 1)
  17712. (eq (char-after) ?|)
  17713. (save-excursion (skip-chars-backward " \t") (bolp))
  17714. (not (org-at-table-p)))
  17715. (delete-char N)
  17716. (org-fix-tags-on-the-fly))
  17717. ((looking-at ".\\(.*?\\)|")
  17718. (let* ((update? org-table-may-need-update)
  17719. (noalign (looking-at-p ".*? |")))
  17720. (delete-char 1)
  17721. (org-table-with-shrunk-field
  17722. (save-excursion
  17723. ;; Last space is `org-table-separator-space', so insert
  17724. ;; a regular one before it instead.
  17725. (goto-char (- (match-end 0) 2))
  17726. (insert " ")))
  17727. ;; If there were two spaces at the end, this field does not
  17728. ;; determine the width of the column.
  17729. (when noalign (setq org-table-may-need-update update?))))
  17730. (t
  17731. (delete-char N)))))
  17732. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  17733. (put 'org-self-insert-command 'delete-selection
  17734. (lambda ()
  17735. (not (run-hook-with-args-until-success
  17736. 'self-insert-uses-region-functions))))
  17737. (put 'orgtbl-self-insert-command 'delete-selection
  17738. (lambda ()
  17739. (not (run-hook-with-args-until-success
  17740. 'self-insert-uses-region-functions))))
  17741. (put 'org-delete-char 'delete-selection 'supersede)
  17742. (put 'org-delete-backward-char 'delete-selection 'supersede)
  17743. (put 'org-yank 'delete-selection 'yank)
  17744. ;; Make `flyspell-mode' delay after some commands
  17745. (put 'org-self-insert-command 'flyspell-delayed t)
  17746. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  17747. (put 'org-delete-char 'flyspell-delayed t)
  17748. (put 'org-delete-backward-char 'flyspell-delayed t)
  17749. ;; Make pabbrev-mode expand after Org mode commands
  17750. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  17751. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  17752. (defun org-transpose-words ()
  17753. "Transpose words for Org.
  17754. This uses the `org-mode-transpose-word-syntax-table' syntax
  17755. table, which interprets characters in `org-emphasis-alist' as
  17756. word constituents."
  17757. (interactive)
  17758. (with-syntax-table org-mode-transpose-word-syntax-table
  17759. (call-interactively 'transpose-words)))
  17760. (defvar org-ctrl-c-ctrl-c-hook nil
  17761. "Hook for functions attaching themselves to `C-c C-c'.
  17762. This can be used to add additional functionality to the C-c C-c
  17763. key which executes context-dependent commands. This hook is run
  17764. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  17765. run after the last test.
  17766. Each function will be called with no arguments. The function
  17767. must check if the context is appropriate for it to act. If yes,
  17768. it should do its thing and then return a non-nil value. If the
  17769. context is wrong, just do nothing and return nil.")
  17770. (defvar org-ctrl-c-ctrl-c-final-hook nil
  17771. "Hook for functions attaching themselves to `C-c C-c'.
  17772. This can be used to add additional functionality to the C-c C-c
  17773. key which executes context-dependent commands. This hook is run
  17774. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  17775. before the first test.
  17776. Each function will be called with no arguments. The function
  17777. must check if the context is appropriate for it to act. If yes,
  17778. it should do its thing and then return a non-nil value. If the
  17779. context is wrong, just do nothing and return nil.")
  17780. (defvar org-tab-first-hook nil
  17781. "Hook for functions to attach themselves to TAB.
  17782. See `org-ctrl-c-ctrl-c-hook' for more information.
  17783. This hook runs as the first action when TAB is pressed, even before
  17784. `org-cycle' messes around with the `outline-regexp' to cater for
  17785. inline tasks and plain list item folding.
  17786. If any function in this hook returns t, any other actions that
  17787. would have been caused by TAB (such as table field motion or visibility
  17788. cycling) will not occur.")
  17789. (defvar org-tab-after-check-for-table-hook nil
  17790. "Hook for functions to attach themselves to TAB.
  17791. See `org-ctrl-c-ctrl-c-hook' for more information.
  17792. This hook runs after it has been established that the cursor is not in a
  17793. table, but before checking if the cursor is in a headline or if global cycling
  17794. should be done.
  17795. If any function in this hook returns t, not other actions like visibility
  17796. cycling will be done.")
  17797. (defvar org-tab-after-check-for-cycling-hook nil
  17798. "Hook for functions to attach themselves to TAB.
  17799. See `org-ctrl-c-ctrl-c-hook' for more information.
  17800. This hook runs after it has been established that not table field motion and
  17801. not visibility should be done because of current context. This is probably
  17802. the place where a package like yasnippets can hook in.")
  17803. (defvar org-tab-before-tab-emulation-hook nil
  17804. "Hook for functions to attach themselves to TAB.
  17805. See `org-ctrl-c-ctrl-c-hook' for more information.
  17806. This hook runs after every other options for TAB have been exhausted, but
  17807. before indentation and \t insertion takes place.")
  17808. (defvar org-metaleft-hook nil
  17809. "Hook for functions attaching themselves to `M-left'.
  17810. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17811. (defvar org-metaright-hook nil
  17812. "Hook for functions attaching themselves to `M-right'.
  17813. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17814. (defvar org-metaup-hook nil
  17815. "Hook for functions attaching themselves to `M-up'.
  17816. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17817. (defvar org-metadown-hook nil
  17818. "Hook for functions attaching themselves to `M-down'.
  17819. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17820. (defvar org-shiftmetaleft-hook nil
  17821. "Hook for functions attaching themselves to `M-S-left'.
  17822. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17823. (defvar org-shiftmetaright-hook nil
  17824. "Hook for functions attaching themselves to `M-S-right'.
  17825. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17826. (defvar org-shiftmetaup-hook nil
  17827. "Hook for functions attaching themselves to `M-S-up'.
  17828. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17829. (defvar org-shiftmetadown-hook nil
  17830. "Hook for functions attaching themselves to `M-S-down'.
  17831. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17832. (defvar org-metareturn-hook nil
  17833. "Hook for functions attaching themselves to `M-RET'.
  17834. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17835. (defvar org-shiftup-hook nil
  17836. "Hook for functions attaching themselves to `S-up'.
  17837. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17838. (defvar org-shiftup-final-hook nil
  17839. "Hook for functions attaching themselves to `S-up'.
  17840. This one runs after all other options except shift-select have been excluded.
  17841. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17842. (defvar org-shiftdown-hook nil
  17843. "Hook for functions attaching themselves to `S-down'.
  17844. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17845. (defvar org-shiftdown-final-hook nil
  17846. "Hook for functions attaching themselves to `S-down'.
  17847. This one runs after all other options except shift-select have been excluded.
  17848. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17849. (defvar org-shiftleft-hook nil
  17850. "Hook for functions attaching themselves to `S-left'.
  17851. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17852. (defvar org-shiftleft-final-hook nil
  17853. "Hook for functions attaching themselves to `S-left'.
  17854. This one runs after all other options except shift-select have been excluded.
  17855. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17856. (defvar org-shiftright-hook nil
  17857. "Hook for functions attaching themselves to `S-right'.
  17858. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17859. (defvar org-shiftright-final-hook nil
  17860. "Hook for functions attaching themselves to `S-right'.
  17861. This one runs after all other options except shift-select have been excluded.
  17862. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17863. (defun org-modifier-cursor-error ()
  17864. "Throw an error, a modified cursor command was applied in wrong context."
  17865. (user-error "This command is active in special context like tables, headlines or items"))
  17866. (defun org-shiftselect-error ()
  17867. "Throw an error because Shift-Cursor command was applied in wrong context."
  17868. (if (and (boundp 'shift-select-mode) shift-select-mode)
  17869. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  17870. (user-error "This command works only in special context like headlines or timestamps")))
  17871. (defun org-call-for-shift-select (cmd)
  17872. (let ((this-command-keys-shift-translated t))
  17873. (call-interactively cmd)))
  17874. (defun org-shifttab (&optional arg)
  17875. "Global visibility cycling or move to previous table field.
  17876. Call `org-table-previous-field' within a table.
  17877. When ARG is nil, cycle globally through visibility states.
  17878. When ARG is a numeric prefix, show contents of this level."
  17879. (interactive "P")
  17880. (cond
  17881. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  17882. ((integerp arg)
  17883. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  17884. (message "Content view to level: %d" arg)
  17885. (org-content (prefix-numeric-value arg2))
  17886. (org-cycle-show-empty-lines t)
  17887. (setq org-cycle-global-status 'overview)))
  17888. (t (call-interactively 'org-global-cycle))))
  17889. (defun org-shiftmetaleft ()
  17890. "Promote subtree or delete table column.
  17891. Calls `org-promote-subtree', `org-outdent-item-tree', or
  17892. `org-table-delete-column', depending on context. See the
  17893. individual commands for more information."
  17894. (interactive)
  17895. (cond
  17896. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  17897. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  17898. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  17899. ((if (not (org-region-active-p)) (org-at-item-p)
  17900. (save-excursion (goto-char (region-beginning))
  17901. (org-at-item-p)))
  17902. (call-interactively 'org-outdent-item-tree))
  17903. (t (org-modifier-cursor-error))))
  17904. (defun org-shiftmetaright ()
  17905. "Demote subtree or insert table column.
  17906. Calls `org-demote-subtree', `org-indent-item-tree', or
  17907. `org-table-insert-column', depending on context. See the
  17908. individual commands for more information."
  17909. (interactive)
  17910. (cond
  17911. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  17912. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  17913. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  17914. ((if (not (org-region-active-p)) (org-at-item-p)
  17915. (save-excursion (goto-char (region-beginning))
  17916. (org-at-item-p)))
  17917. (call-interactively 'org-indent-item-tree))
  17918. (t (org-modifier-cursor-error))))
  17919. (defun org-shiftmetaup (&optional _arg)
  17920. "Drag the line at point up.
  17921. In a table, kill the current row.
  17922. On a clock timestamp, update the value of the timestamp like `S-<up>'
  17923. but also adjust the previous clocked item in the clock history.
  17924. Everywhere else, drag the line at point up."
  17925. (interactive "P")
  17926. (cond
  17927. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  17928. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  17929. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17930. (call-interactively 'org-timestamp-up)))
  17931. (t (call-interactively 'org-drag-line-backward))))
  17932. (defun org-shiftmetadown (&optional _arg)
  17933. "Drag the line at point down.
  17934. In a table, insert an empty row at the current line.
  17935. On a clock timestamp, update the value of the timestamp like `S-<down>'
  17936. but also adjust the previous clocked item in the clock history.
  17937. Everywhere else, drag the line at point down."
  17938. (interactive "P")
  17939. (cond
  17940. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  17941. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  17942. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17943. (call-interactively 'org-timestamp-down)))
  17944. (t (call-interactively 'org-drag-line-forward))))
  17945. (defsubst org-hidden-tree-error ()
  17946. (user-error
  17947. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  17948. (defun org-metaleft (&optional _arg)
  17949. "Promote heading, list item at point or move table column left.
  17950. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  17951. depending on context. With no specific context, calls the Emacs
  17952. default `backward-word'. See the individual commands for more
  17953. information.
  17954. This function runs the hook `org-metaleft-hook' as a first step,
  17955. and returns at first non-nil value."
  17956. (interactive "P")
  17957. (cond
  17958. ((run-hook-with-args-until-success 'org-metaleft-hook))
  17959. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  17960. ((org-with-limited-levels
  17961. (or (org-at-heading-p)
  17962. (and (org-region-active-p)
  17963. (save-excursion
  17964. (goto-char (region-beginning))
  17965. (org-at-heading-p)))))
  17966. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  17967. (call-interactively 'org-do-promote))
  17968. ;; At an inline task.
  17969. ((org-at-heading-p)
  17970. (call-interactively 'org-inlinetask-promote))
  17971. ((or (org-at-item-p)
  17972. (and (org-region-active-p)
  17973. (save-excursion
  17974. (goto-char (region-beginning))
  17975. (org-at-item-p))))
  17976. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  17977. (call-interactively 'org-outdent-item))
  17978. (t (call-interactively 'backward-word))))
  17979. (defun org-metaright (&optional _arg)
  17980. "Demote heading, list item at point or move table column right.
  17981. In front of a drawer or a block keyword, indent it correctly.
  17982. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  17983. `org-indent-drawer' or `org-indent-block' depending on context.
  17984. With no specific context, calls the Emacs default `forward-word'.
  17985. See the individual commands for more information.
  17986. This function runs the hook `org-metaright-hook' as a first step,
  17987. and returns at first non-nil value."
  17988. (interactive "P")
  17989. (cond
  17990. ((run-hook-with-args-until-success 'org-metaright-hook))
  17991. ((org-at-table-p) (call-interactively 'org-table-move-column))
  17992. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  17993. ((org-at-block-p) (call-interactively 'org-indent-block))
  17994. ((org-with-limited-levels
  17995. (or (org-at-heading-p)
  17996. (and (org-region-active-p)
  17997. (save-excursion
  17998. (goto-char (region-beginning))
  17999. (org-at-heading-p)))))
  18000. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18001. (call-interactively 'org-do-demote))
  18002. ;; At an inline task.
  18003. ((org-at-heading-p)
  18004. (call-interactively 'org-inlinetask-demote))
  18005. ((or (org-at-item-p)
  18006. (and (org-region-active-p)
  18007. (save-excursion
  18008. (goto-char (region-beginning))
  18009. (org-at-item-p))))
  18010. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18011. (call-interactively 'org-indent-item))
  18012. (t (call-interactively 'forward-word))))
  18013. (defun org-check-for-hidden (what)
  18014. "Check if there are hidden headlines/items in the current visual line.
  18015. WHAT can be either `headlines' or `items'. If the current line is
  18016. an outline or item heading and it has a folded subtree below it,
  18017. this function returns t, nil otherwise."
  18018. (let ((re (cond
  18019. ((eq what 'headlines) org-outline-regexp-bol)
  18020. ((eq what 'items) (org-item-beginning-re))
  18021. (t (error "This should not happen"))))
  18022. beg end)
  18023. (save-excursion
  18024. (catch 'exit
  18025. (unless (org-region-active-p)
  18026. (setq beg (point-at-bol))
  18027. (beginning-of-line 2)
  18028. (while (and (not (eobp)) ;; this is like `next-line'
  18029. (get-char-property (1- (point)) 'invisible))
  18030. (beginning-of-line 2))
  18031. (setq end (point))
  18032. (goto-char beg)
  18033. (goto-char (point-at-eol))
  18034. (setq end (max end (point)))
  18035. (while (re-search-forward re end t)
  18036. (when (get-char-property (match-beginning 0) 'invisible)
  18037. (throw 'exit t))))
  18038. nil))))
  18039. (defun org-metaup (&optional _arg)
  18040. "Move subtree up or move table row up.
  18041. Calls `org-move-subtree-up' or `org-table-move-row' or
  18042. `org-move-item-up', depending on context. See the individual commands
  18043. for more information."
  18044. (interactive "P")
  18045. (cond
  18046. ((run-hook-with-args-until-success 'org-metaup-hook))
  18047. ((org-region-active-p)
  18048. (let* ((a (min (region-beginning) (region-end)))
  18049. (b (1- (max (region-beginning) (region-end))))
  18050. (c (save-excursion (goto-char a)
  18051. (move-beginning-of-line 0)))
  18052. (d (save-excursion (goto-char a)
  18053. (move-end-of-line 0) (point))))
  18054. (transpose-regions a b c d)
  18055. (goto-char c)))
  18056. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18057. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18058. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18059. (t (org-drag-element-backward))))
  18060. (defun org-metadown (&optional _arg)
  18061. "Move subtree down or move table row down.
  18062. Calls `org-move-subtree-down' or `org-table-move-row' or
  18063. `org-move-item-down', depending on context. See the individual
  18064. commands for more information."
  18065. (interactive "P")
  18066. (cond
  18067. ((run-hook-with-args-until-success 'org-metadown-hook))
  18068. ((org-region-active-p)
  18069. (let* ((a (min (region-beginning) (region-end)))
  18070. (b (max (region-beginning) (region-end)))
  18071. (c (save-excursion (goto-char b)
  18072. (move-beginning-of-line 1)))
  18073. (d (save-excursion (goto-char b)
  18074. (move-end-of-line 1) (1+ (point)))))
  18075. (transpose-regions a b c d)
  18076. (goto-char d)))
  18077. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18078. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18079. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18080. (t (org-drag-element-forward))))
  18081. (defun org-shiftup (&optional arg)
  18082. "Increase item in timestamp or increase priority of current headline.
  18083. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18084. depending on context. See the individual commands for more information."
  18085. (interactive "P")
  18086. (cond
  18087. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18088. ((and org-support-shift-select (org-region-active-p))
  18089. (org-call-for-shift-select 'previous-line))
  18090. ((org-at-timestamp-p 'lax)
  18091. (call-interactively (if org-edit-timestamp-down-means-later
  18092. 'org-timestamp-down 'org-timestamp-up)))
  18093. ((and (not (eq org-support-shift-select 'always))
  18094. org-enable-priority-commands
  18095. (org-at-heading-p))
  18096. (call-interactively 'org-priority-up))
  18097. ((and (not org-support-shift-select) (org-at-item-p))
  18098. (call-interactively 'org-previous-item))
  18099. ((org-clocktable-try-shift 'up arg))
  18100. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18101. (org-support-shift-select
  18102. (org-call-for-shift-select 'previous-line))
  18103. (t (org-shiftselect-error))))
  18104. (defun org-shiftdown (&optional arg)
  18105. "Decrease item in timestamp or decrease priority of current headline.
  18106. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18107. depending on context. See the individual commands for more information."
  18108. (interactive "P")
  18109. (cond
  18110. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18111. ((and org-support-shift-select (org-region-active-p))
  18112. (org-call-for-shift-select 'next-line))
  18113. ((org-at-timestamp-p 'lax)
  18114. (call-interactively (if org-edit-timestamp-down-means-later
  18115. 'org-timestamp-up 'org-timestamp-down)))
  18116. ((and (not (eq org-support-shift-select 'always))
  18117. org-enable-priority-commands
  18118. (org-at-heading-p))
  18119. (call-interactively 'org-priority-down))
  18120. ((and (not org-support-shift-select) (org-at-item-p))
  18121. (call-interactively 'org-next-item))
  18122. ((org-clocktable-try-shift 'down arg))
  18123. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18124. (org-support-shift-select
  18125. (org-call-for-shift-select 'next-line))
  18126. (t (org-shiftselect-error))))
  18127. (defun org-shiftright (&optional arg)
  18128. "Cycle the thing at point or in the current line, depending on context.
  18129. Depending on context, this does one of the following:
  18130. - switch a timestamp at point one day into the future
  18131. - on a headline, switch to the next TODO keyword.
  18132. - on an item, switch entire list to the next bullet type
  18133. - on a property line, switch to the next allowed value
  18134. - on a clocktable definition line, move time block into the future"
  18135. (interactive "P")
  18136. (cond
  18137. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18138. ((and org-support-shift-select (org-region-active-p))
  18139. (org-call-for-shift-select 'forward-char))
  18140. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  18141. ((and (not (eq org-support-shift-select 'always))
  18142. (org-at-heading-p))
  18143. (let ((org-inhibit-logging
  18144. (not org-treat-S-cursor-todo-selection-as-state-change))
  18145. (org-inhibit-blocking
  18146. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18147. (org-call-with-arg 'org-todo 'right)))
  18148. ((or (and org-support-shift-select
  18149. (not (eq org-support-shift-select 'always))
  18150. (org-at-item-bullet-p))
  18151. (and (not org-support-shift-select) (org-at-item-p)))
  18152. (org-call-with-arg 'org-cycle-list-bullet nil))
  18153. ((and (not (eq org-support-shift-select 'always))
  18154. (org-at-property-p))
  18155. (call-interactively 'org-property-next-allowed-value))
  18156. ((org-clocktable-try-shift 'right arg))
  18157. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18158. (org-support-shift-select
  18159. (org-call-for-shift-select 'forward-char))
  18160. (t (org-shiftselect-error))))
  18161. (defun org-shiftleft (&optional arg)
  18162. "Cycle the thing at point or in the current line, depending on context.
  18163. Depending on context, this does one of the following:
  18164. - switch a timestamp at point one day into the past
  18165. - on a headline, switch to the previous TODO keyword.
  18166. - on an item, switch entire list to the previous bullet type
  18167. - on a property line, switch to the previous allowed value
  18168. - on a clocktable definition line, move time block into the past"
  18169. (interactive "P")
  18170. (cond
  18171. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18172. ((and org-support-shift-select (org-region-active-p))
  18173. (org-call-for-shift-select 'backward-char))
  18174. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  18175. ((and (not (eq org-support-shift-select 'always))
  18176. (org-at-heading-p))
  18177. (let ((org-inhibit-logging
  18178. (not org-treat-S-cursor-todo-selection-as-state-change))
  18179. (org-inhibit-blocking
  18180. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18181. (org-call-with-arg 'org-todo 'left)))
  18182. ((or (and org-support-shift-select
  18183. (not (eq org-support-shift-select 'always))
  18184. (org-at-item-bullet-p))
  18185. (and (not org-support-shift-select) (org-at-item-p)))
  18186. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  18187. ((and (not (eq org-support-shift-select 'always))
  18188. (org-at-property-p))
  18189. (call-interactively 'org-property-previous-allowed-value))
  18190. ((org-clocktable-try-shift 'left arg))
  18191. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  18192. (org-support-shift-select
  18193. (org-call-for-shift-select 'backward-char))
  18194. (t (org-shiftselect-error))))
  18195. (defun org-shiftcontrolright ()
  18196. "Switch to next TODO set."
  18197. (interactive)
  18198. (cond
  18199. ((and org-support-shift-select (org-region-active-p))
  18200. (org-call-for-shift-select 'forward-word))
  18201. ((and (not (eq org-support-shift-select 'always))
  18202. (org-at-heading-p))
  18203. (org-call-with-arg 'org-todo 'nextset))
  18204. (org-support-shift-select
  18205. (org-call-for-shift-select 'forward-word))
  18206. (t (org-shiftselect-error))))
  18207. (defun org-shiftcontrolleft ()
  18208. "Switch to previous TODO set."
  18209. (interactive)
  18210. (cond
  18211. ((and org-support-shift-select (org-region-active-p))
  18212. (org-call-for-shift-select 'backward-word))
  18213. ((and (not (eq org-support-shift-select 'always))
  18214. (org-at-heading-p))
  18215. (org-call-with-arg 'org-todo 'previousset))
  18216. (org-support-shift-select
  18217. (org-call-for-shift-select 'backward-word))
  18218. (t (org-shiftselect-error))))
  18219. (defun org-shiftcontrolup (&optional n)
  18220. "Change timestamps synchronously up in CLOCK log lines.
  18221. Optional argument N tells to change by that many units."
  18222. (interactive "P")
  18223. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18224. (let (org-support-shift-select)
  18225. (org-clock-timestamps-up n))
  18226. (user-error "Not at a clock log")))
  18227. (defun org-shiftcontroldown (&optional n)
  18228. "Change timestamps synchronously down in CLOCK log lines.
  18229. Optional argument N tells to change by that many units."
  18230. (interactive "P")
  18231. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18232. (let (org-support-shift-select)
  18233. (org-clock-timestamps-down n))
  18234. (user-error "Not at a clock log")))
  18235. (defun org-increase-number-at-point (&optional inc)
  18236. "Increment the number at point.
  18237. With an optional prefix numeric argument INC, increment using
  18238. this numeric value."
  18239. (interactive "p")
  18240. (if (not (number-at-point))
  18241. (user-error "Not on a number")
  18242. (unless inc (setq inc 1))
  18243. (let ((pos (point))
  18244. (beg (skip-chars-backward "-+^/*0-9eE."))
  18245. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  18246. (setq nap (buffer-substring-no-properties
  18247. (+ pos beg) (+ pos beg end)))
  18248. (delete-region (+ pos beg) (+ pos beg end))
  18249. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18250. (when (org-at-table-p)
  18251. (org-table-align)
  18252. (org-table-end-of-field 1))))
  18253. (defun org-decrease-number-at-point (&optional inc)
  18254. "Decrement the number at point.
  18255. With an optional prefix numeric argument INC, decrement using
  18256. this numeric value."
  18257. (interactive "p")
  18258. (org-increase-number-at-point (- (or inc 1))))
  18259. (defun org-ctrl-c-ret ()
  18260. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  18261. (interactive)
  18262. (cond
  18263. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18264. (t (call-interactively 'org-insert-heading))))
  18265. (defun org-find-visible ()
  18266. (let ((s (point)))
  18267. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18268. (get-char-property s 'invisible)))
  18269. s))
  18270. (defun org-find-invisible ()
  18271. (let ((s (point)))
  18272. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18273. (not (get-char-property s 'invisible))))
  18274. s))
  18275. (defun org-copy-visible (beg end)
  18276. "Copy the visible parts of the region."
  18277. (interactive "r")
  18278. (let ((result ""))
  18279. (while (/= beg end)
  18280. (when (get-char-property beg 'invisible)
  18281. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  18282. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  18283. (setq result (concat result (buffer-substring beg next)))
  18284. (setq beg next)))
  18285. (kill-new result)
  18286. (message "Visible strings have been copied to the kill ring.")))
  18287. (defun org-copy-special ()
  18288. "Copy region in table or copy current subtree.
  18289. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18290. context. See the individual commands for more information."
  18291. (interactive)
  18292. (call-interactively
  18293. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18294. (defun org-cut-special ()
  18295. "Cut region in table or cut current subtree.
  18296. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  18297. context. See the individual commands for more information."
  18298. (interactive)
  18299. (call-interactively
  18300. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  18301. (defun org-paste-special (arg)
  18302. "Paste rectangular region into table, or past subtree relative to level.
  18303. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18304. See the individual commands for more information."
  18305. (interactive "P")
  18306. (if (org-at-table-p)
  18307. (org-table-paste-rectangle)
  18308. (org-paste-subtree arg)))
  18309. (defun org-edit-special (&optional arg)
  18310. "Call a special editor for the element at point.
  18311. When at a table, call the formula editor with `org-table-edit-formulas'.
  18312. When in a source code block, call `org-edit-src-code'.
  18313. When in a fixed-width region, call `org-edit-fixed-width-region'.
  18314. When in an export block, call `org-edit-export-block'.
  18315. When in a LaTeX environment, call `org-edit-latex-environment'.
  18316. When at an #+INCLUDE keyword, visit the included file.
  18317. When at a footnote reference, call `org-edit-footnote-reference'
  18318. On a link, call `ffap' to visit the link at point.
  18319. Otherwise, return a user error."
  18320. (interactive "P")
  18321. (let ((element (org-element-at-point)))
  18322. (barf-if-buffer-read-only)
  18323. (pcase (org-element-type element)
  18324. (`src-block
  18325. (if (not arg) (org-edit-src-code)
  18326. (let* ((info (org-babel-get-src-block-info))
  18327. (lang (nth 0 info))
  18328. (params (nth 2 info))
  18329. (session (cdr (assq :session params))))
  18330. (if (not session) (org-edit-src-code)
  18331. ;; At a src-block with a session and function called with
  18332. ;; an ARG: switch to the buffer related to the inferior
  18333. ;; process.
  18334. (switch-to-buffer
  18335. (funcall (intern (concat "org-babel-prep-session:" lang))
  18336. session params))))))
  18337. (`keyword
  18338. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  18339. (org-open-link-from-string
  18340. (format "[[%s]]"
  18341. (expand-file-name
  18342. (let ((value (org-element-property :value element)))
  18343. (cond ((org-file-url-p value)
  18344. (user-error "The file is specified as a URL, cannot be edited"))
  18345. ((not (org-string-nw-p value))
  18346. (user-error "No file to edit"))
  18347. ((string-match "\\`\"\\(.*?\\)\"" value)
  18348. (match-string 1 value))
  18349. ((string-match "\\`[^ \t\"]\\S-*" value)
  18350. (match-string 0 value))
  18351. (t (user-error "No valid file specified")))))))
  18352. (user-error "No special environment to edit here")))
  18353. (`table
  18354. (if (eq (org-element-property :type element) 'table.el)
  18355. (org-edit-table.el)
  18356. (call-interactively 'org-table-edit-formulas)))
  18357. ;; Only Org tables contain `table-row' type elements.
  18358. (`table-row (call-interactively 'org-table-edit-formulas))
  18359. (`example-block (org-edit-src-code))
  18360. (`export-block (org-edit-export-block))
  18361. (`fixed-width (org-edit-fixed-width-region))
  18362. (`latex-environment (org-edit-latex-environment))
  18363. (_
  18364. ;; No notable element at point. Though, we may be at a link or
  18365. ;; a footnote reference, which are objects. Thus, scan deeper.
  18366. (let ((context (org-element-context element)))
  18367. (pcase (org-element-type context)
  18368. (`footnote-reference (org-edit-footnote-reference))
  18369. (`inline-src-block (org-edit-inline-src-code))
  18370. (`link (call-interactively #'ffap))
  18371. (_ (user-error "No special environment to edit here"))))))))
  18372. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  18373. (defun org-ctrl-c-ctrl-c (&optional arg)
  18374. "Set tags in headline, or update according to changed information at point.
  18375. This command does many different things, depending on context:
  18376. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  18377. this is what we do.
  18378. - If the cursor is on a statistics cookie, update it.
  18379. - If the cursor is in a headline, prompt for tags and insert them
  18380. into the current line, aligned to `org-tags-column'. When called
  18381. with prefix arg, realign all tags in the current buffer.
  18382. - If the cursor is in one of the special #+KEYWORD lines, this
  18383. triggers scanning the buffer for these lines and updating the
  18384. information.
  18385. - If the cursor is inside a table, realign the table. This command
  18386. works even if the automatic table editor has been turned off.
  18387. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  18388. the entire table.
  18389. - If the cursor is at a footnote reference or definition, jump to
  18390. the corresponding definition or references, respectively.
  18391. - If the cursor is a the beginning of a dynamic block, update it.
  18392. - If the current buffer is a capture buffer, close note and file it.
  18393. - If the cursor is on a <<<target>>>, update radio targets and
  18394. corresponding links in this buffer.
  18395. - If the cursor is on a numbered item in a plain list, renumber the
  18396. ordered list.
  18397. - If the cursor is on a checkbox, toggle it.
  18398. - If the cursor is on a code block, evaluate it. The variable
  18399. `org-confirm-babel-evaluate' can be used to control prompting
  18400. before code block evaluation, by default every code block
  18401. evaluation requires confirmation. Code block evaluation can be
  18402. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  18403. (interactive "P")
  18404. (cond
  18405. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  18406. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  18407. (org-remove-occur-highlights)
  18408. (message "Temporary highlights/overlays removed from current buffer"))
  18409. ((and (local-variable-p 'org-finish-function)
  18410. (fboundp org-finish-function))
  18411. (funcall org-finish-function))
  18412. ((org-babel-hash-at-point))
  18413. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  18414. (t
  18415. (let* ((context
  18416. (org-element-lineage
  18417. (org-element-context)
  18418. ;; Limit to supported contexts.
  18419. '(babel-call clock dynamic-block footnote-definition
  18420. footnote-reference inline-babel-call inline-src-block
  18421. inlinetask item keyword node-property paragraph
  18422. plain-list planning property-drawer radio-target
  18423. src-block statistics-cookie table table-cell table-row
  18424. timestamp)
  18425. t))
  18426. (type (org-element-type context)))
  18427. ;; For convenience: at the first line of a paragraph on the same
  18428. ;; line as an item, apply function on that item instead.
  18429. (when (eq type 'paragraph)
  18430. (let ((parent (org-element-property :parent context)))
  18431. (when (and (eq (org-element-type parent) 'item)
  18432. (= (line-beginning-position)
  18433. (org-element-property :begin parent)))
  18434. (setq context parent)
  18435. (setq type 'item))))
  18436. ;; Act according to type of element or object at point.
  18437. ;;
  18438. ;; Do nothing on a blank line, except if it is contained in
  18439. ;; a src block. Hence, we first check if point is in such
  18440. ;; a block and then if it is at a blank line.
  18441. (pcase type
  18442. ((or `inline-src-block `src-block)
  18443. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  18444. (org-babel-eval-wipe-error-buffer)
  18445. (org-babel-execute-src-block
  18446. current-prefix-arg (org-babel-get-src-block-info nil context))))
  18447. ((guard (org-match-line "[ \t]*$"))
  18448. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  18449. (user-error
  18450. (substitute-command-keys
  18451. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  18452. ((or `babel-call `inline-babel-call)
  18453. (let ((info (org-babel-lob-get-info context)))
  18454. (when info (org-babel-execute-src-block nil info))))
  18455. (`clock (org-clock-update-time-maybe))
  18456. (`dynamic-block
  18457. (save-excursion
  18458. (goto-char (org-element-property :post-affiliated context))
  18459. (org-update-dblock)))
  18460. (`footnote-definition
  18461. (goto-char (org-element-property :post-affiliated context))
  18462. (call-interactively 'org-footnote-action))
  18463. (`footnote-reference (call-interactively #'org-footnote-action))
  18464. ((or `headline `inlinetask)
  18465. (save-excursion (goto-char (org-element-property :begin context))
  18466. (call-interactively #'org-set-tags-command)))
  18467. (`item
  18468. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  18469. ;; unconditionally, whereas `C-u' will toggle its presence.
  18470. ;; Without a universal argument, if the item has a checkbox,
  18471. ;; toggle it. Otherwise repair the list.
  18472. (let* ((box (org-element-property :checkbox context))
  18473. (struct (org-element-property :structure context))
  18474. (old-struct (copy-tree struct))
  18475. (parents (org-list-parents-alist struct))
  18476. (prevs (org-list-prevs-alist struct))
  18477. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  18478. (org-list-set-checkbox
  18479. (org-element-property :begin context) struct
  18480. (cond ((equal arg '(16)) "[-]")
  18481. ((and (not box) (equal arg '(4))) "[ ]")
  18482. ((or (not box) (equal arg '(4))) nil)
  18483. ((eq box 'on) "[ ]")
  18484. (t "[X]")))
  18485. ;; Mimic `org-list-write-struct' but with grabbing a return
  18486. ;; value from `org-list-struct-fix-box'.
  18487. (org-list-struct-fix-ind struct parents 2)
  18488. (org-list-struct-fix-item-end struct)
  18489. (org-list-struct-fix-bul struct prevs)
  18490. (org-list-struct-fix-ind struct parents)
  18491. (let ((block-item
  18492. (org-list-struct-fix-box struct parents prevs orderedp)))
  18493. (if (and box (equal struct old-struct))
  18494. (if (equal arg '(16))
  18495. (message "Checkboxes already reset")
  18496. (user-error "Cannot toggle this checkbox: %s"
  18497. (if (eq box 'on)
  18498. "all subitems checked"
  18499. "unchecked subitems")))
  18500. (org-list-struct-apply-struct struct old-struct)
  18501. (org-update-checkbox-count-maybe))
  18502. (when block-item
  18503. (message "Checkboxes were removed due to empty box at line %d"
  18504. (org-current-line block-item))))))
  18505. (`keyword
  18506. (let ((org-inhibit-startup-visibility-stuff t)
  18507. (org-startup-align-all-tables nil))
  18508. (when (boundp 'org-table-coordinate-overlays)
  18509. (mapc #'delete-overlay org-table-coordinate-overlays)
  18510. (setq org-table-coordinate-overlays nil))
  18511. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  18512. (message "Local setup has been refreshed"))
  18513. (`plain-list
  18514. ;; At a plain list, with a double C-u argument, set
  18515. ;; checkboxes of each item to "[-]", whereas a single one
  18516. ;; will toggle their presence according to the state of the
  18517. ;; first item in the list. Without an argument, repair the
  18518. ;; list.
  18519. (let* ((begin (org-element-property :contents-begin context))
  18520. (struct (org-element-property :structure context))
  18521. (old-struct (copy-tree struct))
  18522. (first-box (save-excursion
  18523. (goto-char begin)
  18524. (looking-at org-list-full-item-re)
  18525. (match-string-no-properties 3)))
  18526. (new-box (cond ((equal arg '(16)) "[-]")
  18527. ((equal arg '(4)) (unless first-box "[ ]"))
  18528. ((equal first-box "[X]") "[ ]")
  18529. (t "[X]"))))
  18530. (cond
  18531. (arg
  18532. (dolist (pos
  18533. (org-list-get-all-items
  18534. begin struct (org-list-prevs-alist struct)))
  18535. (org-list-set-checkbox pos struct new-box)))
  18536. ((and first-box (eq (point) begin))
  18537. ;; For convenience, when point is at bol on the first
  18538. ;; item of the list and no argument is provided, simply
  18539. ;; toggle checkbox of that item, if any.
  18540. (org-list-set-checkbox begin struct new-box)))
  18541. (when (equal
  18542. (org-list-write-struct
  18543. struct (org-list-parents-alist struct) old-struct)
  18544. old-struct)
  18545. (message "Cannot update this checkbox"))
  18546. (org-update-checkbox-count-maybe)))
  18547. ((or `property-drawer `node-property)
  18548. (call-interactively #'org-property-action))
  18549. (`radio-target
  18550. (call-interactively #'org-update-radio-target-regexp))
  18551. (`statistics-cookie
  18552. (call-interactively #'org-update-statistics-cookies))
  18553. ((or `table `table-cell `table-row)
  18554. ;; At a table, recalculate every field and align it. Also
  18555. ;; send the table if necessary. If the table has
  18556. ;; a `table.el' type, just give up. At a table row or cell,
  18557. ;; maybe recalculate line but always align table.
  18558. (if (eq (org-element-property :type context) 'table.el)
  18559. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  18560. Use `\\[org-edit-special]' to edit table.el tables"))
  18561. (if (or (eq type 'table)
  18562. ;; Check if point is at a TBLFM line.
  18563. (and (eq type 'table-row)
  18564. (= (point) (org-element-property :end context))))
  18565. (save-excursion
  18566. (if (org-at-TBLFM-p)
  18567. (progn (require 'org-table)
  18568. (org-table-calc-current-TBLFM))
  18569. (goto-char (org-element-property :contents-begin context))
  18570. (org-call-with-arg 'org-table-recalculate (or arg t))
  18571. (orgtbl-send-table 'maybe)))
  18572. (org-table-maybe-eval-formula)
  18573. (cond (arg (call-interactively #'org-table-recalculate))
  18574. ((org-table-maybe-recalculate-line))
  18575. (t (org-table-align))))))
  18576. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  18577. (org-timestamp-change 0 'day))
  18578. ((and `nil (guard (org-at-heading-p)))
  18579. ;; When point is on an unsupported object type, we can miss
  18580. ;; the fact that it also is at a heading. Handle it here.
  18581. (call-interactively #'org-set-tags-command))
  18582. ((guard
  18583. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  18584. (_
  18585. (user-error
  18586. (substitute-command-keys
  18587. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  18588. (defun org-mode-restart ()
  18589. (interactive)
  18590. (let ((indent-status (bound-and-true-p org-indent-mode)))
  18591. (funcall major-mode)
  18592. (hack-local-variables)
  18593. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  18594. (org-indent-mode -1))
  18595. (org-reset-file-cache))
  18596. (message "%s restarted" major-mode))
  18597. (defun org-kill-note-or-show-branches ()
  18598. "Abort storing current note, or call `outline-show-branches'."
  18599. (interactive)
  18600. (if (not org-finish-function)
  18601. (save-excursion
  18602. (save-restriction
  18603. (org-narrow-to-subtree)
  18604. (org-flag-subtree t)
  18605. (call-interactively 'outline-show-branches)
  18606. (org-hide-archived-subtrees (point-min) (point-max))))
  18607. (let ((org-note-abort t))
  18608. (funcall org-finish-function))))
  18609. (defun org-delete-indentation (&optional arg)
  18610. "Join current line to previous and fix whitespace at join.
  18611. If previous line is a headline add to headline title. Otherwise
  18612. the function calls `delete-indentation'.
  18613. With a non-nil optional argument, join it to the following one."
  18614. (interactive "*P")
  18615. (if (save-excursion
  18616. (beginning-of-line (if arg 1 0))
  18617. (let ((case-fold-search nil))
  18618. (looking-at org-complex-heading-regexp)))
  18619. ;; At headline.
  18620. (let ((tags-column (when (match-beginning 5)
  18621. (save-excursion (goto-char (match-beginning 5))
  18622. (current-column))))
  18623. (string (concat " " (progn (when arg (forward-line 1))
  18624. (org-trim (delete-and-extract-region
  18625. (line-beginning-position)
  18626. (line-end-position)))))))
  18627. (unless (bobp) (delete-region (point) (1- (point))))
  18628. (goto-char (or (match-end 4)
  18629. (match-beginning 5)
  18630. (match-end 0)))
  18631. (skip-chars-backward " \t")
  18632. (save-excursion (insert string))
  18633. ;; Adjust alignment of tags.
  18634. (cond
  18635. ((not tags-column)) ;no tags
  18636. (org-auto-align-tags (org-align-tags))
  18637. (t (org--align-tags-here tags-column)))) ;preserve tags column
  18638. (delete-indentation arg)))
  18639. (defun org-open-line (n)
  18640. "Insert a new row in tables, call `open-line' elsewhere.
  18641. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  18642. As a special case, when a document starts with a table, allow to
  18643. call `open-line' on the very first character."
  18644. (interactive "*p")
  18645. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  18646. (org-table-insert-row)
  18647. (open-line n)))
  18648. (defun org-return (&optional indent)
  18649. "Goto next table row or insert a newline.
  18650. Calls `org-table-next-row' or `newline', depending on context.
  18651. When optional INDENT argument is non-nil, call
  18652. `newline-and-indent' instead of `newline'.
  18653. When `org-return-follows-link' is non-nil and point is on
  18654. a timestamp or a link, call `org-open-at-point'. However, it
  18655. will not happen if point is in a table or on a \"dead\"
  18656. object (e.g., within a comment). In these case, you need to use
  18657. `org-open-at-point' directly."
  18658. (interactive)
  18659. (let ((context (if org-return-follows-link (org-element-context)
  18660. (org-element-at-point))))
  18661. (cond
  18662. ;; In a table, call `org-table-next-row'. However, before first
  18663. ;; column or after last one, split the table.
  18664. ((or (and (eq (org-element-type context) 'table)
  18665. (>= (point) (org-element-property :contents-begin context))
  18666. (< (point) (org-element-property :contents-end context)))
  18667. (org-element-lineage context '(table-row table-cell) t))
  18668. (if (or (looking-at-p "[ \t]*$")
  18669. (save-excursion (skip-chars-backward " \t") (bolp)))
  18670. (insert "\n")
  18671. (org-table-justify-field-maybe)
  18672. (call-interactively #'org-table-next-row)))
  18673. ;; On a link or a timestamp, call `org-open-at-point' if
  18674. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  18675. ;; locations, e.g., in a comment, as `org-open-at-point'.
  18676. ((and org-return-follows-link
  18677. (or (and (eq 'link (org-element-type context))
  18678. ;; Ensure point is not on the white spaces after
  18679. ;; the link.
  18680. (let ((origin (point)))
  18681. (org-with-point-at (org-element-property :end context)
  18682. (skip-chars-backward " \t")
  18683. (> (point) origin))))
  18684. (org-in-regexp org-ts-regexp-both nil t)
  18685. (org-in-regexp org-tsr-regexp-both nil t)
  18686. (org-in-regexp org-any-link-re nil t)))
  18687. (call-interactively #'org-open-at-point))
  18688. ;; Insert newline in heading, but preserve tags.
  18689. ((and (not (bolp))
  18690. (save-excursion (beginning-of-line)
  18691. (let ((case-fold-search nil))
  18692. (looking-at org-complex-heading-regexp))))
  18693. ;; At headline. Split line. However, if point is on keyword,
  18694. ;; priority cookie or tags, do not break any of them: add
  18695. ;; a newline after the headline instead.
  18696. (let ((tags-column (and (match-beginning 5)
  18697. (save-excursion (goto-char (match-beginning 5))
  18698. (current-column))))
  18699. (string
  18700. (when (and (match-end 4) (org-point-in-group (point) 4))
  18701. (delete-and-extract-region (point) (match-end 4)))))
  18702. ;; Adjust tag alignment.
  18703. (cond
  18704. ((not (and tags-column string)))
  18705. (org-auto-align-tags (org-align-tags))
  18706. (t (org--align-tags-here tags-column))) ;preserve tags column
  18707. (end-of-line)
  18708. (org-show-entry)
  18709. (if indent (newline-and-indent) (newline))
  18710. (when string (save-excursion (insert (org-trim string))))))
  18711. ;; In a list, make sure indenting keeps trailing text within.
  18712. ((and indent
  18713. (not (eolp))
  18714. (org-element-lineage context '(item)))
  18715. (let ((trailing-data
  18716. (delete-and-extract-region (point) (line-end-position))))
  18717. (newline-and-indent)
  18718. (save-excursion (insert trailing-data))))
  18719. (t
  18720. ;; Do not auto-fill when point is in an Org property drawer.
  18721. (let ((auto-fill-function (and (not (org-at-property-p))
  18722. auto-fill-function)))
  18723. (if indent
  18724. (newline-and-indent)
  18725. (newline)))))))
  18726. (defun org-return-indent ()
  18727. "Goto next table row or insert a newline and indent.
  18728. Calls `org-table-next-row' or `newline-and-indent', depending on
  18729. context. See the individual commands for more information."
  18730. (interactive)
  18731. (org-return t))
  18732. (defun org-ctrl-c-tab (&optional _arg)
  18733. "Toggle columns width in a table, or show children.
  18734. Call `org-table-toggle-column-width' if point is in a table.
  18735. Otherwise, call `org-show-children'."
  18736. (interactive "p")
  18737. (call-interactively
  18738. (if (org-at-table-p) #'org-table-toggle-column-width
  18739. #'org-show-children)))
  18740. (defun org-ctrl-c-star ()
  18741. "Compute table, or change heading status of lines.
  18742. Calls `org-table-recalculate' or `org-toggle-heading',
  18743. depending on context."
  18744. (interactive)
  18745. (cond
  18746. ((org-at-table-p)
  18747. (call-interactively 'org-table-recalculate))
  18748. (t
  18749. ;; Convert all lines in region to list items
  18750. (call-interactively 'org-toggle-heading))))
  18751. (defun org-ctrl-c-minus ()
  18752. "Insert separator line in table or modify bullet status of line.
  18753. Also turns a plain line or a region of lines into list items.
  18754. Calls `org-table-insert-hline', `org-toggle-item', or
  18755. `org-cycle-list-bullet', depending on context."
  18756. (interactive)
  18757. (cond
  18758. ((org-at-table-p)
  18759. (call-interactively 'org-table-insert-hline))
  18760. ((org-region-active-p)
  18761. (call-interactively 'org-toggle-item))
  18762. ((org-in-item-p)
  18763. (call-interactively 'org-cycle-list-bullet))
  18764. (t
  18765. (call-interactively 'org-toggle-item))))
  18766. (defun org-toggle-heading (&optional nstars)
  18767. "Convert headings to normal text, or items or text to headings.
  18768. If there is no active region, only convert the current line.
  18769. With a `\\[universal-argument]' prefix, convert the whole list at
  18770. point into heading.
  18771. In a region:
  18772. - If the first non blank line is a headline, remove the stars
  18773. from all headlines in the region.
  18774. - If it is a normal line, turn each and every normal line (i.e.,
  18775. not an heading or an item) in the region into headings. If you
  18776. want to convert only the first line of this region, use one
  18777. universal prefix argument.
  18778. - If it is a plain list item, turn all plain list items into headings.
  18779. When converting a line into a heading, the number of stars is chosen
  18780. such that the lines become children of the current entry. However,
  18781. when a numeric prefix argument is given, its value determines the
  18782. number of stars to add."
  18783. (interactive "P")
  18784. (let ((skip-blanks
  18785. (function
  18786. ;; Return beginning of first non-blank line, starting from
  18787. ;; line at POS.
  18788. (lambda (pos)
  18789. (save-excursion
  18790. (goto-char pos)
  18791. (while (org-at-comment-p) (forward-line))
  18792. (skip-chars-forward " \r\t\n")
  18793. (point-at-bol)))))
  18794. beg end toggled)
  18795. ;; Determine boundaries of changes. If a universal prefix has
  18796. ;; been given, put the list in a region. If region ends at a bol,
  18797. ;; do not consider the last line to be in the region.
  18798. (when (and current-prefix-arg (org-at-item-p))
  18799. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  18800. (org-mark-element))
  18801. (if (org-region-active-p)
  18802. (setq beg (funcall skip-blanks (region-beginning))
  18803. end (copy-marker (save-excursion
  18804. (goto-char (region-end))
  18805. (if (bolp) (point) (point-at-eol)))))
  18806. (setq beg (funcall skip-blanks (point-at-bol))
  18807. end (copy-marker (point-at-eol))))
  18808. ;; Ensure inline tasks don't count as headings.
  18809. (org-with-limited-levels
  18810. (save-excursion
  18811. (goto-char beg)
  18812. (cond
  18813. ;; Case 1. Started at an heading: de-star headings.
  18814. ((org-at-heading-p)
  18815. (while (< (point) end)
  18816. (when (org-at-heading-p t)
  18817. (looking-at org-outline-regexp) (replace-match "")
  18818. (setq toggled t))
  18819. (forward-line)))
  18820. ;; Case 2. Started at an item: change items into headlines.
  18821. ;; One star will be added by `org-list-to-subtree'.
  18822. ((org-at-item-p)
  18823. (while (< (point) end)
  18824. (when (org-at-item-p)
  18825. ;; Pay attention to cases when region ends before list.
  18826. (let* ((struct (org-list-struct))
  18827. (list-end
  18828. (min (org-list-get-bottom-point struct) (1+ end))))
  18829. (save-restriction
  18830. (narrow-to-region (point) list-end)
  18831. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  18832. (setq toggled t))
  18833. (forward-line)))
  18834. ;; Case 3. Started at normal text: make every line an heading,
  18835. ;; skipping headlines and items.
  18836. (t (let* ((stars
  18837. (make-string
  18838. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  18839. (add-stars
  18840. (cond (nstars "") ; stars from prefix only
  18841. ((equal stars "") "*") ; before first heading
  18842. (org-odd-levels-only "**") ; inside heading, odd
  18843. (t "*"))) ; inside heading, oddeven
  18844. (rpl (concat stars add-stars " "))
  18845. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  18846. (while (< (point) (if (equal nstars '(4)) lend end))
  18847. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  18848. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  18849. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  18850. (forward-line)))))))
  18851. (unless toggled (message "Cannot toggle heading from here"))))
  18852. (defun org-meta-return (&optional arg)
  18853. "Insert a new heading or wrap a region in a table.
  18854. Calls `org-insert-heading', `org-insert-item' or
  18855. `org-table-wrap-region', depending on context. When called with
  18856. an argument, unconditionally call `org-insert-heading'."
  18857. (interactive "P")
  18858. (org-check-before-invisible-edit 'insert)
  18859. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  18860. (call-interactively (cond (arg #'org-insert-heading)
  18861. ((org-at-table-p) #'org-table-wrap-region)
  18862. ((org-in-item-p) #'org-insert-item)
  18863. (t #'org-insert-heading)))))
  18864. ;;; Menu entries
  18865. (defsubst org-in-subtree-not-table-p ()
  18866. "Are we in a subtree and not in a table?"
  18867. (and (not (org-before-first-heading-p))
  18868. (not (org-at-table-p))))
  18869. ;; Define the Org mode menus
  18870. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  18871. '("Tbl"
  18872. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  18873. ["Next Field" org-cycle (org-at-table-p)]
  18874. ["Previous Field" org-shifttab (org-at-table-p)]
  18875. ["Next Row" org-return (org-at-table-p)]
  18876. "--"
  18877. ["Blank Field" org-table-blank-field (org-at-table-p)]
  18878. ["Edit Field" org-table-edit-field (org-at-table-p)]
  18879. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  18880. "--"
  18881. ("Column"
  18882. ["Move Column Left" org-metaleft (org-at-table-p)]
  18883. ["Move Column Right" org-metaright (org-at-table-p)]
  18884. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  18885. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  18886. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  18887. ("Row"
  18888. ["Move Row Up" org-metaup (org-at-table-p)]
  18889. ["Move Row Down" org-metadown (org-at-table-p)]
  18890. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  18891. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  18892. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  18893. "--"
  18894. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  18895. ("Rectangle"
  18896. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  18897. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  18898. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  18899. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  18900. "--"
  18901. ("Calculate"
  18902. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  18903. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  18904. ["Edit Formulas" org-edit-special (org-at-table-p)]
  18905. "--"
  18906. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  18907. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  18908. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  18909. "--"
  18910. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  18911. "--"
  18912. ["Sum Column/Rectangle" org-table-sum
  18913. (or (org-at-table-p) (org-region-active-p))]
  18914. ["Which Column?" org-table-current-column (org-at-table-p)])
  18915. ["Debug Formulas"
  18916. org-table-toggle-formula-debugger
  18917. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  18918. ["Show Col/Row Numbers"
  18919. org-table-toggle-coordinate-overlays
  18920. :style toggle
  18921. :selected (bound-and-true-p org-table-overlay-coordinates)]
  18922. "--"
  18923. ["Create" org-table-create (not (org-at-table-p))]
  18924. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  18925. ["Import from File" org-table-import (not (org-at-table-p))]
  18926. ["Export to File" org-table-export (org-at-table-p)]
  18927. "--"
  18928. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  18929. "--"
  18930. ("Plot"
  18931. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  18932. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  18933. (easy-menu-define org-org-menu org-mode-map "Org menu"
  18934. '("Org"
  18935. ("Show/Hide"
  18936. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  18937. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  18938. ["Sparse Tree..." org-sparse-tree t]
  18939. ["Reveal Context" org-reveal t]
  18940. ["Show All" org-show-all t]
  18941. "--"
  18942. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  18943. "--"
  18944. ["New Heading" org-insert-heading t]
  18945. ("Navigate Headings"
  18946. ["Up" outline-up-heading t]
  18947. ["Next" outline-next-visible-heading t]
  18948. ["Previous" outline-previous-visible-heading t]
  18949. ["Next Same Level" outline-forward-same-level t]
  18950. ["Previous Same Level" outline-backward-same-level t]
  18951. "--"
  18952. ["Jump" org-goto t])
  18953. ("Edit Structure"
  18954. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  18955. "--"
  18956. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  18957. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  18958. "--"
  18959. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  18960. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  18961. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  18962. "--"
  18963. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  18964. "--"
  18965. ["Copy visible text" org-copy-visible t]
  18966. "--"
  18967. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  18968. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  18969. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  18970. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  18971. "--"
  18972. ["Sort Region/Children" org-sort t]
  18973. "--"
  18974. ["Convert to odd levels" org-convert-to-odd-levels t]
  18975. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  18976. ("Editing"
  18977. ["Emphasis..." org-emphasize t]
  18978. ["Edit Source Example" org-edit-special t]
  18979. "--"
  18980. ["Footnote new/jump" org-footnote-action t]
  18981. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  18982. ("Archive"
  18983. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  18984. "--"
  18985. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  18986. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  18987. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  18988. )
  18989. "--"
  18990. ("Hyperlinks"
  18991. ["Store Link (Global)" org-store-link t]
  18992. ["Find existing link to here" org-occur-link-in-agenda-files t]
  18993. ["Insert Link" org-insert-link t]
  18994. ["Follow Link" org-open-at-point t]
  18995. "--"
  18996. ["Next link" org-next-link t]
  18997. ["Previous link" org-previous-link t]
  18998. "--"
  18999. ["Descriptive Links"
  19000. org-toggle-link-display
  19001. :style radio
  19002. :selected org-descriptive-links
  19003. ]
  19004. ["Literal Links"
  19005. org-toggle-link-display
  19006. :style radio
  19007. :selected (not org-descriptive-links)])
  19008. "--"
  19009. ("TODO Lists"
  19010. ["TODO/DONE/-" org-todo t]
  19011. ("Select keyword"
  19012. ["Next keyword" org-shiftright (org-at-heading-p)]
  19013. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19014. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19015. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19016. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19017. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19018. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  19019. "--"
  19020. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19021. :selected org-enforce-todo-dependencies :style toggle :active t]
  19022. "Settings for tree at point"
  19023. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19024. :selected (org-entry-get nil "ORDERED")
  19025. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19026. ["Do Children parallel" org-toggle-ordered-property :style radio
  19027. :selected (not (org-entry-get nil "ORDERED"))
  19028. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19029. "--"
  19030. ["Set Priority" org-priority t]
  19031. ["Priority Up" org-shiftup t]
  19032. ["Priority Down" org-shiftdown t]
  19033. "--"
  19034. ["Get news from all feeds" org-feed-update-all t]
  19035. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19036. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19037. ("TAGS and Properties"
  19038. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19039. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19040. "--"
  19041. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19042. ["Column view of properties" org-columns t]
  19043. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19044. ("Dates and Scheduling"
  19045. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19046. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19047. ("Change Date"
  19048. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  19049. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  19050. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  19051. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  19052. ["Compute Time Range" org-evaluate-time-range t]
  19053. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19054. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19055. "--"
  19056. ["Custom time format" org-toggle-time-stamp-overlays
  19057. :style radio :selected org-display-custom-times]
  19058. "--"
  19059. ["Goto Calendar" org-goto-calendar t]
  19060. ["Date from Calendar" org-date-from-calendar t]
  19061. "--"
  19062. ["Start/Restart Timer" org-timer-start t]
  19063. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19064. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19065. ["Insert Timer String" org-timer t]
  19066. ["Insert Timer Item" org-timer-item t])
  19067. ("Logging work"
  19068. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19069. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19070. ["Clock out" org-clock-out t]
  19071. ["Clock cancel" org-clock-cancel t]
  19072. "--"
  19073. ["Mark as default task" org-clock-mark-default-task t]
  19074. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19075. ["Goto running clock" org-clock-goto t]
  19076. "--"
  19077. ["Display times" org-clock-display t]
  19078. ["Create clock table" org-clock-report t]
  19079. "--"
  19080. ["Record DONE time"
  19081. (progn (setq org-log-done (not org-log-done))
  19082. (message "Switching to %s will %s record a timestamp"
  19083. (car org-done-keywords)
  19084. (if org-log-done "automatically" "not")))
  19085. :style toggle :selected org-log-done])
  19086. "--"
  19087. ["Agenda Command..." org-agenda t]
  19088. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19089. ("File List for Agenda")
  19090. ("Special views current file"
  19091. ["TODO Tree" org-show-todo-tree t]
  19092. ["Check Deadlines" org-check-deadlines t]
  19093. ["Tags/Property tree" org-match-sparse-tree t])
  19094. "--"
  19095. ["Export/Publish..." org-export-dispatch t]
  19096. ("LaTeX"
  19097. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  19098. :style toggle :selected org-cdlatex-mode]
  19099. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19100. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19101. ["Modify math symbol" org-cdlatex-math-modify
  19102. (org-inside-LaTeX-fragment-p)]
  19103. ["Insert citation" org-reftex-citation t])
  19104. "--"
  19105. ("MobileOrg"
  19106. ["Push Files and Views" org-mobile-push t]
  19107. ["Get Captured and Flagged" org-mobile-pull t]
  19108. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
  19109. "--"
  19110. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19111. "--"
  19112. ("Documentation"
  19113. ["Show Version" org-version t]
  19114. ["Info Documentation" org-info t]
  19115. ["Browse Org News" org-browse-news t])
  19116. ("Customize"
  19117. ["Browse Org Group" org-customize t]
  19118. "--"
  19119. ["Expand This Menu" org-create-customize-menu
  19120. (fboundp 'customize-menu-create)])
  19121. ["Send bug report" org-submit-bug-report t]
  19122. "--"
  19123. ("Refresh/Reload"
  19124. ["Refresh setup current buffer" org-mode-restart t]
  19125. ["Reload Org (after update)" org-reload t]
  19126. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  19127. (defun org-info (&optional node)
  19128. "Read documentation for Org in the info system.
  19129. With optional NODE, go directly to that node."
  19130. (interactive)
  19131. (info (format "(org)%s" (or node ""))))
  19132. (defun org-browse-news ()
  19133. "Browse the news for the latest major release."
  19134. (interactive)
  19135. (browse-url "https://orgmode.org/Changes.html"))
  19136. ;;;###autoload
  19137. (defun org-submit-bug-report ()
  19138. "Submit a bug report on Org via mail.
  19139. Don't hesitate to report any problems or inaccurate documentation.
  19140. If you don't have setup sending mail from (X)Emacs, please copy the
  19141. output buffer into your mail program, as it gives us important
  19142. information about your Org version and configuration."
  19143. (interactive)
  19144. (require 'reporter)
  19145. (defvar reporter-prompt-for-summary-p)
  19146. (org-load-modules-maybe)
  19147. (org-require-autoloaded-modules)
  19148. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19149. (reporter-submit-bug-report
  19150. "emacs-orgmode@gnu.org"
  19151. (org-version nil 'full)
  19152. (let (list)
  19153. (save-window-excursion
  19154. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19155. (delete-other-windows)
  19156. (erase-buffer)
  19157. (insert "You are about to submit a bug report to the Org mailing list.
  19158. We would like to add your full Org and Outline configuration to the
  19159. bug report. This greatly simplifies the work of the maintainer and
  19160. other experts on the mailing list.
  19161. HOWEVER, some variables you have customized may contain private
  19162. information. The names of customers, colleagues, or friends, might
  19163. appear in the form of file names, tags, todo states, or search strings.
  19164. If you answer yes to the prompt, you might want to check and remove
  19165. such private information before sending the email.")
  19166. (add-text-properties (point-min) (point-max) '(face org-warning))
  19167. (when (yes-or-no-p "Include your Org configuration ")
  19168. (mapatoms
  19169. (lambda (v)
  19170. (and (boundp v)
  19171. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19172. (or (and (symbol-value v)
  19173. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19174. (and
  19175. (get v 'custom-type) (get v 'standard-value)
  19176. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19177. (push v list)))))
  19178. (kill-buffer (get-buffer "*Warn about privacy*"))
  19179. list))
  19180. nil nil
  19181. "Remember to cover the basics, that is, what you expected to happen and
  19182. what in fact did happen. You don't know how to make a good report? See
  19183. https://orgmode.org/manual/Feedback.html#Feedback
  19184. Your bug report will be posted to the Org mailing list.
  19185. ------------------------------------------------------------------------")
  19186. (save-excursion
  19187. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19188. (replace-match "\\1Bug: \\3 [\\2]")))))
  19189. (defun org-install-agenda-files-menu ()
  19190. (let ((bl (buffer-list)))
  19191. (save-excursion
  19192. (while bl
  19193. (set-buffer (pop bl))
  19194. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19195. (when (derived-mode-p 'org-mode)
  19196. (easy-menu-change
  19197. '("Org") "File List for Agenda"
  19198. (append
  19199. (list
  19200. ["Edit File List" (org-edit-agenda-file-list) t]
  19201. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19202. ["Remove Current File from List" org-remove-file t]
  19203. ["Cycle through agenda files" org-cycle-agenda-files t]
  19204. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19205. "--")
  19206. (mapcar 'org-file-menu-entry
  19207. ;; Prevent initialization from failing.
  19208. (ignore-errors (org-agenda-files t)))))))))
  19209. ;;;; Documentation
  19210. (defun org-require-autoloaded-modules ()
  19211. (interactive)
  19212. (mapc #'require
  19213. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19214. org-table org-timer)))
  19215. ;;;###autoload
  19216. (defun org-reload (&optional uncompiled)
  19217. "Reload all Org Lisp files.
  19218. With prefix arg UNCOMPILED, load the uncompiled versions."
  19219. (interactive "P")
  19220. (require 'loadhist)
  19221. (let* ((org-dir (org-find-library-dir "org"))
  19222. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19223. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  19224. (remove-re (format "\\`%s\\'"
  19225. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19226. (feats (delete-dups
  19227. (mapcar 'file-name-sans-extension
  19228. (mapcar 'file-name-nondirectory
  19229. (delq nil
  19230. (mapcar 'feature-file
  19231. features))))))
  19232. (lfeat (append
  19233. (sort
  19234. (setq feats
  19235. (delq nil (mapcar
  19236. (lambda (f)
  19237. (if (and (string-match feature-re f)
  19238. (not (string-match remove-re f)))
  19239. f nil))
  19240. feats)))
  19241. 'string-lessp)
  19242. (list "org-version" "org")))
  19243. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  19244. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19245. load-uncore load-misses)
  19246. (setq load-misses
  19247. (delq 't
  19248. (mapcar (lambda (f)
  19249. (or (org-load-noerror-mustsuffix (concat org-dir f))
  19250. (and (string= org-dir contrib-dir)
  19251. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19252. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19253. (add-to-list 'load-uncore f 'append)
  19254. 't)
  19255. f))
  19256. lfeat)))
  19257. (when load-uncore
  19258. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19259. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  19260. (if load-misses
  19261. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19262. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19263. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19264. ;;;###autoload
  19265. (defun org-customize ()
  19266. "Call the customize function with org as argument."
  19267. (interactive)
  19268. (org-load-modules-maybe)
  19269. (org-require-autoloaded-modules)
  19270. (customize-browse 'org))
  19271. (defun org-create-customize-menu ()
  19272. "Create a full customization menu for Org mode, insert it into the menu."
  19273. (interactive)
  19274. (org-load-modules-maybe)
  19275. (org-require-autoloaded-modules)
  19276. (if (fboundp 'customize-menu-create)
  19277. (progn
  19278. (easy-menu-change
  19279. '("Org") "Customize"
  19280. `(["Browse Org group" org-customize t]
  19281. "--"
  19282. ,(customize-menu-create 'org)
  19283. ["Set" Custom-set t]
  19284. ["Save" Custom-save t]
  19285. ["Reset to Current" Custom-reset-current t]
  19286. ["Reset to Saved" Custom-reset-saved t]
  19287. ["Reset to Standard Settings" Custom-reset-standard t]))
  19288. (message "\"Org\"-menu now contains full customization menu"))
  19289. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  19290. ;;;; Miscellaneous stuff
  19291. ;;; Generally useful functions
  19292. (defun org-link-display-format (s)
  19293. "Replace links in string S with their description.
  19294. If there is no description, use the link target."
  19295. (save-match-data
  19296. (replace-regexp-in-string
  19297. org-bracket-link-analytic-regexp
  19298. (lambda (m)
  19299. (if (match-end 5) (match-string 5 m)
  19300. (concat (match-string 1 m) (match-string 3 m))))
  19301. s nil t)))
  19302. (defun org-toggle-link-display ()
  19303. "Toggle the literal or descriptive display of links."
  19304. (interactive)
  19305. (if org-descriptive-links
  19306. (remove-from-invisibility-spec '(org-link))
  19307. (add-to-invisibility-spec '(org-link)))
  19308. (org-restart-font-lock)
  19309. (setq org-descriptive-links (not org-descriptive-links)))
  19310. (defun org-in-clocktable-p ()
  19311. "Check if the cursor is in a clocktable."
  19312. (let ((pos (point)) start)
  19313. (save-excursion
  19314. (end-of-line 1)
  19315. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19316. (setq start (match-beginning 0))
  19317. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19318. (>= (match-end 0) pos)
  19319. start))))
  19320. (defun org-in-verbatim-emphasis ()
  19321. (save-match-data
  19322. (and (org-in-regexp org-verbatim-re 2)
  19323. (>= (point) (match-beginning 3))
  19324. (<= (point) (match-end 4)))))
  19325. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19326. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  19327. (if (and marker (marker-buffer marker)
  19328. (buffer-live-p (marker-buffer marker)))
  19329. (progn
  19330. (pop-to-buffer-same-window (marker-buffer marker))
  19331. (when (or (> marker (point-max)) (< marker (point-min)))
  19332. (widen))
  19333. (goto-char marker)
  19334. (org-show-context 'org-goto))
  19335. (if bookmark
  19336. (bookmark-jump bookmark)
  19337. (error "Cannot find location"))))
  19338. (defun org-quote-csv-field (s)
  19339. "Quote field for inclusion in CSV material."
  19340. (if (string-match "[\",]" s)
  19341. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19342. s))
  19343. (defun org-force-self-insert (N)
  19344. "Needed to enforce self-insert under remapping."
  19345. (interactive "p")
  19346. (self-insert-command N))
  19347. (defun org-fill-template (template alist)
  19348. "Find each %key of ALIST in TEMPLATE and replace it."
  19349. (let ((case-fold-search nil))
  19350. (dolist (entry (sort (copy-sequence alist)
  19351. (lambda (a b) (< (length (car a)) (length (car b))))))
  19352. (setq template
  19353. (replace-regexp-in-string
  19354. (concat "%" (regexp-quote (car entry)))
  19355. (or (cdr entry) "") template t t)))
  19356. template))
  19357. (defun org-quote-vert (s)
  19358. "Replace \"|\" with \"\\vert\"."
  19359. (while (string-match "|" s)
  19360. (setq s (replace-match "\\vert" t t s)))
  19361. s)
  19362. (defun org-uuidgen-p (s)
  19363. "Is S an ID created by UUIDGEN?"
  19364. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  19365. (defun org-in-src-block-p (&optional inside)
  19366. "Whether point is in a code source block.
  19367. When INSIDE is non-nil, don't consider we are within a src block
  19368. when point is at #+BEGIN_SRC or #+END_SRC."
  19369. (let ((case-fold-search t))
  19370. (or (and (eq (get-char-property (point) 'src-block) t))
  19371. (and (not inside)
  19372. (save-match-data
  19373. (save-excursion
  19374. (beginning-of-line)
  19375. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  19376. (defun org-context ()
  19377. "Return a list of contexts of the current cursor position.
  19378. If several contexts apply, all are returned.
  19379. Each context entry is a list with a symbol naming the context, and
  19380. two positions indicating start and end of the context. Possible
  19381. contexts are:
  19382. :headline anywhere in a headline
  19383. :headline-stars on the leading stars in a headline
  19384. :todo-keyword on a TODO keyword (including DONE) in a headline
  19385. :tags on the TAGS in a headline
  19386. :priority on the priority cookie in a headline
  19387. :item on the first line of a plain list item
  19388. :item-bullet on the bullet/number of a plain list item
  19389. :checkbox on the checkbox in a plain list item
  19390. :table in an Org table
  19391. :table-special on a special filed in a table
  19392. :table-table in a table.el table
  19393. :clocktable in a clocktable
  19394. :src-block in a source block
  19395. :link on a hyperlink
  19396. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  19397. :target on a <<target>>
  19398. :radio-target on a <<<radio-target>>>
  19399. :latex-fragment on a LaTeX fragment
  19400. :latex-preview on a LaTeX fragment with overlaid preview image
  19401. This function expects the position to be visible because it uses font-lock
  19402. faces as a help to recognize the following contexts: :table-special, :link,
  19403. and :keyword."
  19404. (let* ((f (get-text-property (point) 'face))
  19405. (faces (if (listp f) f (list f)))
  19406. (case-fold-search t)
  19407. (p (point)) clist o)
  19408. ;; First the large context
  19409. (cond
  19410. ((org-at-heading-p t)
  19411. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  19412. (when (progn
  19413. (beginning-of-line 1)
  19414. (looking-at org-todo-line-tags-regexp))
  19415. (push (org-point-in-group p 1 :headline-stars) clist)
  19416. (push (org-point-in-group p 2 :todo-keyword) clist)
  19417. (push (org-point-in-group p 4 :tags) clist))
  19418. (goto-char p)
  19419. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  19420. (when (looking-at "\\[#[A-Z0-9]\\]")
  19421. (push (org-point-in-group p 0 :priority) clist)))
  19422. ((org-at-item-p)
  19423. (push (org-point-in-group p 2 :item-bullet) clist)
  19424. (push (list :item (point-at-bol)
  19425. (save-excursion (org-end-of-item) (point)))
  19426. clist)
  19427. (and (org-at-item-checkbox-p)
  19428. (push (org-point-in-group p 0 :checkbox) clist)))
  19429. ((org-at-table-p)
  19430. (push (list :table (org-table-begin) (org-table-end)) clist)
  19431. (when (memq 'org-formula faces)
  19432. (push (list :table-special
  19433. (previous-single-property-change p 'face)
  19434. (next-single-property-change p 'face)) clist)))
  19435. ((org-at-table-p 'any)
  19436. (push (list :table-table) clist)))
  19437. (goto-char p)
  19438. (let ((case-fold-search t))
  19439. ;; New the "medium" contexts: clocktables, source blocks
  19440. (cond ((org-in-clocktable-p)
  19441. (push (list :clocktable
  19442. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  19443. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  19444. (match-beginning 1))
  19445. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  19446. (match-end 0))) clist))
  19447. ((org-in-src-block-p)
  19448. (push (list :src-block
  19449. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  19450. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  19451. (match-beginning 1))
  19452. (and (search-forward "#+END_SRC" nil t)
  19453. (match-beginning 0))) clist))))
  19454. (goto-char p)
  19455. ;; Now the small context
  19456. (cond
  19457. ((org-at-timestamp-p)
  19458. (push (org-point-in-group p 0 :timestamp) clist))
  19459. ((memq 'org-link faces)
  19460. (push (list :link
  19461. (previous-single-property-change p 'face)
  19462. (next-single-property-change p 'face)) clist))
  19463. ((memq 'org-special-keyword faces)
  19464. (push (list :keyword
  19465. (previous-single-property-change p 'face)
  19466. (next-single-property-change p 'face)) clist))
  19467. ((org-at-target-p)
  19468. (push (org-point-in-group p 0 :target) clist)
  19469. (goto-char (1- (match-beginning 0)))
  19470. (when (looking-at org-radio-target-regexp)
  19471. (push (org-point-in-group p 0 :radio-target) clist))
  19472. (goto-char p))
  19473. ((setq o (cl-some
  19474. (lambda (o)
  19475. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  19476. o))
  19477. (overlays-at (point))))
  19478. (push (list :latex-fragment
  19479. (overlay-start o) (overlay-end o)) clist)
  19480. (push (list :latex-preview
  19481. (overlay-start o) (overlay-end o)) clist))
  19482. ((org-inside-LaTeX-fragment-p)
  19483. ;; FIXME: positions wrong.
  19484. (push (list :latex-fragment (point) (point)) clist)))
  19485. (setq clist (nreverse (delq nil clist)))
  19486. clist))
  19487. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  19488. "Non-nil when point is between matches of START-RE and END-RE.
  19489. Also return a non-nil value when point is on one of the matches.
  19490. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  19491. buffer positions. Default values are the positions of headlines
  19492. surrounding the point.
  19493. The functions returns a cons cell whose car (resp. cdr) is the
  19494. position before START-RE (resp. after END-RE)."
  19495. (save-match-data
  19496. (let ((pos (point))
  19497. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  19498. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  19499. beg end)
  19500. (save-excursion
  19501. ;; Point is on a block when on START-RE or if START-RE can be
  19502. ;; found before it...
  19503. (and (or (org-in-regexp start-re)
  19504. (re-search-backward start-re limit-up t))
  19505. (setq beg (match-beginning 0))
  19506. ;; ... and END-RE after it...
  19507. (goto-char (match-end 0))
  19508. (re-search-forward end-re limit-down t)
  19509. (> (setq end (match-end 0)) pos)
  19510. ;; ... without another START-RE in-between.
  19511. (goto-char (match-beginning 0))
  19512. (not (re-search-backward start-re (1+ beg) t))
  19513. ;; Return value.
  19514. (cons beg end))))))
  19515. (defun org-in-block-p (names)
  19516. "Non-nil when point belongs to a block whose name belongs to NAMES.
  19517. NAMES is a list of strings containing names of blocks.
  19518. Return first block name matched, or nil. Beware that in case of
  19519. nested blocks, the returned name may not belong to the closest
  19520. block from point."
  19521. (save-match-data
  19522. (catch 'exit
  19523. (let ((case-fold-search t)
  19524. (lim-up (save-excursion (outline-previous-heading)))
  19525. (lim-down (save-excursion (outline-next-heading))))
  19526. (dolist (name names)
  19527. (let ((n (regexp-quote name)))
  19528. (when (org-between-regexps-p
  19529. (concat "^[ \t]*#\\+begin_" n)
  19530. (concat "^[ \t]*#\\+end_" n)
  19531. lim-up lim-down)
  19532. (throw 'exit n)))))
  19533. nil)))
  19534. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  19535. "Call `multi-occur' with buffers for all agenda files."
  19536. (interactive "sOrg-files matching: ")
  19537. (let* ((files (org-agenda-files))
  19538. (tnames (mapcar #'file-truename files))
  19539. (extra org-agenda-text-search-extra-files))
  19540. (when (eq (car extra) 'agenda-archives)
  19541. (setq extra (cdr extra))
  19542. (setq files (org-add-archive-files files)))
  19543. (dolist (f extra)
  19544. (unless (member (file-truename f) tnames)
  19545. (unless (member f files) (setq files (append files (list f))))
  19546. (setq tnames (append tnames (list (file-truename f))))))
  19547. (multi-occur
  19548. (mapcar (lambda (x)
  19549. (with-current-buffer
  19550. ;; FIXME: Why not just (find-file-noselect x)?
  19551. ;; Is it to avoid the "revert buffer" prompt?
  19552. (or (get-file-buffer x) (find-file-noselect x))
  19553. (widen)
  19554. (current-buffer)))
  19555. files)
  19556. regexp)))
  19557. (add-hook 'occur-mode-find-occurrence-hook
  19558. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  19559. (defun org-occur-link-in-agenda-files ()
  19560. "Create a link and search for it in the agendas.
  19561. The link is not stored in `org-stored-links', it is just created
  19562. for the search purpose."
  19563. (interactive)
  19564. (let ((link (condition-case nil
  19565. (org-store-link nil)
  19566. (error "Unable to create a link to here"))))
  19567. (org-occur-in-agenda-files (regexp-quote link))))
  19568. (defun org-back-over-empty-lines ()
  19569. "Move backwards over whitespace, to the beginning of the first empty line.
  19570. Returns the number of empty lines passed."
  19571. (let ((pos (point)))
  19572. (if (cdr (assq 'heading org-blank-before-new-entry))
  19573. (skip-chars-backward " \t\n\r")
  19574. (unless (eobp)
  19575. (forward-line -1)))
  19576. (beginning-of-line 2)
  19577. (goto-char (min (point) pos))
  19578. (count-lines (point) pos)))
  19579. (defun org-replace-escapes (string table)
  19580. "Replace %-escapes in STRING with values in TABLE.
  19581. TABLE is an association list with keys like \"%a\" and string values.
  19582. The sequences in STRING may contain normal field width and padding information,
  19583. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  19584. so values can contain further %-escapes if they are define later in TABLE."
  19585. (let ((tbl (copy-alist table))
  19586. (case-fold-search nil)
  19587. (pchg 0)
  19588. re rpl)
  19589. (dolist (e tbl)
  19590. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  19591. (when (and (cdr e) (string-match re (cdr e)))
  19592. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  19593. (safe "SREF"))
  19594. (add-text-properties 0 3 (list 'sref sref) safe)
  19595. (setcdr e (replace-match safe t t (cdr e)))))
  19596. (while (string-match re string)
  19597. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  19598. (cdr e)))
  19599. (setq string (replace-match rpl t t string))))
  19600. (while (setq pchg (next-property-change pchg string))
  19601. (let ((sref (get-text-property pchg 'sref string)))
  19602. (when (and sref (string-match "SREF" string pchg))
  19603. (setq string (replace-match sref t t string)))))
  19604. string))
  19605. ;;; TODO: Only called once, from ox-odt which should probably use
  19606. ;;; org-export-inline-image-p or something.
  19607. (defun org-file-image-p (file)
  19608. "Return non-nil if FILE is an image."
  19609. (save-match-data
  19610. (string-match (image-file-name-regexp) file)))
  19611. (defun org-get-cursor-date (&optional with-time)
  19612. "Return the date at cursor in as a time.
  19613. This works in the calendar and in the agenda, anywhere else it just
  19614. returns the current time.
  19615. If WITH-TIME is non-nil, returns the time of the event at point (in
  19616. the agenda) or the current time of the day."
  19617. (let (date day defd tp hod mod)
  19618. (when with-time
  19619. (setq tp (get-text-property (point) 'time))
  19620. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  19621. (setq hod (string-to-number (match-string 1 tp))
  19622. mod (string-to-number (match-string 2 tp))))
  19623. (or tp (let ((now (decode-time)))
  19624. (setq hod (nth 2 now)
  19625. mod (nth 1 now)))))
  19626. (cond
  19627. ((eq major-mode 'calendar-mode)
  19628. (setq date (calendar-cursor-to-date)
  19629. defd (encode-time 0 (or mod 0) (or hod 0)
  19630. (nth 1 date) (nth 0 date) (nth 2 date))))
  19631. ((eq major-mode 'org-agenda-mode)
  19632. (setq day (get-text-property (point) 'day))
  19633. (when day
  19634. (setq date (calendar-gregorian-from-absolute day)
  19635. defd (encode-time 0 (or mod 0) (or hod 0)
  19636. (nth 1 date) (nth 0 date) (nth 2 date))))))
  19637. (or defd (current-time))))
  19638. (defun org-mark-subtree (&optional up)
  19639. "Mark the current subtree.
  19640. This puts point at the start of the current subtree, and mark at
  19641. the end. If a numeric prefix UP is given, move up into the
  19642. hierarchy of headlines by UP levels before marking the subtree."
  19643. (interactive "P")
  19644. (org-with-limited-levels
  19645. (cond ((org-at-heading-p) (beginning-of-line))
  19646. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  19647. (t (outline-previous-visible-heading 1))))
  19648. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  19649. (if (called-interactively-p 'any)
  19650. (call-interactively 'org-mark-element)
  19651. (org-mark-element)))
  19652. ;;; Indentation
  19653. (defvar org-element-greater-elements)
  19654. (defun org--get-expected-indentation (element contentsp)
  19655. "Expected indentation column for current line, according to ELEMENT.
  19656. ELEMENT is an element containing point. CONTENTSP is non-nil
  19657. when indentation is to be computed according to contents of
  19658. ELEMENT."
  19659. (let ((type (org-element-type element))
  19660. (start (org-element-property :begin element))
  19661. (post-affiliated (org-element-property :post-affiliated element)))
  19662. (org-with-wide-buffer
  19663. (cond
  19664. (contentsp
  19665. (cl-case type
  19666. ((diary-sexp footnote-definition) 0)
  19667. ((headline inlinetask nil)
  19668. (if (not org-adapt-indentation) 0
  19669. (let ((level (org-current-level)))
  19670. (if level (1+ level) 0))))
  19671. ((item plain-list) (org-list-item-body-column post-affiliated))
  19672. (t
  19673. (goto-char start)
  19674. (current-indentation))))
  19675. ((memq type '(headline inlinetask nil))
  19676. (if (org-match-line "[ \t]*$")
  19677. (org--get-expected-indentation element t)
  19678. 0))
  19679. ((memq type '(diary-sexp footnote-definition)) 0)
  19680. ;; First paragraph of a footnote definition or an item.
  19681. ;; Indent like parent.
  19682. ((< (line-beginning-position) start)
  19683. (org--get-expected-indentation
  19684. (org-element-property :parent element) t))
  19685. ;; At first line: indent according to previous sibling, if any,
  19686. ;; ignoring footnote definitions and inline tasks, or parent's
  19687. ;; contents.
  19688. ((= (line-beginning-position) start)
  19689. (catch 'exit
  19690. (while t
  19691. (if (= (point-min) start) (throw 'exit 0)
  19692. (goto-char (1- start))
  19693. (let* ((previous (org-element-at-point))
  19694. (parent previous))
  19695. (while (and parent (<= (org-element-property :end parent) start))
  19696. (setq previous parent
  19697. parent (org-element-property :parent parent)))
  19698. (cond
  19699. ((not previous) (throw 'exit 0))
  19700. ((> (org-element-property :end previous) start)
  19701. (throw 'exit (org--get-expected-indentation previous t)))
  19702. ((memq (org-element-type previous)
  19703. '(footnote-definition inlinetask))
  19704. (setq start (org-element-property :begin previous)))
  19705. (t (goto-char (org-element-property :begin previous))
  19706. (throw 'exit
  19707. (if (bolp) (current-indentation)
  19708. ;; At first paragraph in an item or
  19709. ;; a footnote definition.
  19710. (org--get-expected-indentation
  19711. (org-element-property :parent previous) t))))))))))
  19712. ;; Otherwise, move to the first non-blank line above.
  19713. (t
  19714. (beginning-of-line)
  19715. (let ((pos (point)))
  19716. (skip-chars-backward " \r\t\n")
  19717. (cond
  19718. ;; Two blank lines end a footnote definition or a plain
  19719. ;; list. When we indent an empty line after them, the
  19720. ;; containing list or footnote definition is over, so it
  19721. ;; qualifies as a previous sibling. Therefore, we indent
  19722. ;; like its first line.
  19723. ((and (memq type '(footnote-definition plain-list))
  19724. (> (count-lines (point) pos) 2))
  19725. (goto-char start)
  19726. (current-indentation))
  19727. ;; Line above is the first one of a paragraph at the
  19728. ;; beginning of an item or a footnote definition. Indent
  19729. ;; like parent.
  19730. ((< (line-beginning-position) start)
  19731. (org--get-expected-indentation
  19732. (org-element-property :parent element) t))
  19733. ;; Line above is the beginning of an element, i.e., point
  19734. ;; was originally on the blank lines between element's start
  19735. ;; and contents.
  19736. ((= (line-beginning-position) post-affiliated)
  19737. (org--get-expected-indentation element t))
  19738. ;; POS is after contents in a greater element. Indent like
  19739. ;; the beginning of the element.
  19740. ((and (memq type org-element-greater-elements)
  19741. (let ((cend (org-element-property :contents-end element)))
  19742. (and cend (<= cend pos))))
  19743. ;; As a special case, if point is at the end of a footnote
  19744. ;; definition or an item, indent like the very last element
  19745. ;; within. If that last element is an item, indent like
  19746. ;; its contents.
  19747. (if (memq type '(footnote-definition item plain-list))
  19748. (let ((last (org-element-at-point)))
  19749. (goto-char pos)
  19750. (org--get-expected-indentation
  19751. last (eq (org-element-type last) 'item)))
  19752. (goto-char start)
  19753. (current-indentation)))
  19754. ;; In any other case, indent like the current line.
  19755. (t (current-indentation)))))))))
  19756. (defun org--align-node-property ()
  19757. "Align node property at point.
  19758. Alignment is done according to `org-property-format', which see."
  19759. (when (save-excursion
  19760. (beginning-of-line)
  19761. (looking-at org-property-re))
  19762. (replace-match
  19763. (concat (match-string 4)
  19764. (org-trim
  19765. (format org-property-format (match-string 1) (match-string 3))))
  19766. t t)))
  19767. (defun org-indent-line ()
  19768. "Indent line depending on context.
  19769. Indentation is done according to the following rules:
  19770. - Footnote definitions, diary sexps, headlines and inline tasks
  19771. have to start at column 0.
  19772. - On the very first line of an element, consider, in order, the
  19773. next rules until one matches:
  19774. 1. If there's a sibling element before, ignoring footnote
  19775. definitions and inline tasks, indent like its first line.
  19776. 2. If element has a parent, indent like its contents. More
  19777. precisely, if parent is an item, indent after the
  19778. description part, if any, or the bullet (see
  19779. `org-list-description-max-indent'). Else, indent like
  19780. parent's first line.
  19781. 3. Otherwise, indent relatively to current level, if
  19782. `org-adapt-indentation' is non-nil, or to left margin.
  19783. - On a blank line at the end of an element, indent according to
  19784. the type of the element. More precisely
  19785. 1. If element is a plain list, an item, or a footnote
  19786. definition, indent like the very last element within.
  19787. 2. If element is a paragraph, indent like its last non blank
  19788. line.
  19789. 3. Otherwise, indent like its very first line.
  19790. - In the code part of a source block, use language major mode
  19791. to indent current line if `org-src-tab-acts-natively' is
  19792. non-nil. If it is nil, do nothing.
  19793. - Otherwise, indent like the first non-blank line above.
  19794. The function doesn't indent an item as it could break the whole
  19795. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  19796. `\\[org-shiftmetaright]'.
  19797. Also align node properties according to `org-property-format'."
  19798. (interactive)
  19799. (cond
  19800. ((org-at-heading-p) 'noindent)
  19801. (t
  19802. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  19803. (type (org-element-type element)))
  19804. (cond ((and (memq type '(plain-list item))
  19805. (= (line-beginning-position)
  19806. (org-element-property :post-affiliated element)))
  19807. 'noindent)
  19808. ((and (eq type 'latex-environment)
  19809. (>= (point) (org-element-property :post-affiliated element))
  19810. (< (point) (org-with-wide-buffer
  19811. (goto-char (org-element-property :end element))
  19812. (skip-chars-backward " \r\t\n")
  19813. (line-beginning-position 2))))
  19814. 'noindent)
  19815. ((and (eq type 'src-block)
  19816. org-src-tab-acts-natively
  19817. (> (line-beginning-position)
  19818. (org-element-property :post-affiliated element))
  19819. (< (line-beginning-position)
  19820. (org-with-wide-buffer
  19821. (goto-char (org-element-property :end element))
  19822. (skip-chars-backward " \r\t\n")
  19823. (line-beginning-position))))
  19824. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  19825. (t
  19826. (let ((column (org--get-expected-indentation element nil)))
  19827. ;; Preserve current column.
  19828. (if (<= (current-column) (current-indentation))
  19829. (indent-line-to column)
  19830. (save-excursion (indent-line-to column))))
  19831. ;; Align node property. Also preserve current column.
  19832. (when (eq type 'node-property)
  19833. (let ((column (current-column)))
  19834. (org--align-node-property)
  19835. (org-move-to-column column)))))))))
  19836. (defun org-indent-region (start end)
  19837. "Indent each non-blank line in the region.
  19838. Called from a program, START and END specify the region to
  19839. indent. The function will not indent contents of example blocks,
  19840. verse blocks and export blocks as leading white spaces are
  19841. assumed to be significant there."
  19842. (interactive "r")
  19843. (save-excursion
  19844. (goto-char start)
  19845. (skip-chars-forward " \r\t\n")
  19846. (unless (eobp) (beginning-of-line))
  19847. (let ((indent-to
  19848. (lambda (ind pos)
  19849. ;; Set IND as indentation for all lines between point and
  19850. ;; POS. Blank lines are ignored. Leave point after POS
  19851. ;; once done.
  19852. (let ((limit (copy-marker pos)))
  19853. (while (< (point) limit)
  19854. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  19855. (forward-line))
  19856. (set-marker limit nil))))
  19857. (end (copy-marker end)))
  19858. (while (< (point) end)
  19859. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  19860. (let* ((element (org-element-at-point))
  19861. (type (org-element-type element))
  19862. (element-end (copy-marker (org-element-property :end element)))
  19863. (ind (org--get-expected-indentation element nil)))
  19864. (cond
  19865. ;; Element indented as a single block. Example blocks
  19866. ;; preserving indentation are a special case since the
  19867. ;; "contents" must not be indented whereas the block
  19868. ;; boundaries can.
  19869. ((or (memq type '(export-block latex-environment))
  19870. (and (eq type 'example-block)
  19871. (not
  19872. (or org-src-preserve-indentation
  19873. (org-element-property :preserve-indent element)))))
  19874. (let ((offset (- ind (current-indentation))))
  19875. (unless (zerop offset)
  19876. (indent-rigidly (org-element-property :begin element)
  19877. (org-element-property :end element)
  19878. offset)))
  19879. (goto-char element-end))
  19880. ;; Elements indented line wise. Be sure to exclude
  19881. ;; example blocks (preserving indentation) and source
  19882. ;; blocks from this category as they are treated
  19883. ;; specially later.
  19884. ((or (memq type '(paragraph table table-row))
  19885. (not (or (org-element-property :contents-begin element)
  19886. (memq type '(example-block src-block)))))
  19887. (when (eq type 'node-property)
  19888. (org--align-node-property)
  19889. (beginning-of-line))
  19890. (funcall indent-to ind (min element-end end)))
  19891. ;; Elements consisting of three parts: before the
  19892. ;; contents, the contents, and after the contents. The
  19893. ;; contents are treated specially, according to the
  19894. ;; element type, or not indented at all. Other parts are
  19895. ;; indented as a single block.
  19896. (t
  19897. (let* ((post (copy-marker
  19898. (org-element-property :post-affiliated element)))
  19899. (cbeg
  19900. (copy-marker
  19901. (cond
  19902. ((not (org-element-property :contents-begin element))
  19903. ;; Fake contents for source blocks.
  19904. (org-with-wide-buffer
  19905. (goto-char post)
  19906. (line-beginning-position 2)))
  19907. ((memq type '(footnote-definition item plain-list))
  19908. ;; Contents in these elements could start on
  19909. ;; the same line as the beginning of the
  19910. ;; element. Make sure we start indenting
  19911. ;; from the second line.
  19912. (org-with-wide-buffer
  19913. (goto-char post)
  19914. (end-of-line)
  19915. (skip-chars-forward " \r\t\n")
  19916. (if (eobp) (point) (line-beginning-position))))
  19917. (t (org-element-property :contents-begin element)))))
  19918. (cend (copy-marker
  19919. (or (org-element-property :contents-end element)
  19920. ;; Fake contents for source blocks.
  19921. (org-with-wide-buffer
  19922. (goto-char element-end)
  19923. (skip-chars-backward " \r\t\n")
  19924. (line-beginning-position)))
  19925. t)))
  19926. ;; Do not change items indentation individually as it
  19927. ;; might break the list as a whole. On the other
  19928. ;; hand, when at a plain list, indent it as a whole.
  19929. (cond ((eq type 'plain-list)
  19930. (let ((offset (- ind (current-indentation))))
  19931. (unless (zerop offset)
  19932. (indent-rigidly (org-element-property :begin element)
  19933. (org-element-property :end element)
  19934. offset))
  19935. (goto-char cbeg)))
  19936. ((eq type 'item) (goto-char cbeg))
  19937. (t (funcall indent-to ind (min cbeg end))))
  19938. (when (< (point) end)
  19939. (cl-case type
  19940. ((example-block verse-block))
  19941. (src-block
  19942. ;; In a source block, indent source code
  19943. ;; according to language major mode, but only if
  19944. ;; `org-src-tab-acts-natively' is non-nil.
  19945. (when (and (< (point) end) org-src-tab-acts-natively)
  19946. (ignore-errors
  19947. (org-babel-do-in-edit-buffer
  19948. (indent-region (point-min) (point-max))))))
  19949. (t (org-indent-region (point) (min cend end))))
  19950. (goto-char (min cend end))
  19951. (when (< (point) end)
  19952. (funcall indent-to ind (min element-end end))))
  19953. (set-marker post nil)
  19954. (set-marker cbeg nil)
  19955. (set-marker cend nil))))
  19956. (set-marker element-end nil))))
  19957. (set-marker end nil))))
  19958. (defun org-indent-drawer ()
  19959. "Indent the drawer at point."
  19960. (interactive)
  19961. (unless (save-excursion
  19962. (beginning-of-line)
  19963. (looking-at-p org-drawer-regexp))
  19964. (user-error "Not at a drawer"))
  19965. (let ((element (org-element-at-point)))
  19966. (unless (memq (org-element-type element) '(drawer property-drawer))
  19967. (user-error "Not at a drawer"))
  19968. (org-with-wide-buffer
  19969. (org-indent-region (org-element-property :begin element)
  19970. (org-element-property :end element))))
  19971. (message "Drawer at point indented"))
  19972. (defun org-indent-block ()
  19973. "Indent the block at point."
  19974. (interactive)
  19975. (unless (save-excursion
  19976. (beginning-of-line)
  19977. (let ((case-fold-search t))
  19978. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  19979. (user-error "Not at a block"))
  19980. (let ((element (org-element-at-point)))
  19981. (unless (memq (org-element-type element)
  19982. '(comment-block center-block dynamic-block example-block
  19983. export-block quote-block special-block
  19984. src-block verse-block))
  19985. (user-error "Not at a block"))
  19986. (org-with-wide-buffer
  19987. (org-indent-region (org-element-property :begin element)
  19988. (org-element-property :end element))))
  19989. (message "Block at point indented"))
  19990. ;;; Filling
  19991. ;; We use our own fill-paragraph and auto-fill functions.
  19992. ;; `org-fill-paragraph' relies on adaptive filling and context
  19993. ;; checking. Appropriate `fill-prefix' is computed with
  19994. ;; `org-adaptive-fill-function'.
  19995. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  19996. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  19997. ;; `org-adaptive-fill-function' value. Internally,
  19998. ;; `org-comment-line-break-function' breaks the line.
  19999. ;; `org-setup-filling' installs filling and auto-filling related
  20000. ;; variables during `org-mode' initialization.
  20001. (defun org-setup-filling ()
  20002. (require 'org-element)
  20003. ;; Prevent auto-fill from inserting unwanted new items.
  20004. (when (boundp 'fill-nobreak-predicate)
  20005. (setq-local
  20006. fill-nobreak-predicate
  20007. (org-uniquify
  20008. (append fill-nobreak-predicate
  20009. '(org-fill-line-break-nobreak-p
  20010. org-fill-n-macro-as-item-nobreak-p
  20011. org-fill-paragraph-with-timestamp-nobreak-p)))))
  20012. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  20013. (setq-local paragraph-start paragraph-ending)
  20014. (setq-local paragraph-separate paragraph-ending))
  20015. (setq-local fill-paragraph-function 'org-fill-paragraph)
  20016. (setq-local auto-fill-inhibit-regexp nil)
  20017. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  20018. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  20019. (setq-local comment-line-break-function 'org-comment-line-break-function))
  20020. (defun org-fill-line-break-nobreak-p ()
  20021. "Non-nil when a new line at point would create an Org line break."
  20022. (save-excursion
  20023. (skip-chars-backward "[ \t]")
  20024. (skip-chars-backward "\\\\")
  20025. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  20026. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  20027. "Non-nil when a new line at point would split a timestamp."
  20028. (and (org-at-timestamp-p 'lax)
  20029. (not (looking-at org-ts-regexp-both))))
  20030. (defun org-fill-n-macro-as-item-nobreak-p ()
  20031. "Non-nil when a new line at point would create a new list."
  20032. ;; During export, a "n" macro followed by a dot or a closing
  20033. ;; parenthesis can end up being parsed as a new list item.
  20034. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  20035. (defvar orgtbl-line-start-regexp) ; From org-table.el
  20036. (defun org-adaptive-fill-function ()
  20037. "Compute a fill prefix for the current line.
  20038. Return fill prefix, as a string, or nil if current line isn't
  20039. meant to be filled. For convenience, if `adaptive-fill-regexp'
  20040. matches in paragraphs or comments, use it."
  20041. (org-with-wide-buffer
  20042. (unless (org-at-heading-p)
  20043. (let* ((p (line-beginning-position))
  20044. (element (save-excursion
  20045. (beginning-of-line)
  20046. (org-element-at-point)))
  20047. (type (org-element-type element))
  20048. (post-affiliated (org-element-property :post-affiliated element)))
  20049. (unless (< p post-affiliated)
  20050. (cl-case type
  20051. (comment
  20052. (save-excursion
  20053. (beginning-of-line)
  20054. (looking-at "[ \t]*")
  20055. (concat (match-string 0) "# ")))
  20056. (footnote-definition "")
  20057. ((item plain-list)
  20058. (make-string (org-list-item-body-column post-affiliated) ?\s))
  20059. (paragraph
  20060. ;; Fill prefix is usually the same as the current line,
  20061. ;; unless the paragraph is at the beginning of an item.
  20062. (let ((parent (org-element-property :parent element)))
  20063. (save-excursion
  20064. (beginning-of-line)
  20065. (cond ((eq (org-element-type parent) 'item)
  20066. (make-string (org-list-item-body-column
  20067. (org-element-property :begin parent))
  20068. ?\s))
  20069. ((and adaptive-fill-regexp
  20070. ;; Locally disable
  20071. ;; `adaptive-fill-function' to let
  20072. ;; `fill-context-prefix' handle
  20073. ;; `adaptive-fill-regexp' variable.
  20074. (let (adaptive-fill-function)
  20075. (fill-context-prefix
  20076. post-affiliated
  20077. (org-element-property :end element)))))
  20078. ((looking-at "[ \t]+") (match-string 0))
  20079. (t "")))))
  20080. (comment-block
  20081. ;; Only fill contents if P is within block boundaries.
  20082. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  20083. (forward-line)
  20084. (point)))
  20085. (cend (save-excursion
  20086. (goto-char (org-element-property :end element))
  20087. (skip-chars-backward " \r\t\n")
  20088. (line-beginning-position))))
  20089. (when (and (>= p cbeg) (< p cend))
  20090. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  20091. (match-string 0)
  20092. ""))))))))))
  20093. (defun org-fill-element (&optional justify)
  20094. "Fill element at point, when applicable.
  20095. This function only applies to comment blocks, comments, example
  20096. blocks and paragraphs. Also, as a special case, re-align table
  20097. when point is at one.
  20098. If JUSTIFY is non-nil (interactively, with prefix argument),
  20099. justify as well. If `sentence-end-double-space' is non-nil, then
  20100. period followed by one space does not end a sentence, so don't
  20101. break a line there. The variable `fill-column' controls the
  20102. width for filling.
  20103. For convenience, when point is at a plain list, an item or
  20104. a footnote definition, try to fill the first paragraph within."
  20105. (with-syntax-table org-mode-transpose-word-syntax-table
  20106. ;; Move to end of line in order to get the first paragraph within
  20107. ;; a plain list or a footnote definition.
  20108. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  20109. ;; First check if point is in a blank line at the beginning of
  20110. ;; the buffer. In that case, ignore filling.
  20111. (cl-case (org-element-type element)
  20112. ;; Use major mode filling function is src blocks.
  20113. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  20114. ;; Align Org tables, leave table.el tables as-is.
  20115. (table-row (org-table-align) t)
  20116. (table
  20117. (when (eq (org-element-property :type element) 'org)
  20118. (save-excursion
  20119. (goto-char (org-element-property :post-affiliated element))
  20120. (org-table-align)))
  20121. t)
  20122. (paragraph
  20123. ;; Paragraphs may contain `line-break' type objects.
  20124. (let ((beg (max (point-min)
  20125. (org-element-property :contents-begin element)))
  20126. (end (min (point-max)
  20127. (org-element-property :contents-end element))))
  20128. ;; Do nothing if point is at an affiliated keyword.
  20129. (if (< (line-end-position) beg) t
  20130. ;; Fill paragraph, taking line breaks into account.
  20131. (save-excursion
  20132. (goto-char beg)
  20133. (let ((cuts (list beg)))
  20134. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  20135. (when (eq 'line-break
  20136. (org-element-type
  20137. (save-excursion (backward-char)
  20138. (org-element-context))))
  20139. (push (point) cuts)))
  20140. (dolist (c (delq end cuts))
  20141. (fill-region-as-paragraph c end justify)
  20142. (setq end c))))
  20143. t)))
  20144. ;; Contents of `comment-block' type elements should be
  20145. ;; filled as plain text, but only if point is within block
  20146. ;; markers.
  20147. (comment-block
  20148. (let* ((case-fold-search t)
  20149. (beg (save-excursion
  20150. (goto-char (org-element-property :begin element))
  20151. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  20152. (forward-line)
  20153. (point)))
  20154. (end (save-excursion
  20155. (goto-char (org-element-property :end element))
  20156. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  20157. (line-beginning-position))))
  20158. (if (or (< (point) beg) (> (point) end)) t
  20159. (fill-region-as-paragraph
  20160. (save-excursion (end-of-line)
  20161. (re-search-backward "^[ \t]*$" beg 'move)
  20162. (line-beginning-position))
  20163. (save-excursion (beginning-of-line)
  20164. (re-search-forward "^[ \t]*$" end 'move)
  20165. (line-beginning-position))
  20166. justify))))
  20167. ;; Fill comments.
  20168. (comment
  20169. (let ((begin (org-element-property :post-affiliated element))
  20170. (end (org-element-property :end element)))
  20171. (when (and (>= (point) begin) (<= (point) end))
  20172. (let ((begin (save-excursion
  20173. (end-of-line)
  20174. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  20175. (progn (forward-line) (point))
  20176. begin)))
  20177. (end (save-excursion
  20178. (end-of-line)
  20179. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  20180. (1- (line-beginning-position))
  20181. (skip-chars-backward " \r\t\n")
  20182. (line-end-position)))))
  20183. ;; Do not fill comments when at a blank line.
  20184. (when (> end begin)
  20185. (let ((fill-prefix
  20186. (save-excursion
  20187. (beginning-of-line)
  20188. (looking-at "[ \t]*#")
  20189. (let ((comment-prefix (match-string 0)))
  20190. (goto-char (match-end 0))
  20191. (if (looking-at adaptive-fill-regexp)
  20192. (concat comment-prefix (match-string 0))
  20193. (concat comment-prefix " "))))))
  20194. (save-excursion
  20195. (fill-region-as-paragraph begin end justify))))))
  20196. t))
  20197. ;; Ignore every other element.
  20198. (otherwise t)))))
  20199. (defun org-fill-paragraph (&optional justify region)
  20200. "Fill element at point, when applicable.
  20201. This function only applies to comment blocks, comments, example
  20202. blocks and paragraphs. Also, as a special case, re-align table
  20203. when point is at one.
  20204. For convenience, when point is at a plain list, an item or
  20205. a footnote definition, try to fill the first paragraph within.
  20206. If JUSTIFY is non-nil (interactively, with prefix argument),
  20207. justify as well. If `sentence-end-double-space' is non-nil, then
  20208. period followed by one space does not end a sentence, so don't
  20209. break a line there. The variable `fill-column' controls the
  20210. width for filling.
  20211. The REGION argument is non-nil if called interactively; in that
  20212. case, if Transient Mark mode is enabled and the mark is active,
  20213. fill each of the elements in the active region, instead of just
  20214. filling the current element."
  20215. (interactive (progn
  20216. (barf-if-buffer-read-only)
  20217. (list (when current-prefix-arg 'full) t)))
  20218. (cond
  20219. ((and region transient-mark-mode mark-active
  20220. (not (eq (region-beginning) (region-end))))
  20221. (let ((origin (point-marker))
  20222. (start (region-beginning)))
  20223. (unwind-protect
  20224. (progn
  20225. (goto-char (region-end))
  20226. (while (> (point) start)
  20227. (org-backward-paragraph)
  20228. (org-fill-element justify)))
  20229. (goto-char origin)
  20230. (set-marker origin nil))))
  20231. (t (org-fill-element justify))))
  20232. (defun org-auto-fill-function ()
  20233. "Auto-fill function."
  20234. ;; Check if auto-filling is meaningful.
  20235. (let ((fc (current-fill-column)))
  20236. (when (and fc (> (current-column) fc))
  20237. (let* ((fill-prefix (org-adaptive-fill-function))
  20238. ;; Enforce empty fill prefix, if required. Otherwise, it
  20239. ;; will be computed again.
  20240. (adaptive-fill-mode (not (equal fill-prefix ""))))
  20241. (when fill-prefix (do-auto-fill))))))
  20242. (defun org-comment-line-break-function (&optional soft)
  20243. "Break line at point and indent, continuing comment if within one.
  20244. The inserted newline is marked hard if variable
  20245. `use-hard-newlines' is true, unless optional argument SOFT is
  20246. non-nil."
  20247. (if soft (insert-and-inherit ?\n) (newline 1))
  20248. (save-excursion (forward-char -1) (delete-horizontal-space))
  20249. (delete-horizontal-space)
  20250. (indent-to-left-margin)
  20251. (insert-before-markers-and-inherit fill-prefix))
  20252. ;;; Fixed Width Areas
  20253. (defun org-toggle-fixed-width ()
  20254. "Toggle fixed-width markup.
  20255. Add or remove fixed-width markup on current line, whenever it
  20256. makes sense. Return an error otherwise.
  20257. If a region is active and if it contains only fixed-width areas
  20258. or blank lines, remove all fixed-width markup in it. If the
  20259. region contains anything else, convert all non-fixed-width lines
  20260. to fixed-width ones.
  20261. Blank lines at the end of the region are ignored unless the
  20262. region only contains such lines."
  20263. (interactive)
  20264. (if (not (org-region-active-p))
  20265. ;; No region:
  20266. ;;
  20267. ;; Remove fixed width marker only in a fixed-with element.
  20268. ;;
  20269. ;; Add fixed width maker in paragraphs, in blank lines after
  20270. ;; elements or at the beginning of a headline or an inlinetask,
  20271. ;; and before any one-line elements (e.g., a clock).
  20272. (progn
  20273. (beginning-of-line)
  20274. (let* ((element (org-element-at-point))
  20275. (type (org-element-type element)))
  20276. (cond
  20277. ((and (eq type 'fixed-width)
  20278. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  20279. (replace-match
  20280. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  20281. ((and (memq type '(babel-call clock comment diary-sexp headline
  20282. horizontal-rule keyword paragraph
  20283. planning))
  20284. (<= (org-element-property :post-affiliated element) (point)))
  20285. (skip-chars-forward " \t")
  20286. (insert ": "))
  20287. ((and (looking-at-p "[ \t]*$")
  20288. (or (eq type 'inlinetask)
  20289. (save-excursion
  20290. (skip-chars-forward " \r\t\n")
  20291. (<= (org-element-property :end element) (point)))))
  20292. (delete-region (point) (line-end-position))
  20293. (org-indent-line)
  20294. (insert ": "))
  20295. (t (user-error "Cannot insert a fixed-width line here")))))
  20296. ;; Region active.
  20297. (let* ((begin (save-excursion
  20298. (goto-char (region-beginning))
  20299. (line-beginning-position)))
  20300. (end (copy-marker
  20301. (save-excursion
  20302. (goto-char (region-end))
  20303. (unless (eolp) (beginning-of-line))
  20304. (if (save-excursion (re-search-backward "\\S-" begin t))
  20305. (progn (skip-chars-backward " \r\t\n") (point))
  20306. (point)))))
  20307. (all-fixed-width-p
  20308. (catch 'not-all-p
  20309. (save-excursion
  20310. (goto-char begin)
  20311. (skip-chars-forward " \r\t\n")
  20312. (when (eobp) (throw 'not-all-p nil))
  20313. (while (< (point) end)
  20314. (let ((element (org-element-at-point)))
  20315. (if (eq (org-element-type element) 'fixed-width)
  20316. (goto-char (org-element-property :end element))
  20317. (throw 'not-all-p nil))))
  20318. t))))
  20319. (if all-fixed-width-p
  20320. (save-excursion
  20321. (goto-char begin)
  20322. (while (< (point) end)
  20323. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  20324. (replace-match
  20325. "" nil nil nil
  20326. (if (= (line-end-position) (match-end 0)) 0 1)))
  20327. (forward-line)))
  20328. (let ((min-ind (point-max)))
  20329. ;; Find minimum indentation across all lines.
  20330. (save-excursion
  20331. (goto-char begin)
  20332. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  20333. (setq min-ind 0)
  20334. (catch 'zerop
  20335. (while (< (point) end)
  20336. (unless (looking-at-p "[ \t]*$")
  20337. (let ((ind (current-indentation)))
  20338. (setq min-ind (min min-ind ind))
  20339. (when (zerop ind) (throw 'zerop t))))
  20340. (forward-line)))))
  20341. ;; Loop over all lines and add fixed-width markup everywhere
  20342. ;; but in fixed-width lines.
  20343. (save-excursion
  20344. (goto-char begin)
  20345. (while (< (point) end)
  20346. (cond
  20347. ((org-at-heading-p)
  20348. (insert ": ")
  20349. (forward-line)
  20350. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  20351. (insert ":")
  20352. (forward-line)))
  20353. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  20354. (let* ((element (org-element-at-point))
  20355. (element-end (org-element-property :end element)))
  20356. (if (eq (org-element-type element) 'fixed-width)
  20357. (progn (goto-char element-end)
  20358. (skip-chars-backward " \r\t\n")
  20359. (forward-line))
  20360. (let ((limit (min end element-end)))
  20361. (while (< (point) limit)
  20362. (org-move-to-column min-ind t)
  20363. (insert ": ")
  20364. (forward-line))))))
  20365. (t
  20366. (org-move-to-column min-ind t)
  20367. (insert ": ")
  20368. (forward-line)))))))
  20369. (set-marker end nil))))
  20370. ;;; Blocks
  20371. (defun org-block-map (function &optional start end)
  20372. "Call FUNCTION at the head of all source blocks in the current buffer.
  20373. Optional arguments START and END can be used to limit the range."
  20374. (let ((start (or start (point-min)))
  20375. (end (or end (point-max))))
  20376. (save-excursion
  20377. (goto-char start)
  20378. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  20379. (save-excursion
  20380. (save-match-data
  20381. (goto-char (match-beginning 0))
  20382. (funcall function)))))))
  20383. (defun org-next-block (arg &optional backward block-regexp)
  20384. "Jump to the next block.
  20385. With a prefix argument ARG, jump forward ARG many blocks.
  20386. When BACKWARD is non-nil, jump to the previous block.
  20387. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  20388. Match data is set according to this regexp when the function
  20389. returns.
  20390. Return point at beginning of the opening line of found block.
  20391. Throw an error if no block is found."
  20392. (interactive "p")
  20393. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  20394. (case-fold-search t)
  20395. (search-fn (if backward #'re-search-backward #'re-search-forward))
  20396. (count (or arg 1))
  20397. (origin (point))
  20398. last-element)
  20399. (if backward (beginning-of-line) (end-of-line))
  20400. (while (and (> count 0) (funcall search-fn re nil t))
  20401. (let ((element (save-excursion
  20402. (goto-char (match-beginning 0))
  20403. (save-match-data (org-element-at-point)))))
  20404. (when (and (memq (org-element-type element)
  20405. '(center-block comment-block dynamic-block
  20406. example-block export-block quote-block
  20407. special-block src-block verse-block))
  20408. (<= (match-beginning 0)
  20409. (org-element-property :post-affiliated element)))
  20410. (setq last-element element)
  20411. (cl-decf count))))
  20412. (if (= count 0)
  20413. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  20414. (save-match-data (org-show-context)))
  20415. (goto-char origin)
  20416. (user-error "No %s code blocks" (if backward "previous" "further")))))
  20417. (defun org-previous-block (arg &optional block-regexp)
  20418. "Jump to the previous block.
  20419. With a prefix argument ARG, jump backward ARG many source blocks.
  20420. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  20421. (interactive "p")
  20422. (org-next-block arg t block-regexp))
  20423. ;;; Comments
  20424. ;; Org comments syntax is quite complex. It requires the entire line
  20425. ;; to be just a comment. Also, even with the right syntax at the
  20426. ;; beginning of line, some elements (e.g., verse-block or
  20427. ;; example-block) don't accept comments. Usual Emacs comment commands
  20428. ;; cannot cope with those requirements. Therefore, Org replaces them.
  20429. ;; Org still relies on `comment-dwim', but cannot trust
  20430. ;; `comment-only-p'. So, `comment-region-function' and
  20431. ;; `uncomment-region-function' both point
  20432. ;; to`org-comment-or-uncomment-region'. Eventually,
  20433. ;; `org-insert-comment' takes care of insertion of comments at the
  20434. ;; beginning of line.
  20435. ;; `org-setup-comments-handling' install comments related variables
  20436. ;; during `org-mode' initialization.
  20437. (defun org-setup-comments-handling ()
  20438. (interactive)
  20439. (setq-local comment-use-syntax nil)
  20440. (setq-local comment-start "# ")
  20441. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  20442. (setq-local comment-insert-comment-function 'org-insert-comment)
  20443. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  20444. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  20445. (defun org-insert-comment ()
  20446. "Insert an empty comment above current line.
  20447. If the line is empty, insert comment at its beginning. When
  20448. point is within a source block, comment according to the related
  20449. major mode."
  20450. (if (let ((element (org-element-at-point)))
  20451. (and (eq (org-element-type element) 'src-block)
  20452. (< (save-excursion
  20453. (goto-char (org-element-property :post-affiliated element))
  20454. (line-end-position))
  20455. (point))
  20456. (> (save-excursion
  20457. (goto-char (org-element-property :end element))
  20458. (skip-chars-backward " \r\t\n")
  20459. (line-beginning-position))
  20460. (point))))
  20461. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  20462. (beginning-of-line)
  20463. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  20464. (open-line 1))
  20465. (org-indent-line)
  20466. (insert "# ")))
  20467. (defvar comment-empty-lines) ; From newcomment.el.
  20468. (defun org-comment-or-uncomment-region (beg end &rest _)
  20469. "Comment or uncomment each non-blank line in the region.
  20470. Uncomment each non-blank line between BEG and END if it only
  20471. contains commented lines. Otherwise, comment them. If region is
  20472. strictly within a source block, use appropriate comment syntax."
  20473. (if (let ((element (org-element-at-point)))
  20474. (and (eq (org-element-type element) 'src-block)
  20475. (< (save-excursion
  20476. (goto-char (org-element-property :post-affiliated element))
  20477. (line-end-position))
  20478. beg)
  20479. (>= (save-excursion
  20480. (goto-char (org-element-property :end element))
  20481. (skip-chars-backward " \r\t\n")
  20482. (line-beginning-position))
  20483. end)))
  20484. ;; Translate region boundaries for the Org buffer to the source
  20485. ;; buffer.
  20486. (let ((offset (- end beg)))
  20487. (save-excursion
  20488. (goto-char beg)
  20489. (org-babel-do-in-edit-buffer
  20490. (comment-or-uncomment-region (point) (+ offset (point))))))
  20491. (save-restriction
  20492. ;; Restrict region
  20493. (narrow-to-region (save-excursion (goto-char beg)
  20494. (skip-chars-forward " \r\t\n" end)
  20495. (line-beginning-position))
  20496. (save-excursion (goto-char end)
  20497. (skip-chars-backward " \r\t\n" beg)
  20498. (line-end-position)))
  20499. (let ((uncommentp
  20500. ;; UNCOMMENTP is non-nil when every non blank line between
  20501. ;; BEG and END is a comment.
  20502. (save-excursion
  20503. (goto-char (point-min))
  20504. (while (and (not (eobp))
  20505. (let ((element (org-element-at-point)))
  20506. (and (eq (org-element-type element) 'comment)
  20507. (goto-char (min (point-max)
  20508. (org-element-property
  20509. :end element)))))))
  20510. (eobp))))
  20511. (if uncommentp
  20512. ;; Only blank lines and comments in region: uncomment it.
  20513. (save-excursion
  20514. (goto-char (point-min))
  20515. (while (not (eobp))
  20516. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  20517. (replace-match "" nil nil nil 1))
  20518. (forward-line)))
  20519. ;; Comment each line in region.
  20520. (let ((min-indent (point-max)))
  20521. ;; First find the minimum indentation across all lines.
  20522. (save-excursion
  20523. (goto-char (point-min))
  20524. (while (and (not (eobp)) (not (zerop min-indent)))
  20525. (unless (looking-at "[ \t]*$")
  20526. (setq min-indent (min min-indent (current-indentation))))
  20527. (forward-line)))
  20528. ;; Then loop over all lines.
  20529. (save-excursion
  20530. (goto-char (point-min))
  20531. (while (not (eobp))
  20532. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  20533. ;; Don't get fooled by invisible text (e.g. link path)
  20534. ;; when moving to column MIN-INDENT.
  20535. (let ((buffer-invisibility-spec nil))
  20536. (org-move-to-column min-indent t))
  20537. (insert comment-start))
  20538. (forward-line)))))))))
  20539. (defun org-comment-dwim (_arg)
  20540. "Call the comment command you mean.
  20541. Call `org-toggle-comment' if on a heading, otherwise call
  20542. `comment-dwim', within a source edit buffer if needed."
  20543. (interactive "*P")
  20544. (cond ((org-at-heading-p)
  20545. (call-interactively #'org-toggle-comment))
  20546. ((org-in-src-block-p)
  20547. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  20548. (t (call-interactively #'comment-dwim))))
  20549. ;;; Timestamps API
  20550. ;; This section contains tools to operate on, or create, timestamp
  20551. ;; objects, as returned by, e.g. `org-element-context'.
  20552. (defun org-timestamp-from-string (s)
  20553. "Convert Org timestamp S, as a string, into a timestamp object.
  20554. Return nil if S is not a valid timestamp string."
  20555. (when (org-string-nw-p s)
  20556. (with-temp-buffer
  20557. (save-excursion (insert s))
  20558. (org-element-timestamp-parser))))
  20559. (defun org-timestamp-from-time (time &optional with-time inactive)
  20560. "Convert a time value into a timestamp object.
  20561. TIME is an Emacs internal time representation, as returned, e.g.,
  20562. by `current-time'.
  20563. When optional argument WITH-TIME is non-nil, return a timestamp
  20564. object with a time part, i.e., with hours and minutes.
  20565. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  20566. return an active timestamp."
  20567. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  20568. (org-element-create 'timestamp
  20569. (list :type (if inactive 'inactive 'active)
  20570. :year-start year
  20571. :month-start month
  20572. :day-start day
  20573. :hour-start (and with-time hour)
  20574. :minute-start (and with-time minute)))))
  20575. (defun org-timestamp-to-time (timestamp &optional end)
  20576. "Convert TIMESTAMP object into an Emacs internal time value.
  20577. Use end of date range or time range when END is non-nil.
  20578. Otherwise, use its start."
  20579. (apply #'encode-time
  20580. (cons 0
  20581. (mapcar
  20582. (lambda (prop) (or (org-element-property prop timestamp) 0))
  20583. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  20584. '(:minute-start :hour-start :day-start :month-start
  20585. :year-start))))))
  20586. (defun org-timestamp-has-time-p (timestamp)
  20587. "Non-nil when TIMESTAMP has a time specified."
  20588. (org-element-property :hour-start timestamp))
  20589. (defun org-timestamp-format (timestamp format &optional end utc)
  20590. "Format a TIMESTAMP object into a string.
  20591. FORMAT is a format specifier to be passed to
  20592. `format-time-string'.
  20593. When optional argument END is non-nil, use end of date-range or
  20594. time-range, if possible.
  20595. When optional argument UTC is non-nil, time is be expressed as
  20596. Universal Time."
  20597. (format-time-string format (org-timestamp-to-time timestamp end)
  20598. (and utc t)))
  20599. (defun org-timestamp-split-range (timestamp &optional end)
  20600. "Extract a TIMESTAMP object from a date or time range.
  20601. END, when non-nil, means extract the end of the range.
  20602. Otherwise, extract its start.
  20603. Return a new timestamp object."
  20604. (let ((type (org-element-property :type timestamp)))
  20605. (if (memq type '(active inactive diary)) timestamp
  20606. (let ((split-ts (org-element-copy timestamp)))
  20607. ;; Set new type.
  20608. (org-element-put-property
  20609. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  20610. ;; Copy start properties over end properties if END is
  20611. ;; non-nil. Otherwise, copy end properties over `start' ones.
  20612. (let ((p-alist '((:minute-start . :minute-end)
  20613. (:hour-start . :hour-end)
  20614. (:day-start . :day-end)
  20615. (:month-start . :month-end)
  20616. (:year-start . :year-end))))
  20617. (dolist (p-cell p-alist)
  20618. (org-element-put-property
  20619. split-ts
  20620. (funcall (if end #'car #'cdr) p-cell)
  20621. (org-element-property
  20622. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  20623. ;; Eventually refresh `:raw-value'.
  20624. (org-element-put-property split-ts :raw-value nil)
  20625. (org-element-put-property
  20626. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  20627. (defun org-timestamp-translate (timestamp &optional boundary)
  20628. "Translate TIMESTAMP object to custom format.
  20629. Format string is defined in `org-time-stamp-custom-formats',
  20630. which see.
  20631. When optional argument BOUNDARY is non-nil, it is either the
  20632. symbol `start' or `end'. In this case, only translate the
  20633. starting or ending part of TIMESTAMP if it is a date or time
  20634. range. Otherwise, translate both parts.
  20635. Return timestamp as-is if `org-display-custom-times' is nil or if
  20636. it has a `diary' type."
  20637. (let ((type (org-element-property :type timestamp)))
  20638. (if (or (not org-display-custom-times) (eq type 'diary))
  20639. (org-element-interpret-data timestamp)
  20640. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  20641. org-time-stamp-custom-formats)))
  20642. (if (and (not boundary) (memq type '(active-range inactive-range)))
  20643. (concat (org-timestamp-format timestamp fmt)
  20644. "--"
  20645. (org-timestamp-format timestamp fmt t))
  20646. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  20647. ;;; Other stuff
  20648. (defvar reftex-docstruct-symbol)
  20649. (defvar org--rds)
  20650. (defun org-reftex-citation ()
  20651. "Use reftex-citation to insert a citation into the buffer.
  20652. This looks for a line like
  20653. #+BIBLIOGRAPHY: foo plain option:-d
  20654. and derives from it that foo.bib is the bibliography file relevant
  20655. for this document. It then installs the necessary environment for RefTeX
  20656. to work in this buffer and calls `reftex-citation' to insert a citation
  20657. into the buffer.
  20658. Export of such citations to both LaTeX and HTML is handled by the contributed
  20659. package ox-bibtex by Taru Karttunen."
  20660. (interactive)
  20661. (let ((reftex-docstruct-symbol 'org--rds)
  20662. org--rds bib)
  20663. (org-with-wide-buffer
  20664. (let ((case-fold-search t)
  20665. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  20666. (if (not (save-excursion
  20667. (or (re-search-forward re nil t)
  20668. (re-search-backward re nil t))))
  20669. (user-error "No bibliography defined in file")
  20670. (setq bib (concat (match-string 1) ".bib")
  20671. org--rds (list (list 'bib bib))))))
  20672. (call-interactively 'reftex-citation)))
  20673. ;;;; Functions extending outline functionality
  20674. (defun org-beginning-of-line (&optional n)
  20675. "Go to the beginning of the current visible line.
  20676. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  20677. symbol `reversed', on the first attempt move to where the
  20678. headline text starts, and only move to beginning of line when the
  20679. cursor is already before the start of the text of the headline.
  20680. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  20681. start of the text on the second attempt.
  20682. With argument N not nil or 1, move forward N - 1 lines first."
  20683. (interactive "^p")
  20684. (let ((origin (point))
  20685. (special (pcase org-special-ctrl-a/e
  20686. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  20687. deactivate-mark)
  20688. ;; First move to a visible line.
  20689. (if (bound-and-true-p visual-line-mode)
  20690. (beginning-of-visual-line n)
  20691. (move-beginning-of-line n)
  20692. ;; `move-beginning-of-line' may leave point after invisible
  20693. ;; characters if line starts with such of these (e.g., with
  20694. ;; a link at column 0). Really move to the beginning of the
  20695. ;; current visible line.
  20696. (beginning-of-line))
  20697. (cond
  20698. ;; No special behavior. Point is already at the beginning of
  20699. ;; a line, logical or visual.
  20700. ((not special))
  20701. ;; `beginning-of-visual-line' left point before logical beginning
  20702. ;; of line: point is at the beginning of a visual line. Bail
  20703. ;; out.
  20704. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  20705. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  20706. ;; At a headline, special position is before the title, but
  20707. ;; after any TODO keyword or priority cookie.
  20708. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  20709. (line-end-position)))
  20710. (bol (point)))
  20711. (if (eq special 'reversed)
  20712. (when (and (= origin bol) (eq last-command this-command))
  20713. (goto-char refpos))
  20714. (when (or (> origin refpos) (= origin bol))
  20715. (goto-char refpos)))))
  20716. ((and (looking-at org-list-full-item-re)
  20717. (memq (org-element-type (save-match-data (org-element-at-point)))
  20718. '(item plain-list)))
  20719. ;; Set special position at first white space character after
  20720. ;; bullet, and check-box, if any.
  20721. (let ((after-bullet
  20722. (let ((box (match-end 3)))
  20723. (cond ((not box) (match-end 1))
  20724. ((eq (char-after box) ?\s) (1+ box))
  20725. (t box)))))
  20726. (if (eq special 'reversed)
  20727. (when (and (= (point) origin) (eq last-command this-command))
  20728. (goto-char after-bullet))
  20729. (when (or (> origin after-bullet) (= (point) origin))
  20730. (goto-char after-bullet)))))
  20731. ;; No special context. Point is already at beginning of line.
  20732. (t nil))))
  20733. (defun org-end-of-line (&optional n)
  20734. "Go to the end of the line, but before ellipsis, if any.
  20735. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  20736. symbol `reversed', ignore tags on the first attempt, and only
  20737. move to after the tags when the cursor is already beyond the end
  20738. of the headline.
  20739. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  20740. on the second attempt.
  20741. With argument N not nil or 1, move forward N - 1 lines first."
  20742. (interactive "^p")
  20743. (let ((origin (point))
  20744. (special (pcase org-special-ctrl-a/e
  20745. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  20746. deactivate-mark)
  20747. ;; First move to a visible line.
  20748. (if (bound-and-true-p visual-line-mode)
  20749. (beginning-of-visual-line n)
  20750. (move-beginning-of-line n))
  20751. (cond
  20752. ;; At a headline, with tags.
  20753. ((and special
  20754. (save-excursion
  20755. (beginning-of-line)
  20756. (let ((case-fold-search nil))
  20757. (looking-at org-complex-heading-regexp)))
  20758. (match-end 5))
  20759. (let ((tags (save-excursion
  20760. (goto-char (match-beginning 5))
  20761. (skip-chars-backward " \t")
  20762. (point)))
  20763. (visual-end (and (bound-and-true-p visual-line-mode)
  20764. (save-excursion
  20765. (end-of-visual-line)
  20766. (point)))))
  20767. ;; If `end-of-visual-line' brings us before end of line or
  20768. ;; even tags, i.e., the headline spans over multiple visual
  20769. ;; lines, move there.
  20770. (cond ((and visual-end
  20771. (< visual-end tags)
  20772. (<= origin visual-end))
  20773. (goto-char visual-end))
  20774. ((eq special 'reversed)
  20775. (if (and (= origin (line-end-position))
  20776. (eq this-command last-command))
  20777. (goto-char tags)
  20778. (end-of-line)))
  20779. (t
  20780. (if (or (< origin tags) (= origin (line-end-position)))
  20781. (goto-char tags)
  20782. (end-of-line))))))
  20783. ((bound-and-true-p visual-line-mode)
  20784. (let ((bol (line-beginning-position)))
  20785. (end-of-visual-line)
  20786. ;; If `end-of-visual-line' gets us past the ellipsis at the
  20787. ;; end of a line, backtrack and use `end-of-line' instead.
  20788. (when (/= bol (line-beginning-position))
  20789. (goto-char bol)
  20790. (end-of-line))))
  20791. (t (end-of-line)))))
  20792. (defun org-backward-sentence (&optional _arg)
  20793. "Go to beginning of sentence, or beginning of table field.
  20794. This will call `backward-sentence' or `org-table-beginning-of-field',
  20795. depending on context."
  20796. (interactive)
  20797. (let* ((element (org-element-at-point))
  20798. (contents-begin (org-element-property :contents-begin element))
  20799. (table (org-element-lineage element '(table) t)))
  20800. (if (and table
  20801. (> (point) contents-begin)
  20802. (<= (point) (org-element-property :contents-end table)))
  20803. (call-interactively #'org-table-beginning-of-field)
  20804. (save-restriction
  20805. (when (and contents-begin
  20806. (< (point-min) contents-begin)
  20807. (> (point) contents-begin))
  20808. (narrow-to-region contents-begin
  20809. (org-element-property :contents-end element)))
  20810. (call-interactively #'backward-sentence)))))
  20811. (defun org-forward-sentence (&optional _arg)
  20812. "Go to end of sentence, or end of table field.
  20813. This will call `forward-sentence' or `org-table-end-of-field',
  20814. depending on context."
  20815. (interactive)
  20816. (if (and (org-at-heading-p)
  20817. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  20818. (save-restriction
  20819. (narrow-to-region (line-beginning-position) (line-end-position))
  20820. (call-interactively #'forward-sentence))
  20821. (let* ((element (org-element-at-point))
  20822. (contents-end (org-element-property :contents-end element))
  20823. (table (org-element-lineage element '(table) t)))
  20824. (if (and table
  20825. (>= (point) (org-element-property :contents-begin table))
  20826. (< (point) contents-end))
  20827. (call-interactively #'org-table-end-of-field)
  20828. (save-restriction
  20829. (when (and contents-end
  20830. (> (point-max) contents-end)
  20831. ;; Skip blank lines between elements.
  20832. (< (org-element-property :end element)
  20833. (save-excursion (goto-char contents-end)
  20834. (skip-chars-forward " \r\t\n"))))
  20835. (narrow-to-region (org-element-property :contents-begin element)
  20836. contents-end))
  20837. ;; End of heading is considered as the end of a sentence.
  20838. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  20839. (call-interactively #'forward-sentence)))))))
  20840. (defun org-kill-line (&optional _arg)
  20841. "Kill line, to tags or end of line."
  20842. (interactive)
  20843. (cond
  20844. ((or (not org-special-ctrl-k)
  20845. (bolp)
  20846. (not (org-at-heading-p)))
  20847. (when (and (get-char-property (line-end-position) 'invisible)
  20848. org-ctrl-k-protect-subtree
  20849. (or (eq org-ctrl-k-protect-subtree 'error)
  20850. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  20851. (user-error
  20852. (substitute-command-keys
  20853. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  20854. (call-interactively
  20855. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  20856. ((looking-at org-tag-line-re)
  20857. (let ((end (save-excursion
  20858. (goto-char (match-beginning 1))
  20859. (skip-chars-backward " \t"))))
  20860. (if (<= end (point)) ;on tags part
  20861. (kill-region (point) (line-end-position))
  20862. (kill-region (point) end)))
  20863. (org-align-tags))
  20864. (t (kill-region (point) (line-end-position)))))
  20865. (defun org-yank (&optional arg)
  20866. "Yank. If the kill is a subtree, treat it specially.
  20867. This command will look at the current kill and check if is a single
  20868. subtree, or a series of subtrees[1]. If it passes the test, and if the
  20869. cursor is at the beginning of a line or after the stars of a currently
  20870. empty headline, then the yank is handled specially. How exactly depends
  20871. on the value of the following variables.
  20872. `org-yank-folded-subtrees'
  20873. By default, this variable is non-nil, which results in
  20874. subtree(s) being folded after insertion, except if doing so
  20875. would swallow text after the yanked text.
  20876. `org-yank-adjusted-subtrees'
  20877. When non-nil (the default value is nil), the subtree will be
  20878. promoted or demoted in order to fit into the local outline tree
  20879. structure, which means that the level will be adjusted so that it
  20880. becomes the smaller one of the two *visible* surrounding headings.
  20881. Any prefix to this command will cause `yank' to be called directly with
  20882. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  20883. will just
  20884. plainly yank the text as it is.
  20885. \[1] The test checks if the first non-white line is a heading
  20886. and if there are no other headings with fewer stars."
  20887. (interactive "P")
  20888. (org-yank-generic 'yank arg))
  20889. (defun org-yank-generic (command arg)
  20890. "Perform some yank-like command.
  20891. This function implements the behavior described in the `org-yank'
  20892. documentation. However, it has been generalized to work for any
  20893. interactive command with similar behavior."
  20894. ;; pretend to be command COMMAND
  20895. (setq this-command command)
  20896. (if arg
  20897. (call-interactively command)
  20898. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  20899. (and (org-kill-is-subtree-p)
  20900. (or (bolp)
  20901. (and (looking-at "[ \t]*$")
  20902. (string-match
  20903. "\\`\\*+\\'"
  20904. (buffer-substring (point-at-bol) (point)))))))
  20905. swallowp)
  20906. (cond
  20907. ((and subtreep org-yank-folded-subtrees)
  20908. (let ((beg (point))
  20909. end)
  20910. (if (and subtreep org-yank-adjusted-subtrees)
  20911. (org-paste-subtree nil nil 'for-yank)
  20912. (call-interactively command))
  20913. (setq end (point))
  20914. (goto-char beg)
  20915. (when (and (bolp) subtreep
  20916. (not (setq swallowp
  20917. (org-yank-folding-would-swallow-text beg end))))
  20918. (org-with-limited-levels
  20919. (or (looking-at org-outline-regexp)
  20920. (re-search-forward org-outline-regexp-bol end t))
  20921. (while (and (< (point) end) (looking-at org-outline-regexp))
  20922. (outline-hide-subtree)
  20923. (org-cycle-show-empty-lines 'folded)
  20924. (condition-case nil
  20925. (outline-forward-same-level 1)
  20926. (error (goto-char end))))))
  20927. (when swallowp
  20928. (message
  20929. "Inserted text not folded because that would swallow text"))
  20930. (goto-char end)
  20931. (skip-chars-forward " \t\n\r")
  20932. (beginning-of-line 1)
  20933. (push-mark beg 'nomsg)))
  20934. ((and subtreep org-yank-adjusted-subtrees)
  20935. (let ((beg (point-at-bol)))
  20936. (org-paste-subtree nil nil 'for-yank)
  20937. (push-mark beg 'nomsg)))
  20938. (t
  20939. (call-interactively command))))))
  20940. (defun org-yank-folding-would-swallow-text (beg end)
  20941. "Would hide-subtree at BEG swallow any text after END?"
  20942. (let (level)
  20943. (org-with-limited-levels
  20944. (save-excursion
  20945. (goto-char beg)
  20946. (when (or (looking-at org-outline-regexp)
  20947. (re-search-forward org-outline-regexp-bol end t))
  20948. (setq level (org-outline-level)))
  20949. (goto-char end)
  20950. (skip-chars-forward " \t\r\n\v\f")
  20951. (not (or (eobp)
  20952. (and (bolp) (looking-at-p org-outline-regexp)
  20953. (<= (org-outline-level) level))))))))
  20954. (defun org-back-to-heading (&optional invisible-ok)
  20955. "Call `outline-back-to-heading', but provide a better error message."
  20956. (condition-case nil
  20957. (outline-back-to-heading invisible-ok)
  20958. (error (error "Before first headline at position %d in buffer %s"
  20959. (point) (current-buffer)))))
  20960. (defun org-before-first-heading-p ()
  20961. "Before first heading?"
  20962. (save-excursion
  20963. (end-of-line)
  20964. (null (re-search-backward org-outline-regexp-bol nil t))))
  20965. (defun org-at-heading-p (&optional ignored)
  20966. (outline-on-heading-p t))
  20967. (defun org-in-commented-heading-p (&optional no-inheritance)
  20968. "Non-nil if point is under a commented heading.
  20969. This function also checks ancestors of the current headline,
  20970. unless optional argument NO-INHERITANCE is non-nil."
  20971. (cond
  20972. ((org-before-first-heading-p) nil)
  20973. ((let ((headline (nth 4 (org-heading-components))))
  20974. (and headline
  20975. (let ((case-fold-search nil))
  20976. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  20977. headline)))))
  20978. (no-inheritance nil)
  20979. (t
  20980. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  20981. (defun org-at-comment-p nil
  20982. "Is cursor in a commented line?"
  20983. (save-excursion
  20984. (save-match-data
  20985. (beginning-of-line)
  20986. (looking-at "^[ \t]*# "))))
  20987. (defun org-at-drawer-p nil
  20988. "Is cursor at a drawer keyword?"
  20989. (save-excursion
  20990. (move-beginning-of-line 1)
  20991. (looking-at org-drawer-regexp)))
  20992. (defun org-at-block-p nil
  20993. "Is cursor at a block keyword?"
  20994. (save-excursion
  20995. (move-beginning-of-line 1)
  20996. (looking-at org-block-regexp)))
  20997. (defun org-point-at-end-of-empty-headline ()
  20998. "If point is at the end of an empty headline, return t, else nil.
  20999. If the heading only contains a TODO keyword, it is still still considered
  21000. empty."
  21001. (let ((case-fold-search nil))
  21002. (and (looking-at "[ \t]*$")
  21003. org-todo-line-regexp
  21004. (save-excursion
  21005. (beginning-of-line)
  21006. (looking-at org-todo-line-regexp)
  21007. (string= (match-string 3) "")))))
  21008. (defun org-at-heading-or-item-p ()
  21009. (or (org-at-heading-p) (org-at-item-p)))
  21010. (defun org-at-target-p ()
  21011. (or (org-in-regexp org-radio-target-regexp)
  21012. (org-in-regexp org-target-regexp)))
  21013. (defun org-up-heading-all (arg)
  21014. "Move to the heading line of which the present line is a subheading.
  21015. This function considers both visible and invisible heading lines.
  21016. With argument, move up ARG levels."
  21017. (outline-up-heading arg t))
  21018. (defun org-up-heading-safe ()
  21019. "Move to the heading line of which the present line is a subheading.
  21020. This version will not throw an error. It will return the level of the
  21021. headline found, or nil if no higher level is found.
  21022. Also, this function will be a lot faster than `outline-up-heading',
  21023. because it relies on stars being the outline starters. This can really
  21024. make a significant difference in outlines with very many siblings."
  21025. (when (ignore-errors (org-back-to-heading t))
  21026. (let ((level-up (1- (funcall outline-level))))
  21027. (and (> level-up 0)
  21028. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  21029. (funcall outline-level)))))
  21030. (defun org-first-sibling-p ()
  21031. "Is this heading the first child of its parents?"
  21032. (interactive)
  21033. (let ((re org-outline-regexp-bol)
  21034. level l)
  21035. (unless (org-at-heading-p t)
  21036. (user-error "Not at a heading"))
  21037. (setq level (funcall outline-level))
  21038. (save-excursion
  21039. (if (not (re-search-backward re nil t))
  21040. t
  21041. (setq l (funcall outline-level))
  21042. (< l level)))))
  21043. (defun org-goto-sibling (&optional previous)
  21044. "Goto the next sibling, even if it is invisible.
  21045. When PREVIOUS is set, go to the previous sibling instead. Returns t
  21046. when a sibling was found. When none is found, return nil and don't
  21047. move point."
  21048. (let ((fun (if previous 're-search-backward 're-search-forward))
  21049. (pos (point))
  21050. (re org-outline-regexp-bol)
  21051. level l)
  21052. (when (ignore-errors (org-back-to-heading t))
  21053. (setq level (funcall outline-level))
  21054. (catch 'exit
  21055. (or previous (forward-char 1))
  21056. (while (funcall fun re nil t)
  21057. (setq l (funcall outline-level))
  21058. (when (< l level) (goto-char pos) (throw 'exit nil))
  21059. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21060. (goto-char pos)
  21061. nil))))
  21062. (defun org-show-siblings ()
  21063. "Show all siblings of the current headline."
  21064. (save-excursion
  21065. (while (org-goto-sibling) (org-flag-heading nil)))
  21066. (save-excursion
  21067. (while (org-goto-sibling 'previous)
  21068. (org-flag-heading nil))))
  21069. (defun org-goto-first-child ()
  21070. "Goto the first child, even if it is invisible.
  21071. Return t when a child was found. Otherwise don't move point and
  21072. return nil."
  21073. (let (level (pos (point)) (re org-outline-regexp-bol))
  21074. (when (ignore-errors (org-back-to-heading t))
  21075. (setq level (outline-level))
  21076. (forward-char 1)
  21077. (if (and (re-search-forward re nil t) (> (outline-level) level))
  21078. (progn (goto-char (match-beginning 0)) t)
  21079. (goto-char pos) nil))))
  21080. (defun org-show-hidden-entry ()
  21081. "Show an entry where even the heading is hidden."
  21082. (save-excursion
  21083. (org-show-entry)))
  21084. (defun org-flag-heading (flag &optional entry)
  21085. "Flag the current heading. FLAG non-nil means make invisible.
  21086. When ENTRY is non-nil, show the entire entry."
  21087. (save-excursion
  21088. (org-back-to-heading t)
  21089. ;; Check if we should show the entire entry
  21090. (if (not entry)
  21091. (org-flag-region
  21092. (line-end-position 0) (line-end-position) flag 'outline)
  21093. (org-show-entry)
  21094. (save-excursion
  21095. (and (outline-next-heading)
  21096. (org-flag-heading nil))))))
  21097. (defun org-get-next-sibling ()
  21098. "Move to next heading of the same level, and return point.
  21099. If there is no such heading, return nil.
  21100. This is like outline-next-sibling, but invisible headings are ok."
  21101. (let ((level (funcall outline-level)))
  21102. (outline-next-heading)
  21103. (while (and (not (eobp)) (> (funcall outline-level) level))
  21104. (outline-next-heading))
  21105. (unless (or (eobp) (< (funcall outline-level) level))
  21106. (point))))
  21107. (defun org-get-last-sibling ()
  21108. "Move to previous heading of the same level, and return point.
  21109. If there is no such heading, return nil."
  21110. (let ((opoint (point))
  21111. (level (funcall outline-level)))
  21112. (outline-previous-heading)
  21113. (when (and (/= (point) opoint) (outline-on-heading-p t))
  21114. (while (and (> (funcall outline-level) level)
  21115. (not (bobp)))
  21116. (outline-previous-heading))
  21117. (unless (< (funcall outline-level) level)
  21118. (point)))))
  21119. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  21120. "Goto to the end of a subtree."
  21121. ;; This contains an exact copy of the original function, but it uses
  21122. ;; `org-back-to-heading', to make it work also in invisible
  21123. ;; trees. And is uses an invisible-ok argument.
  21124. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  21125. ;; Furthermore, when used inside Org, finding the end of a large subtree
  21126. ;; with many children and grandchildren etc, this can be much faster
  21127. ;; than the outline version.
  21128. (org-back-to-heading invisible-ok)
  21129. (let ((first t)
  21130. (level (funcall outline-level)))
  21131. (if (and (derived-mode-p 'org-mode) (< level 1000))
  21132. ;; A true heading (not a plain list item), in Org
  21133. ;; This means we can easily find the end by looking
  21134. ;; only for the right number of stars. Using a regexp to do
  21135. ;; this is so much faster than using a Lisp loop.
  21136. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  21137. (forward-char 1)
  21138. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  21139. ;; something else, do it the slow way
  21140. (while (and (not (eobp))
  21141. (or first (> (funcall outline-level) level)))
  21142. (setq first nil)
  21143. (outline-next-heading)))
  21144. (unless to-heading
  21145. (when (memq (preceding-char) '(?\n ?\^M))
  21146. ;; Go to end of line before heading
  21147. (forward-char -1)
  21148. (when (memq (preceding-char) '(?\n ?\^M))
  21149. ;; leave blank line before heading
  21150. (forward-char -1)))))
  21151. (point))
  21152. (defun org-end-of-meta-data (&optional full)
  21153. "Skip planning line and properties drawer in current entry.
  21154. When optional argument FULL is non-nil, also skip empty lines,
  21155. clocking lines and regular drawers at the beginning of the
  21156. entry."
  21157. (org-back-to-heading t)
  21158. (forward-line)
  21159. (when (looking-at-p org-planning-line-re) (forward-line))
  21160. (when (looking-at org-property-drawer-re)
  21161. (goto-char (match-end 0))
  21162. (forward-line))
  21163. (when (and full (not (org-at-heading-p)))
  21164. (catch 'exit
  21165. (let ((end (save-excursion (outline-next-heading) (point)))
  21166. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  21167. (while (not (eobp))
  21168. (cond ((looking-at-p org-drawer-regexp)
  21169. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21170. (forward-line)
  21171. (throw 'exit t)))
  21172. ((looking-at-p re) (forward-line))
  21173. (t (throw 'exit t))))))))
  21174. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  21175. "Move forward to the ARG'th subheading at same level as this one.
  21176. Stop at the first and last subheadings of a superior heading.
  21177. Normally this only looks at visible headings, but when INVISIBLE-OK is
  21178. non-nil it will also look at invisible ones."
  21179. (interactive "p")
  21180. (let ((backward? (and arg (< arg 0))))
  21181. (if (org-before-first-heading-p)
  21182. (if backward? (goto-char (point-min)) (outline-next-heading))
  21183. (org-back-to-heading invisible-ok)
  21184. (unless backward? (end-of-line)) ;do not match current headline
  21185. (let ((level (- (match-end 0) (match-beginning 0) 1))
  21186. (f (if backward? #'re-search-backward #'re-search-forward))
  21187. (count (if arg (abs arg) 1))
  21188. (result (point)))
  21189. (while (and (> count 0)
  21190. (funcall f org-outline-regexp-bol nil 'move))
  21191. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  21192. (cond ((< l level) (setq count 0))
  21193. ((and (= l level)
  21194. (or invisible-ok
  21195. (not (org-invisible-p
  21196. (line-beginning-position)))))
  21197. (cl-decf count)
  21198. (when (= l level) (setq result (point)))))))
  21199. (goto-char result))
  21200. (beginning-of-line))))
  21201. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  21202. "Move backward to the ARG'th subheading at same level as this one.
  21203. Stop at the first and last subheadings of a superior heading."
  21204. (interactive "p")
  21205. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  21206. (defun org-next-visible-heading (arg)
  21207. "Move to the next visible heading.
  21208. This function wraps `outline-next-visible-heading' with
  21209. `org-with-limited-levels' in order to skip over inline tasks and
  21210. respect customization of `org-odd-levels-only'."
  21211. (interactive "p")
  21212. (org-with-limited-levels
  21213. (outline-next-visible-heading arg)))
  21214. (defun org-previous-visible-heading (arg)
  21215. "Move to the previous visible heading.
  21216. This function wraps `outline-previous-visible-heading' with
  21217. `org-with-limited-levels' in order to skip over inline tasks and
  21218. respect customization of `org-odd-levels-only'."
  21219. (interactive "p")
  21220. (org-with-limited-levels
  21221. (outline-previous-visible-heading arg)))
  21222. (defun org-forward-paragraph ()
  21223. "Move forward to beginning of next paragraph or equivalent.
  21224. The function moves point to the beginning of the next visible
  21225. structural element, which can be a paragraph, a table, a list
  21226. item, etc. It also provides some special moves for convenience:
  21227. - On an affiliated keyword, jump to the beginning of the
  21228. relative element.
  21229. - On an item or a footnote definition, move to the second
  21230. element inside, if any.
  21231. - On a table or a property drawer, jump after it.
  21232. - On a verse or source block, stop after blank lines."
  21233. (interactive)
  21234. (unless (eobp)
  21235. (let* ((deactivate-mark nil)
  21236. (element (org-element-at-point))
  21237. (type (org-element-type element))
  21238. (post-affiliated (org-element-property :post-affiliated element))
  21239. (contents-begin (org-element-property :contents-begin element))
  21240. (contents-end (org-element-property :contents-end element))
  21241. (end (let ((end (org-element-property :end element)) (parent element))
  21242. (while (and (setq parent (org-element-property :parent parent))
  21243. (= (org-element-property :contents-end parent) end))
  21244. (setq end (org-element-property :end parent)))
  21245. end)))
  21246. (cond ((not element)
  21247. (skip-chars-forward " \r\t\n")
  21248. (or (eobp) (beginning-of-line)))
  21249. ;; On affiliated keywords, move to element's beginning.
  21250. ((< (point) post-affiliated)
  21251. (goto-char post-affiliated))
  21252. ;; At a table row, move to the end of the table. Similarly,
  21253. ;; at a node property, move to the end of the property
  21254. ;; drawer.
  21255. ((memq type '(node-property table-row))
  21256. (goto-char (org-element-property
  21257. :end (org-element-property :parent element))))
  21258. ((memq type '(property-drawer table)) (goto-char end))
  21259. ;; Consider blank lines as separators in verse and source
  21260. ;; blocks to ease editing.
  21261. ((memq type '(src-block verse-block))
  21262. (when (eq type 'src-block)
  21263. (setq contents-end
  21264. (save-excursion (goto-char end)
  21265. (skip-chars-backward " \r\t\n")
  21266. (line-beginning-position))))
  21267. (beginning-of-line)
  21268. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  21269. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  21270. (goto-char end)
  21271. (skip-chars-forward " \r\t\n")
  21272. (if (= (point) contents-end) (goto-char end)
  21273. (beginning-of-line))))
  21274. ;; With no contents, just skip element.
  21275. ((not contents-begin) (goto-char end))
  21276. ;; If contents are invisible, skip the element altogether.
  21277. ((org-invisible-p (line-end-position))
  21278. (cl-case type
  21279. (headline
  21280. (org-with-limited-levels (outline-next-visible-heading 1)))
  21281. ;; At a plain list, make sure we move to the next item
  21282. ;; instead of skipping the whole list.
  21283. (plain-list (forward-char)
  21284. (org-forward-paragraph))
  21285. (otherwise (goto-char end))))
  21286. ((>= (point) contents-end) (goto-char end))
  21287. ((>= (point) contents-begin)
  21288. ;; This can only happen on paragraphs and plain lists.
  21289. (cl-case type
  21290. (paragraph (goto-char end))
  21291. ;; At a plain list, try to move to second element in
  21292. ;; first item, if possible.
  21293. (plain-list (end-of-line)
  21294. (org-forward-paragraph))))
  21295. ;; When contents start on the middle of a line (e.g. in
  21296. ;; items and footnote definitions), try to reach first
  21297. ;; element starting after current line.
  21298. ((> (line-end-position) contents-begin)
  21299. (end-of-line)
  21300. (org-forward-paragraph))
  21301. (t (goto-char contents-begin))))))
  21302. (defun org-backward-paragraph ()
  21303. "Move backward to start of previous paragraph or equivalent.
  21304. The function moves point to the beginning of the current
  21305. structural element, which can be a paragraph, a table, a list
  21306. item, etc., or to the beginning of the previous visible one if
  21307. point is already there. It also provides some special moves for
  21308. convenience:
  21309. - On an affiliated keyword, jump to the first one.
  21310. - On a table or a property drawer, move to its beginning.
  21311. - On comment, example, export, src and verse blocks, stop
  21312. before blank lines."
  21313. (interactive)
  21314. (unless (bobp)
  21315. (let* ((deactivate-mark nil)
  21316. (element (org-element-at-point))
  21317. (type (org-element-type element))
  21318. (contents-end (org-element-property :contents-end element))
  21319. (post-affiliated (org-element-property :post-affiliated element))
  21320. (begin (org-element-property :begin element))
  21321. (special? ;blocks handled specially
  21322. (memq type '(comment-block example-block export-block src-block
  21323. verse-block)))
  21324. (contents-begin
  21325. (if special?
  21326. ;; These types have no proper contents. Fake line
  21327. ;; below the block opening line as contents beginning.
  21328. (save-excursion (goto-char begin) (line-beginning-position 2))
  21329. (org-element-property :contents-begin element))))
  21330. (cond
  21331. ((not element) (goto-char (point-min)))
  21332. ((= (point) begin)
  21333. (backward-char)
  21334. (org-backward-paragraph))
  21335. ((<= (point) post-affiliated) (goto-char begin))
  21336. ;; Special behavior: on a table or a property drawer, move to
  21337. ;; its beginning.
  21338. ((memq type '(node-property table-row))
  21339. (goto-char (org-element-property
  21340. :post-affiliated (org-element-property :parent element))))
  21341. (special?
  21342. (if (<= (point) contents-begin) (goto-char post-affiliated)
  21343. ;; Inside a verse block, see blank lines as paragraph
  21344. ;; separators.
  21345. (let ((origin (point)))
  21346. (skip-chars-backward " \r\t\n" contents-begin)
  21347. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  21348. (skip-chars-forward " \r\t\n" origin)
  21349. (if (= (point) origin) (goto-char contents-begin)
  21350. (beginning-of-line))))))
  21351. ((eq type 'paragraph) (goto-char contents-begin)
  21352. ;; When at first paragraph in an item or a footnote definition,
  21353. ;; move directly to beginning of line.
  21354. (let ((parent-contents
  21355. (org-element-property
  21356. :contents-begin (org-element-property :parent element))))
  21357. (when (and parent-contents (= parent-contents contents-begin))
  21358. (beginning-of-line))))
  21359. ;; At the end of a greater element, move to the beginning of
  21360. ;; the last element within.
  21361. ((and contents-end (>= (point) contents-end))
  21362. (goto-char (1- contents-end))
  21363. (org-backward-paragraph))
  21364. (t (goto-char (or post-affiliated begin))))
  21365. ;; Ensure we never leave point invisible.
  21366. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  21367. (defun org-forward-element ()
  21368. "Move forward by one element.
  21369. Move to the next element at the same level, when possible."
  21370. (interactive)
  21371. (cond ((eobp) (user-error "Cannot move further down"))
  21372. ((org-with-limited-levels (org-at-heading-p))
  21373. (let ((origin (point)))
  21374. (goto-char (org-end-of-subtree nil t))
  21375. (unless (org-with-limited-levels (org-at-heading-p))
  21376. (goto-char origin)
  21377. (user-error "Cannot move further down"))))
  21378. (t
  21379. (let* ((elem (org-element-at-point))
  21380. (end (org-element-property :end elem))
  21381. (parent (org-element-property :parent elem)))
  21382. (cond ((and parent (= (org-element-property :contents-end parent) end))
  21383. (goto-char (org-element-property :end parent)))
  21384. ((integer-or-marker-p end) (goto-char end))
  21385. (t (message "No element at point")))))))
  21386. (defun org-backward-element ()
  21387. "Move backward by one element.
  21388. Move to the previous element at the same level, when possible."
  21389. (interactive)
  21390. (cond ((bobp) (user-error "Cannot move further up"))
  21391. ((org-with-limited-levels (org-at-heading-p))
  21392. ;; At a headline, move to the previous one, if any, or stay
  21393. ;; here.
  21394. (let ((origin (point)))
  21395. (org-with-limited-levels (org-backward-heading-same-level 1))
  21396. ;; When current headline has no sibling above, move to its
  21397. ;; parent.
  21398. (when (= (point) origin)
  21399. (or (org-with-limited-levels (org-up-heading-safe))
  21400. (progn (goto-char origin)
  21401. (user-error "Cannot move further up"))))))
  21402. (t
  21403. (let* ((elem (org-element-at-point))
  21404. (beg (org-element-property :begin elem)))
  21405. (cond
  21406. ;; Move to beginning of current element if point isn't
  21407. ;; there already.
  21408. ((null beg) (message "No element at point"))
  21409. ((/= (point) beg) (goto-char beg))
  21410. (t (goto-char beg)
  21411. (skip-chars-backward " \r\t\n")
  21412. (unless (bobp)
  21413. (let ((prev (org-element-at-point)))
  21414. (goto-char (org-element-property :begin prev))
  21415. (while (and (setq prev (org-element-property :parent prev))
  21416. (<= (org-element-property :end prev) beg))
  21417. (goto-char (org-element-property :begin prev)))))))))))
  21418. (defun org-up-element ()
  21419. "Move to upper element."
  21420. (interactive)
  21421. (if (org-with-limited-levels (org-at-heading-p))
  21422. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  21423. (let* ((elem (org-element-at-point))
  21424. (parent (org-element-property :parent elem)))
  21425. (if parent (goto-char (org-element-property :begin parent))
  21426. (if (org-with-limited-levels (org-before-first-heading-p))
  21427. (user-error "No surrounding element")
  21428. (org-with-limited-levels (org-back-to-heading)))))))
  21429. (defun org-down-element ()
  21430. "Move to inner element."
  21431. (interactive)
  21432. (let ((element (org-element-at-point)))
  21433. (cond
  21434. ((memq (org-element-type element) '(plain-list table))
  21435. (goto-char (org-element-property :contents-begin element))
  21436. (forward-char))
  21437. ((memq (org-element-type element) org-element-greater-elements)
  21438. ;; If contents are hidden, first disclose them.
  21439. (when (org-invisible-p (line-end-position)) (org-cycle))
  21440. (goto-char (or (org-element-property :contents-begin element)
  21441. (user-error "No content for this element"))))
  21442. (t (user-error "No inner element")))))
  21443. (defun org-drag-element-backward ()
  21444. "Move backward element at point."
  21445. (interactive)
  21446. (let ((elem (or (org-element-at-point)
  21447. (user-error "No element at point"))))
  21448. (if (eq (org-element-type elem) 'headline)
  21449. ;; Preserve point when moving a whole tree, even if point was
  21450. ;; on blank lines below the headline.
  21451. (let ((offset (skip-chars-backward " \t\n")))
  21452. (unwind-protect (org-move-subtree-up)
  21453. (forward-char (- offset))))
  21454. (let ((prev-elem
  21455. (save-excursion
  21456. (goto-char (org-element-property :begin elem))
  21457. (skip-chars-backward " \r\t\n")
  21458. (unless (bobp)
  21459. (let* ((beg (org-element-property :begin elem))
  21460. (prev (org-element-at-point))
  21461. (up prev))
  21462. (while (and (setq up (org-element-property :parent up))
  21463. (<= (org-element-property :end up) beg))
  21464. (setq prev up))
  21465. prev)))))
  21466. ;; Error out if no previous element or previous element is
  21467. ;; a parent of the current one.
  21468. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  21469. (user-error "Cannot drag element backward")
  21470. (let ((pos (point)))
  21471. (org-element-swap-A-B prev-elem elem)
  21472. (goto-char (+ (org-element-property :begin prev-elem)
  21473. (- pos (org-element-property :begin elem))))))))))
  21474. (defun org-drag-element-forward ()
  21475. "Move forward element at point."
  21476. (interactive)
  21477. (let* ((pos (point))
  21478. (elem (or (org-element-at-point)
  21479. (user-error "No element at point"))))
  21480. (when (= (point-max) (org-element-property :end elem))
  21481. (user-error "Cannot drag element forward"))
  21482. (goto-char (org-element-property :end elem))
  21483. (let ((next-elem (org-element-at-point)))
  21484. (when (or (org-element-nested-p elem next-elem)
  21485. (and (eq (org-element-type next-elem) 'headline)
  21486. (not (eq (org-element-type elem) 'headline))))
  21487. (goto-char pos)
  21488. (user-error "Cannot drag element forward"))
  21489. ;; Compute new position of point: it's shifted by NEXT-ELEM
  21490. ;; body's length (without final blanks) and by the length of
  21491. ;; blanks between ELEM and NEXT-ELEM.
  21492. (let ((size-next (- (save-excursion
  21493. (goto-char (org-element-property :end next-elem))
  21494. (skip-chars-backward " \r\t\n")
  21495. (forward-line)
  21496. ;; Small correction if buffer doesn't end
  21497. ;; with a newline character.
  21498. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  21499. (org-element-property :begin next-elem)))
  21500. (size-blank (- (org-element-property :end elem)
  21501. (save-excursion
  21502. (goto-char (org-element-property :end elem))
  21503. (skip-chars-backward " \r\t\n")
  21504. (forward-line)
  21505. (point)))))
  21506. (org-element-swap-A-B elem next-elem)
  21507. (goto-char (+ pos size-next size-blank))))))
  21508. (defun org-drag-line-forward (arg)
  21509. "Drag the line at point ARG lines forward."
  21510. (interactive "p")
  21511. (dotimes (_ (abs arg))
  21512. (let ((c (current-column)))
  21513. (if (< 0 arg)
  21514. (progn
  21515. (beginning-of-line 2)
  21516. (transpose-lines 1)
  21517. (beginning-of-line 0))
  21518. (transpose-lines 1)
  21519. (beginning-of-line -1))
  21520. (org-move-to-column c))))
  21521. (defun org-drag-line-backward (arg)
  21522. "Drag the line at point ARG lines backward."
  21523. (interactive "p")
  21524. (org-drag-line-forward (- arg)))
  21525. (defun org-mark-element ()
  21526. "Put point at beginning of this element, mark at end.
  21527. Interactively, if this command is repeated or (in Transient Mark
  21528. mode) if the mark is active, it marks the next element after the
  21529. ones already marked."
  21530. (interactive)
  21531. (let (deactivate-mark)
  21532. (if (and (called-interactively-p 'any)
  21533. (or (and (eq last-command this-command) (mark t))
  21534. (and transient-mark-mode mark-active)))
  21535. (set-mark
  21536. (save-excursion
  21537. (goto-char (mark))
  21538. (goto-char (org-element-property :end (org-element-at-point)))))
  21539. (let ((element (org-element-at-point)))
  21540. (end-of-line)
  21541. (push-mark (org-element-property :end element) t t)
  21542. (goto-char (org-element-property :begin element))))))
  21543. (defun org-narrow-to-element ()
  21544. "Narrow buffer to current element."
  21545. (interactive)
  21546. (let ((elem (org-element-at-point)))
  21547. (cond
  21548. ((eq (car elem) 'headline)
  21549. (narrow-to-region
  21550. (org-element-property :begin elem)
  21551. (org-element-property :end elem)))
  21552. ((memq (car elem) org-element-greater-elements)
  21553. (narrow-to-region
  21554. (org-element-property :contents-begin elem)
  21555. (org-element-property :contents-end elem)))
  21556. (t
  21557. (narrow-to-region
  21558. (org-element-property :begin elem)
  21559. (org-element-property :end elem))))))
  21560. (defun org-transpose-element ()
  21561. "Transpose current and previous elements, keeping blank lines between.
  21562. Point is moved after both elements."
  21563. (interactive)
  21564. (org-skip-whitespace)
  21565. (let ((end (org-element-property :end (org-element-at-point))))
  21566. (org-drag-element-backward)
  21567. (goto-char end)))
  21568. (defun org-unindent-buffer ()
  21569. "Un-indent the visible part of the buffer.
  21570. Relative indentation (between items, inside blocks, etc.) isn't
  21571. modified."
  21572. (interactive)
  21573. (unless (eq major-mode 'org-mode)
  21574. (user-error "Cannot un-indent a buffer not in Org mode"))
  21575. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  21576. (unindent-tree
  21577. (lambda (contents)
  21578. (dolist (element (reverse contents))
  21579. (if (memq (org-element-type element) '(headline section))
  21580. (funcall unindent-tree (org-element-contents element))
  21581. (save-excursion
  21582. (save-restriction
  21583. (narrow-to-region
  21584. (org-element-property :begin element)
  21585. (org-element-property :end element))
  21586. (org-do-remove-indentation))))))))
  21587. (funcall unindent-tree (org-element-contents parse-tree))))
  21588. (defun org-make-options-regexp (kwds &optional extra)
  21589. "Make a regular expression for keyword lines.
  21590. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  21591. when non-nil, is a regexp matching keywords names."
  21592. (concat "^[ \t]*#\\+\\("
  21593. (regexp-opt kwds)
  21594. (and extra (concat (and kwds "\\|") extra))
  21595. "\\):[ \t]*\\(.*\\)"))
  21596. ;;; Finish up
  21597. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  21598. (lambda () (add-hook 'change-major-mode-hook
  21599. 'org-show-all 'append 'local)))
  21600. (provide 'org)
  21601. (run-hooks 'org-load-hook)
  21602. ;;; org.el ends here