org.el 894 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601
  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.12
  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. (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-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  105. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  106. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  107. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  108. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  109. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  110. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  111. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  112. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  113. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  114. (declare-function org-clock-update-time-maybe "org-clock" ())
  115. (declare-function org-clocking-buffer "org-clock" ())
  116. (declare-function org-clocktable-shift "org-clock" (dir n))
  117. (declare-function
  118. org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  119. (declare-function org-element-at-point "org-element" ())
  120. (declare-function org-element-cache-refresh "org-element" (pos))
  121. (declare-function org-element-cache-reset "org-element" (&optional all))
  122. (declare-function org-element-contents "org-element" (element))
  123. (declare-function org-element-context "org-element" (&optional element))
  124. (declare-function org-element-copy "org-element" (datum))
  125. (declare-function org-element-interpret-data "org-element" (data))
  126. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  127. (declare-function org-element-link-parser "org-element" ())
  128. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  129. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  130. (declare-function org-element-property "org-element" (property element))
  131. (declare-function org-element-put-property "org-element" (element property value))
  132. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  133. (declare-function org-element-type "org-element" (element))
  134. (declare-function org-element-update-syntax "org-element" ())
  135. (declare-function org-id-find-id-file "org-id" (id))
  136. (declare-function org-id-get-create "org-id" (&optional force))
  137. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  138. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  139. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  140. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  141. (declare-function org-table-align "org-table" ())
  142. (declare-function org-table-begin "org-table" (&optional table-type))
  143. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  144. (declare-function org-table-blank-field "org-table" ())
  145. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  146. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  147. (declare-function org-table-cut-region "org-table" (beg end))
  148. (declare-function org-table-edit-field "org-table" (arg))
  149. (declare-function org-table-end "org-table" (&optional table-type))
  150. (declare-function org-table-end-of-field "org-table" (&optional n))
  151. (declare-function org-table-insert-row "org-table" (&optional arg))
  152. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  153. (declare-function org-table-maybe-eval-formula "org-table" ())
  154. (declare-function org-table-maybe-recalculate-line "org-table" ())
  155. (declare-function org-table-next-row "org-table" ())
  156. (declare-function org-table-paste-rectangle "org-table" ())
  157. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  158. (declare-function
  159. org-table-sort-lines "org-table"
  160. (&optional with-case sorting-type getkey-func compare-func interactive?))
  161. (declare-function org-table-shrink "org-table" (&optional begin end))
  162. (declare-function org-table-toggle-column-width "org-table" (&optional arg))
  163. (declare-function org-table-wrap-region "org-table" (arg))
  164. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  165. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  166. (declare-function orgtbl-mode "org-table" (&optional arg))
  167. (declare-function org-export-get-backend "ox" (name))
  168. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  169. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  170. (defvar ffap-url-regexp)
  171. (defvar org-element-paragraph-separate)
  172. (defvar org-indent-indentation-per-level)
  173. ;; load languages based on value of `org-babel-load-languages'
  174. (defvar org-babel-load-languages)
  175. ;;;###autoload
  176. (defun org-babel-do-load-languages (sym value)
  177. "Load the languages defined in `org-babel-load-languages'."
  178. (set-default sym value)
  179. (dolist (pair org-babel-load-languages)
  180. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  181. (if active
  182. (require (intern (concat "ob-" lang)))
  183. (funcall 'fmakunbound
  184. (intern (concat "org-babel-execute:" lang)))
  185. (funcall 'fmakunbound
  186. (intern (concat "org-babel-expand-body:" lang)))))))
  187. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  188. ;;;###autoload
  189. (defun org-babel-load-file (file &optional compile)
  190. "Load Emacs Lisp source code blocks in the Org FILE.
  191. This function exports the source code using `org-babel-tangle'
  192. and then loads the resulting file using `load-file'. With prefix
  193. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  194. file to byte-code before it is loaded."
  195. (interactive "fFile to load: \nP")
  196. (let* ((age (lambda (file)
  197. (float-time
  198. (time-subtract (current-time)
  199. (nth 5 (or (file-attributes (file-truename file))
  200. (file-attributes file)))))))
  201. (base-name (file-name-sans-extension file))
  202. (exported-file (concat base-name ".el")))
  203. ;; tangle if the Org file is newer than the elisp file
  204. (unless (and (file-exists-p exported-file)
  205. (> (funcall age file) (funcall age exported-file)))
  206. ;; Tangle-file traversal returns reversed list of tangled files
  207. ;; and we want to evaluate the first target.
  208. (setq exported-file
  209. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  210. (message "%s %s"
  211. (if compile
  212. (progn (byte-compile-file exported-file 'load)
  213. "Compiled and loaded")
  214. (progn (load-file exported-file) "Loaded"))
  215. exported-file)))
  216. (defcustom org-babel-load-languages '((emacs-lisp . t))
  217. "Languages which can be evaluated in Org buffers.
  218. This list can be used to load support for any of the languages
  219. below, note that each language will depend on a different set of
  220. system executables and/or Emacs modes. When a language is
  221. \"loaded\", then code blocks in that language can be evaluated
  222. with `org-babel-execute-src-block' bound by default to C-c
  223. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  224. be set to remove code block evaluation from the C-c C-c
  225. keybinding. By default only Emacs Lisp (which has no
  226. requirements) is loaded."
  227. :group 'org-babel
  228. :set 'org-babel-do-load-languages
  229. :version "24.1"
  230. :type '(alist :tag "Babel Languages"
  231. :key-type
  232. (choice
  233. (const :tag "Awk" awk)
  234. (const :tag "C" C)
  235. (const :tag "R" R)
  236. (const :tag "Asymptote" asymptote)
  237. (const :tag "Calc" calc)
  238. (const :tag "Clojure" clojure)
  239. (const :tag "CSS" css)
  240. (const :tag "Ditaa" ditaa)
  241. (const :tag "Dot" dot)
  242. (const :tag "Ebnf2ps" ebnf2ps)
  243. (const :tag "Emacs Lisp" emacs-lisp)
  244. (const :tag "Forth" forth)
  245. (const :tag "Fortran" fortran)
  246. (const :tag "Gnuplot" gnuplot)
  247. (const :tag "Haskell" haskell)
  248. (const :tag "hledger" hledger)
  249. (const :tag "IO" io)
  250. (const :tag "J" J)
  251. (const :tag "Java" java)
  252. (const :tag "Javascript" js)
  253. (const :tag "LaTeX" latex)
  254. (const :tag "Ledger" ledger)
  255. (const :tag "Lilypond" lilypond)
  256. (const :tag "Lisp" lisp)
  257. (const :tag "Makefile" makefile)
  258. (const :tag "Maxima" maxima)
  259. (const :tag "Matlab" matlab)
  260. (const :tag "Mscgen" mscgen)
  261. (const :tag "Ocaml" ocaml)
  262. (const :tag "Octave" octave)
  263. (const :tag "Org" org)
  264. (const :tag "Perl" perl)
  265. (const :tag "Pico Lisp" picolisp)
  266. (const :tag "PlantUML" plantuml)
  267. (const :tag "Python" python)
  268. (const :tag "Ruby" ruby)
  269. (const :tag "Sass" sass)
  270. (const :tag "Scala" scala)
  271. (const :tag "Scheme" scheme)
  272. (const :tag "Screen" screen)
  273. (const :tag "Shell Script" shell)
  274. (const :tag "Shen" shen)
  275. (const :tag "Sql" sql)
  276. (const :tag "Sqlite" sqlite)
  277. (const :tag "Stan" stan)
  278. (const :tag "Vala" vala))
  279. :value-type (boolean :tag "Activate" :value t)))
  280. ;;;; Customization variables
  281. (defcustom org-clone-delete-id nil
  282. "Remove ID property of clones of a subtree.
  283. When non-nil, clones of a subtree don't inherit the ID property.
  284. Otherwise they inherit the ID property with a new unique
  285. identifier."
  286. :type 'boolean
  287. :version "24.1"
  288. :group 'org-id)
  289. ;;; Version
  290. (org-check-version)
  291. ;;;###autoload
  292. (defun org-version (&optional here full message)
  293. "Show the Org version.
  294. Interactively, or when MESSAGE is non-nil, show it in echo area.
  295. With prefix argument, or when HERE is non-nil, insert it at point.
  296. In non-interactive uses, a reduced version string is output unless
  297. FULL is given."
  298. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  299. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  300. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  301. (load-suffixes (list ".el"))
  302. (org-install-dir
  303. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  304. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  305. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  306. (let* ((load-suffixes save-load-suffixes)
  307. (release (org-release))
  308. (git-version (org-git-version))
  309. (version (format "Org mode version %s (%s @ %s)"
  310. release
  311. git-version
  312. (if org-install-dir
  313. (if (string= org-dir org-install-dir)
  314. org-install-dir
  315. (concat "mixed installation! "
  316. org-install-dir
  317. " and "
  318. org-dir))
  319. "org-loaddefs.el can not be found!")))
  320. (version1 (if full version release)))
  321. (when here (insert version1))
  322. (when message (message "%s" version1))
  323. version1)))
  324. (defconst org-version (org-version))
  325. ;;; Syntax Constants
  326. ;;;; Block
  327. (defconst org-block-regexp
  328. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  329. "Regular expression for hiding blocks.")
  330. (defconst org-dblock-start-re
  331. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  332. "Matches the start line of a dynamic block, with parameters.")
  333. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  334. "Matches the end of a dynamic block.")
  335. ;;;; Clock and Planning
  336. (defconst org-clock-string "CLOCK:"
  337. "String used as prefix for timestamps clocking work hours on an item.")
  338. (defvar org-closed-string "CLOSED:"
  339. "String used as the prefix for timestamps logging closing a TODO entry.")
  340. (defvar org-deadline-string "DEADLINE:"
  341. "String to mark deadline entries.
  342. \\<org-mode-map>
  343. A deadline is this string, followed by a time stamp. It must be
  344. a word, terminated by a colon. You can insert a schedule keyword
  345. and a timestamp with `\\[org-deadline]'.")
  346. (defvar org-scheduled-string "SCHEDULED:"
  347. "String to mark scheduled TODO entries.
  348. \\<org-mode-map>
  349. A schedule is this string, followed by a time stamp. It must be
  350. a word, terminated by a colon. You can insert a schedule keyword
  351. and a timestamp with `\\[org-schedule]'.")
  352. (defconst org-ds-keyword-length
  353. (+ 2
  354. (apply #'max
  355. (mapcar #'length
  356. (list org-deadline-string org-scheduled-string
  357. org-clock-string org-closed-string))))
  358. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  359. (defconst org-planning-line-re
  360. (concat "^[ \t]*"
  361. (regexp-opt
  362. (list org-closed-string org-deadline-string org-scheduled-string)
  363. t))
  364. "Matches a line with planning info.
  365. Matched keyword is in group 1.")
  366. (defconst org-clock-line-re
  367. (concat "^[ \t]*" org-clock-string)
  368. "Matches a line with clock info.")
  369. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  370. "Matches the DEADLINE keyword.")
  371. (defconst org-deadline-time-regexp
  372. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  373. "Matches the DEADLINE keyword together with a time stamp.")
  374. (defconst org-deadline-time-hour-regexp
  375. (concat "\\<" org-deadline-string
  376. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  377. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  378. (defconst org-deadline-line-regexp
  379. (concat "\\<\\(" org-deadline-string "\\).*")
  380. "Matches the DEADLINE keyword and the rest of the line.")
  381. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  382. "Matches the SCHEDULED keyword.")
  383. (defconst org-scheduled-time-regexp
  384. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  385. "Matches the SCHEDULED keyword together with a time stamp.")
  386. (defconst org-scheduled-time-hour-regexp
  387. (concat "\\<" org-scheduled-string
  388. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  389. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  390. (defconst org-closed-time-regexp
  391. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  392. "Matches the CLOSED keyword together with a time stamp.")
  393. (defconst org-keyword-time-regexp
  394. (concat "\\<"
  395. (regexp-opt
  396. (list org-scheduled-string org-deadline-string org-closed-string
  397. org-clock-string)
  398. t)
  399. " *[[<]\\([^]>]+\\)[]>]")
  400. "Matches any of the 4 keywords, together with the time stamp.")
  401. (defconst org-keyword-time-not-clock-regexp
  402. (concat
  403. "\\<"
  404. (regexp-opt
  405. (list org-scheduled-string org-deadline-string org-closed-string) t)
  406. " *[[<]\\([^]>]+\\)[]>]")
  407. "Matches any of the 3 keywords, together with the time stamp.")
  408. (defconst org-maybe-keyword-time-regexp
  409. (concat "\\(\\<"
  410. (regexp-opt
  411. (list org-scheduled-string org-deadline-string org-closed-string
  412. org-clock-string)
  413. t)
  414. "\\)?"
  415. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  416. "\\|"
  417. "<%%([^\r\n>]*>\\)")
  418. "Matches a timestamp, possibly preceded by a keyword.")
  419. (defconst org-all-time-keywords
  420. (mapcar (lambda (w) (substring w 0 -1))
  421. (list org-scheduled-string org-deadline-string
  422. org-clock-string org-closed-string))
  423. "List of time keywords.")
  424. ;;;; Drawer
  425. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  426. "Matches first or last line of a hidden block.
  427. Group 1 contains drawer's name or \"END\".")
  428. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  429. "Regular expression matching the first line of a property drawer.")
  430. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  431. "Regular expression matching the last line of a property drawer.")
  432. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  433. "Regular expression matching the first line of a clock drawer.")
  434. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  435. "Regular expression matching the last line of a clock drawer.")
  436. (defconst org-property-drawer-re
  437. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  438. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  439. "[ \t]*:END:[ \t]*$")
  440. "Matches an entire property drawer.")
  441. (defconst org-clock-drawer-re
  442. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  443. org-clock-drawer-end-re "\\)\n?")
  444. "Matches an entire clock drawer.")
  445. ;;;; Headline
  446. (defconst org-heading-keyword-regexp-format
  447. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  448. "Printf format for a regexp matching a headline with some keyword.
  449. This regexp will match the headline of any node which has the
  450. exact keyword that is put into the format. The keyword isn't in
  451. any group by default, but the stars and the body are.")
  452. (defconst org-heading-keyword-maybe-regexp-format
  453. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  454. "Printf format for a regexp matching a headline, possibly with some keyword.
  455. This regexp can match any headline with the specified keyword, or
  456. without a keyword. The keyword isn't in any group by default,
  457. but the stars and the body are.")
  458. (defconst org-archive-tag "ARCHIVE"
  459. "The tag that marks a subtree as archived.
  460. An archived subtree does not open during visibility cycling, and does
  461. not contribute to the agenda listings.")
  462. (defconst org-tag-re "[[:alnum:]_@#%]+"
  463. "Regexp matching a single tag.")
  464. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  465. "Regexp matching the tag group at the end of a line, with leading spaces.
  466. Tags are stored in match group 1. Match group 2 stores the tags
  467. without the enclosing colons.")
  468. (defconst org-tag-line-re
  469. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  470. "Regexp matching tags in a headline.
  471. Tags are stored in match group 1. Match group 2 stores the tags
  472. without the enclosing colons.")
  473. (eval-and-compile
  474. (defconst org-comment-string "COMMENT"
  475. "Entries starting with this keyword will never be exported.
  476. \\<org-mode-map>
  477. An entry can be toggled between COMMENT and normal with
  478. `\\[org-toggle-comment]'."))
  479. ;;;; LaTeX Environments and Fragments
  480. (defconst org-latex-regexps
  481. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  482. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  483. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  484. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  485. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  486. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  487. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  488. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  489. "Regular expressions for matching embedded LaTeX.")
  490. ;;;; Node Property
  491. (defconst org-effort-property "Effort"
  492. "The property that is being used to keep track of effort estimates.
  493. Effort estimates given in this property need to have the format H:MM.")
  494. ;;;; Table
  495. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  496. "Detect an org-type or table-type table.")
  497. (defconst org-table-line-regexp "^[ \t]*|"
  498. "Detect an org-type table line.")
  499. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  500. "Detect an org-type table line.")
  501. (defconst org-table-hline-regexp "^[ \t]*|-"
  502. "Detect an org-type table hline.")
  503. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  504. "Detect a table-type table hline.")
  505. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  506. "Detect the first line outside a table when searching from within it.
  507. This works for both table types.")
  508. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  509. "Detect a #+TBLFM line.")
  510. ;;;; Timestamp
  511. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  512. "Regular expression for fast time stamp matching.")
  513. (defconst org-ts-regexp-inactive
  514. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  515. "Regular expression for fast inactive time stamp matching.")
  516. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  517. "Regular expression for fast time stamp matching.")
  518. (defconst org-ts-regexp0
  519. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  520. "Regular expression matching time strings for analysis.
  521. This one does not require the space after the date, so it can be used
  522. on a string that terminates immediately after the date.")
  523. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  524. "Regular expression matching time strings for analysis.")
  525. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  526. "Regular expression matching time stamps, with groups.")
  527. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  528. "Regular expression matching time stamps (also [..]), with groups.")
  529. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  530. "Regular expression matching a time stamp range.")
  531. (defconst org-tr-regexp-both
  532. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  533. "Regular expression matching a time stamp range.")
  534. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  535. org-ts-regexp "\\)?")
  536. "Regular expression matching a time stamp or time stamp range.")
  537. (defconst org-tsr-regexp-both
  538. (concat org-ts-regexp-both "\\(--?-?"
  539. org-ts-regexp-both "\\)?")
  540. "Regular expression matching a time stamp or time stamp range.
  541. The time stamps may be either active or inactive.")
  542. (defconst org-repeat-re
  543. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  544. "Regular expression for specifying repeated events.
  545. After a match, group 1 contains the repeat expression.")
  546. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  547. "Formats for `format-time-string' which are used for time stamps.")
  548. ;;; The custom variables
  549. (defgroup org nil
  550. "Outline-based notes management and organizer."
  551. :tag "Org"
  552. :group 'outlines
  553. :group 'calendar)
  554. (defcustom org-mode-hook nil
  555. "Mode hook for Org mode, run after the mode was turned on."
  556. :group 'org
  557. :type 'hook)
  558. (defcustom org-load-hook nil
  559. "Hook that is run after org.el has been loaded."
  560. :group 'org
  561. :type 'hook)
  562. (defcustom org-log-buffer-setup-hook nil
  563. "Hook that is run after an Org log buffer is created."
  564. :group 'org
  565. :version "24.1"
  566. :type 'hook)
  567. (defvar org-modules) ; defined below
  568. (defvar org-modules-loaded nil
  569. "Have the modules been loaded already?")
  570. (defun org-load-modules-maybe (&optional force)
  571. "Load all extensions listed in `org-modules'."
  572. (when (or force (not org-modules-loaded))
  573. (dolist (ext org-modules)
  574. (condition-case nil (require ext)
  575. (error (message "Problems while trying to load feature `%s'" ext))))
  576. (setq org-modules-loaded t)))
  577. (defun org-set-modules (var value)
  578. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  579. (set var value)
  580. (when (featurep 'org)
  581. (org-load-modules-maybe 'force)
  582. (org-element-cache-reset 'all)))
  583. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail org-tempo org-eww)
  584. "Modules that should always be loaded together with org.el.
  585. If a description starts with <C>, the file is not part of Emacs
  586. and loading it will require that you have downloaded and properly
  587. installed the Org mode distribution.
  588. You can also use this system to load external packages (i.e. neither Org
  589. core modules, nor modules from the CONTRIB directory). Just add symbols
  590. to the end of the list. If the package is called org-xyz.el, then you need
  591. to add the symbol `xyz', and the package must have a call to:
  592. (provide \\='org-xyz)
  593. For export specific modules, see also `org-export-backends'."
  594. :group 'org
  595. :set 'org-set-modules
  596. :version "26.1"
  597. :package-version '(Org . "9.2")
  598. :type
  599. '(set :greedy t
  600. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  601. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  602. (const :tag " crypt: Encryption of subtrees" org-crypt)
  603. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  604. (const :tag " docview: Links to doc-view buffers" org-docview)
  605. (const :tag " eww: Store link to url of eww" org-eww)
  606. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  607. (const :tag " habit: Track your consistency with habits" org-habit)
  608. (const :tag " id: Global IDs for identifying entries" org-id)
  609. (const :tag " info: Links to Info nodes" org-info)
  610. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  611. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  612. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  613. (const :tag " mouse: Additional mouse support" org-mouse)
  614. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  615. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  616. (const :tag " tempo: Fast completion for structures" org-tempo)
  617. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  618. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  619. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  620. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  621. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  622. (const :tag "C collector: Collect properties into tables" org-collector)
  623. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  624. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  625. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  626. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  627. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  628. (const :tag "C eval: Include command output as text" org-eval)
  629. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  630. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  631. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  632. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  633. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  634. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  635. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  636. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  637. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  638. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  639. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  640. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  641. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  642. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  643. (const :tag "C registry: A registry for Org links" org-registry)
  644. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  645. (const :tag "C secretary: Team management with Org" org-secretary)
  646. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  647. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  648. (const :tag "C track: Keep up with Org mode development" org-track)
  649. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  650. (const :tag "C vm: Links to VM folders/messages" org-vm)
  651. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  652. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  653. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  654. (defvar org-export-registered-backends) ; From ox.el.
  655. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  656. (declare-function org-export-backend-name "ox" (backend) t)
  657. (defcustom org-export-backends '(ascii html icalendar latex odt)
  658. "List of export back-ends that should be always available.
  659. If a description starts with <C>, the file is not part of Emacs
  660. and loading it will require that you have downloaded and properly
  661. installed the Org mode distribution.
  662. Unlike to `org-modules', libraries in this list will not be
  663. loaded along with Org, but only once the export framework is
  664. needed.
  665. This variable needs to be set before org.el is loaded. If you
  666. need to make a change while Emacs is running, use the customize
  667. interface or run the following code, where VAL stands for the new
  668. value of the variable, after updating it:
  669. (progn
  670. (setq org-export-registered-backends
  671. (cl-remove-if-not
  672. (lambda (backend)
  673. (let ((name (org-export-backend-name backend)))
  674. (or (memq name val)
  675. (catch \\='parentp
  676. (dolist (b val)
  677. (and (org-export-derived-backend-p b name)
  678. (throw \\='parentp t)))))))
  679. org-export-registered-backends))
  680. (let ((new-list (mapcar #\\='org-export-backend-name
  681. org-export-registered-backends)))
  682. (dolist (backend val)
  683. (cond
  684. ((not (load (format \"ox-%s\" backend) t t))
  685. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  686. backend))
  687. ((not (memq backend new-list)) (push backend new-list))))
  688. (set-default \\='org-export-backends new-list)))
  689. Adding a back-end to this list will also pull the back-end it
  690. depends on, if any."
  691. :group 'org
  692. :group 'org-export
  693. :version "26.1"
  694. :package-version '(Org . "9.0")
  695. :initialize 'custom-initialize-set
  696. :set (lambda (var val)
  697. (if (not (featurep 'ox)) (set-default var val)
  698. ;; Any back-end not required anymore (not present in VAL and not
  699. ;; a parent of any back-end in the new value) is removed from the
  700. ;; list of registered back-ends.
  701. (setq org-export-registered-backends
  702. (cl-remove-if-not
  703. (lambda (backend)
  704. (let ((name (org-export-backend-name backend)))
  705. (or (memq name val)
  706. (catch 'parentp
  707. (dolist (b val)
  708. (and (org-export-derived-backend-p b name)
  709. (throw 'parentp t)))))))
  710. org-export-registered-backends))
  711. ;; Now build NEW-LIST of both new back-ends and required
  712. ;; parents.
  713. (let ((new-list (mapcar #'org-export-backend-name
  714. org-export-registered-backends)))
  715. (dolist (backend val)
  716. (cond
  717. ((not (load (format "ox-%s" backend) t t))
  718. (message "Problems while trying to load export back-end `%s'"
  719. backend))
  720. ((not (memq backend new-list)) (push backend new-list))))
  721. ;; Set VAR to that list with fixed dependencies.
  722. (set-default var new-list))))
  723. :type '(set :greedy t
  724. (const :tag " ascii Export buffer to ASCII format" ascii)
  725. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  726. (const :tag " html Export buffer to HTML format" html)
  727. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  728. (const :tag " latex Export buffer to LaTeX format" latex)
  729. (const :tag " man Export buffer to MAN format" man)
  730. (const :tag " md Export buffer to Markdown format" md)
  731. (const :tag " odt Export buffer to ODT format" odt)
  732. (const :tag " org Export buffer to Org format" org)
  733. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  734. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  735. (const :tag "C deck Export buffer to deck.js presentations" deck)
  736. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  737. (const :tag "C groff Export buffer to Groff format" groff)
  738. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  739. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  740. (const :tag "C s5 Export buffer to s5 presentations" s5)
  741. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  742. (eval-after-load 'ox
  743. '(dolist (backend org-export-backends)
  744. (condition-case nil (require (intern (format "ox-%s" backend)))
  745. (error (message "Problems while trying to load export back-end `%s'"
  746. backend)))))
  747. (defcustom org-support-shift-select nil
  748. "Non-nil means make shift-cursor commands select text when possible.
  749. \\<org-mode-map>\
  750. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  751. start selecting a region, or enlarge regions started in this way.
  752. In Org mode, in special contexts, these same keys are used for
  753. other purposes, important enough to compete with shift selection.
  754. Org tries to balance these needs by supporting `shift-select-mode'
  755. outside these special contexts, under control of this variable.
  756. The default of this variable is nil, to avoid confusing behavior. Shifted
  757. cursor keys will then execute Org commands in the following contexts:
  758. - on a headline, changing TODO state (left/right) and priority (up/down)
  759. - on a time stamp, changing the time
  760. - in a plain list item, changing the bullet type
  761. - in a property definition line, switching between allowed values
  762. - in the BEGIN line of a clock table (changing the time block).
  763. Outside these contexts, the commands will throw an error.
  764. When this variable is t and the cursor is not in a special
  765. context, Org mode will support shift-selection for making and
  766. enlarging regions. To make this more effective, the bullet
  767. cycling will no longer happen anywhere in an item line, but only
  768. if the cursor is exactly on the bullet.
  769. If you set this variable to the symbol `always', then the keys
  770. will not be special in headlines, property lines, and item lines,
  771. to make shift selection work there as well. If this is what you
  772. want, you can use the following alternative commands:
  773. `\\[org-todo]' and `\\[org-priority]' \
  774. to change TODO state and priority,
  775. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  776. can be used to switch TODO sets,
  777. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  778. and properties can be edited by hand or in column view.
  779. However, when the cursor is on a timestamp, shift-cursor commands
  780. will still edit the time stamp - this is just too good to give up."
  781. :group 'org
  782. :type '(choice
  783. (const :tag "Never" nil)
  784. (const :tag "When outside special context" t)
  785. (const :tag "Everywhere except timestamps" always)))
  786. (defcustom org-loop-over-headlines-in-active-region nil
  787. "Shall some commands act upon headlines in the active region?
  788. When set to t, some commands will be performed in all headlines
  789. within the active region.
  790. When set to `start-level', some commands will be performed in all
  791. headlines within the active region, provided that these headlines
  792. are of the same level than the first one.
  793. When set to a string, those commands will be performed on the
  794. matching headlines within the active region. Such string must be
  795. a tags/property/todo match as it is used in the agenda tags view.
  796. The list of commands is: `org-schedule', `org-deadline',
  797. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  798. `org-archive-to-archive-sibling'. The archiving commands skip
  799. already archived entries."
  800. :type '(choice (const :tag "Don't loop" nil)
  801. (const :tag "All headlines in active region" t)
  802. (const :tag "In active region, headlines at the same level than the first one" start-level)
  803. (string :tag "Tags/Property/Todo matcher"))
  804. :version "24.1"
  805. :group 'org-todo
  806. :group 'org-archive)
  807. (defcustom org-startup-folded t
  808. "Non-nil means entering Org mode will switch to OVERVIEW.
  809. This can also be configured on a per-file basis by adding one of
  810. the following lines anywhere in the buffer:
  811. #+STARTUP: fold (or `overview', this is equivalent)
  812. #+STARTUP: nofold (or `showall', this is equivalent)
  813. #+STARTUP: content
  814. #+STARTUP: showeverything
  815. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  816. to ignore this option when Org opens agenda files for the first
  817. time."
  818. :group 'org-startup
  819. :type '(choice
  820. (const :tag "nofold: show all" nil)
  821. (const :tag "fold: overview" t)
  822. (const :tag "content: all headlines" content)
  823. (const :tag "show everything, even drawers" showeverything)))
  824. (defcustom org-startup-truncated t
  825. "Non-nil means entering Org mode will set `truncate-lines'.
  826. This is useful since some lines containing links can be very long and
  827. uninteresting. Also tables look terrible when wrapped.
  828. The variable `org-startup-truncated' allows to configure
  829. truncation for Org mode different to the other modes that use the
  830. variable `truncate-lines' and as a shortcut instead of putting
  831. the variable `truncate-lines' into the `org-mode-hook'. If one
  832. wants to configure truncation for Org mode not statically but
  833. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  834. the variable `truncate-lines' has to be used because in such a
  835. case it is too late to set the variable `org-startup-truncated'."
  836. :group 'org-startup
  837. :type 'boolean)
  838. (defcustom org-startup-indented nil
  839. "Non-nil means turn on `org-indent-mode' on startup.
  840. This can also be configured on a per-file basis by adding one of
  841. the following lines anywhere in the buffer:
  842. #+STARTUP: indent
  843. #+STARTUP: noindent"
  844. :group 'org-structure
  845. :type '(choice
  846. (const :tag "Not" nil)
  847. (const :tag "Globally (slow on startup in large files)" t)))
  848. (defcustom org-use-sub-superscripts t
  849. "Non-nil means interpret \"_\" and \"^\" for display.
  850. If you want to control how Org exports those characters, see
  851. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  852. used to be an alias for `org-export-with-sub-superscripts' in
  853. Org <8.0, it is not anymore.
  854. When this option is turned on, you can use TeX-like syntax for
  855. sub- and superscripts within the buffer. Several characters after
  856. \"_\" or \"^\" will be considered as a single item - so grouping
  857. with {} is normally not needed. For example, the following things
  858. will be parsed as single sub- or superscripts:
  859. 10^24 or 10^tau several digits will be considered 1 item.
  860. 10^-12 or 10^-tau a leading sign with digits or a word
  861. x^2-y^3 will be read as x^2 - y^3, because items are
  862. terminated by almost any nonword/nondigit char.
  863. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  864. Still, ambiguity is possible. So when in doubt, use {} to enclose
  865. the sub/superscript. If you set this variable to the symbol `{}',
  866. the braces are *required* in order to trigger interpretations as
  867. sub/superscript. This can be helpful in documents that need \"_\"
  868. frequently in plain text."
  869. :group 'org-startup
  870. :version "24.4"
  871. :package-version '(Org . "8.0")
  872. :type '(choice
  873. (const :tag "Always interpret" t)
  874. (const :tag "Only with braces" {})
  875. (const :tag "Never interpret" nil)))
  876. (defcustom org-startup-with-beamer-mode nil
  877. "Non-nil means turn on `org-beamer-mode' on startup.
  878. This can also be configured on a per-file basis by adding one of
  879. the following lines anywhere in the buffer:
  880. #+STARTUP: beamer"
  881. :group 'org-startup
  882. :version "24.1"
  883. :type 'boolean)
  884. (defcustom org-startup-align-all-tables nil
  885. "Non-nil means align all tables when visiting a file.
  886. This can also be configured on a per-file basis by adding one of
  887. the following lines anywhere in the buffer:
  888. #+STARTUP: align
  889. #+STARTUP: noalign"
  890. :group 'org-startup
  891. :type 'boolean)
  892. (defcustom org-startup-shrink-all-tables nil
  893. "Non-nil means shrink all table columns with a width cookie.
  894. This can also be configured on a per-file basis by adding one of
  895. the following lines anywhere in the buffer:
  896. #+STARTUP: shrink"
  897. :group 'org-startup
  898. :type 'boolean
  899. :version "27.1"
  900. :package-version '(Org . "9.2")
  901. :safe #'booleanp)
  902. (defcustom org-startup-with-inline-images nil
  903. "Non-nil means show inline images when loading a new Org file.
  904. This can also be configured on a per-file basis by adding one of
  905. the following lines anywhere in the buffer:
  906. #+STARTUP: inlineimages
  907. #+STARTUP: noinlineimages"
  908. :group 'org-startup
  909. :version "24.1"
  910. :type 'boolean)
  911. (defcustom org-startup-with-latex-preview nil
  912. "Non-nil means preview LaTeX fragments when loading a new Org file.
  913. This can also be configured on a per-file basis by adding one of
  914. the following lines anywhere in the buffer:
  915. #+STARTUP: latexpreview
  916. #+STARTUP: nolatexpreview"
  917. :group 'org-startup
  918. :version "24.4"
  919. :package-version '(Org . "8.0")
  920. :type 'boolean)
  921. (defcustom org-insert-mode-line-in-empty-file nil
  922. "Non-nil means insert the first line setting Org mode in empty files.
  923. When the function `org-mode' is called interactively in an empty file, this
  924. normally means that the file name does not automatically trigger Org mode.
  925. To ensure that the file will always be in Org mode in the future, a
  926. line enforcing Org mode will be inserted into the buffer, if this option
  927. has been set."
  928. :group 'org-startup
  929. :type 'boolean)
  930. (defcustom org-replace-disputed-keys nil
  931. "Non-nil means use alternative key bindings for some keys.
  932. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  933. These keys are also used by other packages like Shift Select mode,
  934. CUA mode or Windmove. If you want to use Org mode together with
  935. one of these other modes, or more generally if you would like to
  936. move some Org mode commands to other keys, set this variable and
  937. configure the keys with the variable `org-disputed-keys'.
  938. This option is only relevant at load-time of Org mode, and must be set
  939. *before* org.el is loaded. Changing it requires a restart of Emacs to
  940. become effective."
  941. :group 'org-startup
  942. :type 'boolean)
  943. (defcustom org-use-extra-keys nil
  944. "Non-nil means use extra key sequence definitions for certain commands.
  945. This happens automatically if `window-system' is nil. This
  946. variable lets you do the same manually. You must set it before
  947. loading Org."
  948. :group 'org-startup
  949. :type 'boolean)
  950. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  951. (defcustom org-disputed-keys
  952. '(([(shift up)] . [(meta p)])
  953. ([(shift down)] . [(meta n)])
  954. ([(shift left)] . [(meta -)])
  955. ([(shift right)] . [(meta +)])
  956. ([(control shift right)] . [(meta shift +)])
  957. ([(control shift left)] . [(meta shift -)]))
  958. "Keys for which Org mode and other modes compete.
  959. This is an alist, cars are the default keys, second element specifies
  960. the alternative to use when `org-replace-disputed-keys' is t.
  961. Keys can be specified in any syntax supported by `define-key'.
  962. The value of this option takes effect only at Org mode startup,
  963. therefore you'll have to restart Emacs to apply it after changing."
  964. :group 'org-startup
  965. :type 'alist)
  966. (defun org-key (key)
  967. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  968. Or return the original if not disputed."
  969. (when org-replace-disputed-keys
  970. (let* ((nkey (key-description key))
  971. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  972. org-disputed-keys)))
  973. (setq key (if x (cdr x) key))))
  974. key)
  975. (defun org-defkey (keymap key def)
  976. "Define a key, possibly translated, as returned by `org-key'."
  977. (define-key keymap (org-key key) def))
  978. (defcustom org-ellipsis nil
  979. "The ellipsis to use in the Org mode outline.
  980. When nil, just use the standard three dots. When a non-empty string,
  981. use that string instead.
  982. The change affects only Org mode (which will then use its own display table).
  983. Changing this requires executing `\\[org-mode]' in a buffer to become
  984. effective."
  985. :group 'org-startup
  986. :type '(choice (const :tag "Default" nil)
  987. (string :tag "String" :value "...#"))
  988. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  989. (defvar org-display-table nil
  990. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  991. (defgroup org-keywords nil
  992. "Keywords in Org mode."
  993. :tag "Org Keywords"
  994. :group 'org)
  995. (defcustom org-closed-keep-when-no-todo nil
  996. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  997. :group 'org-todo
  998. :group 'org-keywords
  999. :version "24.4"
  1000. :package-version '(Org . "8.0")
  1001. :type 'boolean)
  1002. (defgroup org-structure nil
  1003. "Options concerning the general structure of Org files."
  1004. :tag "Org Structure"
  1005. :group 'org)
  1006. (defgroup org-reveal-location nil
  1007. "Options about how to make context of a location visible."
  1008. :tag "Org Reveal Location"
  1009. :group 'org-structure)
  1010. (defcustom org-show-context-detail '((agenda . local)
  1011. (bookmark-jump . lineage)
  1012. (isearch . lineage)
  1013. (default . ancestors))
  1014. "Alist between context and visibility span when revealing a location.
  1015. \\<org-mode-map>Some actions may move point into invisible
  1016. locations. As a consequence, Org always expose a neighborhood
  1017. around point. How much is shown depends on the initial action,
  1018. or context. Valid contexts are
  1019. agenda when exposing an entry from the agenda
  1020. org-goto when using the command `org-goto' (`\\[org-goto]')
  1021. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1022. tags-tree when constructing a sparse tree based on tags matches
  1023. link-search when exposing search matches associated with a link
  1024. mark-goto when exposing the jump goal of a mark
  1025. bookmark-jump when exposing a bookmark location
  1026. isearch when exiting from an incremental search
  1027. default default for all contexts not set explicitly
  1028. Allowed visibility spans are
  1029. minimal show current headline; if point is not on headline,
  1030. also show entry
  1031. local show current headline, entry and next headline
  1032. ancestors show current headline and its direct ancestors; if
  1033. point is not on headline, also show entry
  1034. lineage show current headline, its direct ancestors and all
  1035. their children; if point is not on headline, also show
  1036. entry and first child
  1037. tree show current headline, its direct ancestors and all
  1038. their children; if point is not on headline, also show
  1039. entry and all children
  1040. canonical show current headline, its direct ancestors along with
  1041. their entries and children; if point is not located on
  1042. the headline, also show current entry and all children
  1043. As special cases, a nil or t value means show all contexts in
  1044. `minimal' or `canonical' view, respectively.
  1045. Some views can make displayed information very compact, but also
  1046. make it harder to edit the location of the match. In such
  1047. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1048. more context."
  1049. :group 'org-reveal-location
  1050. :version "26.1"
  1051. :package-version '(Org . "9.0")
  1052. :type '(choice
  1053. (const :tag "Canonical" t)
  1054. (const :tag "Minimal" nil)
  1055. (repeat :greedy t :tag "Individual contexts"
  1056. (cons
  1057. (choice :tag "Context"
  1058. (const agenda)
  1059. (const org-goto)
  1060. (const occur-tree)
  1061. (const tags-tree)
  1062. (const link-search)
  1063. (const mark-goto)
  1064. (const bookmark-jump)
  1065. (const isearch)
  1066. (const default))
  1067. (choice :tag "Detail level"
  1068. (const minimal)
  1069. (const local)
  1070. (const ancestors)
  1071. (const lineage)
  1072. (const tree)
  1073. (const canonical))))))
  1074. (defcustom org-indirect-buffer-display 'other-window
  1075. "How should indirect tree buffers be displayed?
  1076. This applies to indirect buffers created with the commands
  1077. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1078. Valid values are:
  1079. current-window Display in the current window
  1080. other-window Just display in another window.
  1081. dedicated-frame Create one new frame, and re-use it each time.
  1082. new-frame Make a new frame each time. Note that in this case
  1083. previously-made indirect buffers are kept, and you need to
  1084. kill these buffers yourself."
  1085. :group 'org-structure
  1086. :group 'org-agenda-windows
  1087. :type '(choice
  1088. (const :tag "In current window" current-window)
  1089. (const :tag "In current frame, other window" other-window)
  1090. (const :tag "Each time a new frame" new-frame)
  1091. (const :tag "One dedicated frame" dedicated-frame)))
  1092. (defcustom org-use-speed-commands nil
  1093. "Non-nil means activate single letter commands at beginning of a headline.
  1094. This may also be a function to test for appropriate locations where speed
  1095. commands should be active.
  1096. For example, to activate speed commands when the point is on any
  1097. star at the beginning of the headline, you can do this:
  1098. (setq org-use-speed-commands
  1099. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1100. :group 'org-structure
  1101. :type '(choice
  1102. (const :tag "Never" nil)
  1103. (const :tag "At beginning of headline stars" t)
  1104. (function)))
  1105. (defcustom org-speed-commands-user nil
  1106. "Alist of additional speed commands.
  1107. This list will be checked before `org-speed-commands-default'
  1108. when the variable `org-use-speed-commands' is non-nil
  1109. and when the cursor is at the beginning of a headline.
  1110. The car of each entry is a string with a single letter, which must
  1111. be assigned to `self-insert-command' in the global map.
  1112. The cdr is either a command to be called interactively, a function
  1113. to be called, or a form to be evaluated.
  1114. An entry that is just a list with a single string will be interpreted
  1115. as a descriptive headline that will be added when listing the speed
  1116. commands in the Help buffer using the `?' speed command."
  1117. :group 'org-structure
  1118. :type '(repeat :value ("k" . ignore)
  1119. (choice :value ("k" . ignore)
  1120. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1121. (cons :tag "Letter and Command"
  1122. (string :tag "Command letter")
  1123. (choice
  1124. (function)
  1125. (sexp))))))
  1126. (defcustom org-bookmark-names-plist
  1127. '(:last-capture "org-capture-last-stored"
  1128. :last-refile "org-refile-last-stored"
  1129. :last-capture-marker "org-capture-last-stored-marker")
  1130. "Names for bookmarks automatically set by some Org commands.
  1131. This can provide strings as names for a number of bookmarks Org sets
  1132. automatically. The following keys are currently implemented:
  1133. :last-capture
  1134. :last-capture-marker
  1135. :last-refile
  1136. When a key does not show up in the property list, the corresponding bookmark
  1137. is not set."
  1138. :group 'org-structure
  1139. :type 'plist)
  1140. (defgroup org-cycle nil
  1141. "Options concerning visibility cycling in Org mode."
  1142. :tag "Org Cycle"
  1143. :group 'org-structure)
  1144. (defcustom org-cycle-skip-children-state-if-no-children t
  1145. "Non-nil means skip CHILDREN state in entries that don't have any."
  1146. :group 'org-cycle
  1147. :type 'boolean)
  1148. (defcustom org-cycle-max-level nil
  1149. "Maximum level which should still be subject to visibility cycling.
  1150. Levels higher than this will, for cycling, be treated as text, not a headline.
  1151. When `org-odd-levels-only' is set, a value of N in this variable actually
  1152. means 2N-1 stars as the limiting headline.
  1153. When nil, cycle all levels.
  1154. Note that the limiting level of cycling is also influenced by
  1155. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1156. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1157. than its value."
  1158. :group 'org-cycle
  1159. :type '(choice
  1160. (const :tag "No limit" nil)
  1161. (integer :tag "Maximum level")))
  1162. (defcustom org-hide-block-startup nil
  1163. "Non-nil means entering Org mode will fold all blocks.
  1164. This can also be set in on a per-file basis with
  1165. #+STARTUP: hideblocks
  1166. #+STARTUP: showblocks"
  1167. :group 'org-startup
  1168. :group 'org-cycle
  1169. :type 'boolean)
  1170. (defcustom org-cycle-global-at-bob nil
  1171. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1172. This makes it possible to do global cycling without having to use `S-TAB'
  1173. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1174. line of the buffer
  1175. must not be a headline -- it may be empty or some other text.
  1176. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1177. sure the cursor stays at the beginning of the buffer.
  1178. When this option is nil, don't do anything special at the beginning of
  1179. the buffer."
  1180. :group 'org-cycle
  1181. :type 'boolean)
  1182. (defcustom org-cycle-level-after-item/entry-creation t
  1183. "Non-nil means cycle entry level or item indentation in new empty entries.
  1184. When the cursor is at the end of an empty headline, i.e., with only stars
  1185. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1186. and then all possible ancestor states, before returning to the original state.
  1187. This makes data entry extremely fast: M-RET to create a new headline,
  1188. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1189. When the cursor is at the end of an empty plain list item, one TAB will
  1190. make it a subitem, two or more tabs will back up to make this an item
  1191. higher up in the item hierarchy."
  1192. :group 'org-cycle
  1193. :type 'boolean)
  1194. (defcustom org-cycle-emulate-tab t
  1195. "Where should `org-cycle' emulate TAB.
  1196. nil Never
  1197. white Only in completely white lines
  1198. whitestart Only at the beginning of lines, before the first non-white char
  1199. t Everywhere except in headlines
  1200. exc-hl-bol Everywhere except at the start of a headline
  1201. If TAB is used in a place where it does not emulate TAB, the current subtree
  1202. visibility is cycled."
  1203. :group 'org-cycle
  1204. :type '(choice (const :tag "Never" nil)
  1205. (const :tag "Only in completely white lines" white)
  1206. (const :tag "Before first char in a line" whitestart)
  1207. (const :tag "Everywhere except in headlines" t)
  1208. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1209. (defcustom org-cycle-separator-lines 2
  1210. "Number of empty lines needed to keep an empty line between collapsed trees.
  1211. If you leave an empty line between the end of a subtree and the following
  1212. headline, this empty line is hidden when the subtree is folded.
  1213. Org mode will leave (exactly) one empty line visible if the number of
  1214. empty lines is equal or larger to the number given in this variable.
  1215. So the default 2 means at least 2 empty lines after the end of a subtree
  1216. are needed to produce free space between a collapsed subtree and the
  1217. following headline.
  1218. If the number is negative, and the number of empty lines is at least -N,
  1219. all empty lines are shown.
  1220. Special case: when 0, never leave empty lines in collapsed view."
  1221. :group 'org-cycle
  1222. :type 'integer)
  1223. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1224. (defcustom org-pre-cycle-hook nil
  1225. "Hook that is run before visibility cycling is happening.
  1226. The function(s) in this hook must accept a single argument which indicates
  1227. the new state that will be set right after running this hook. The
  1228. argument is a symbol. Before a global state change, it can have the values
  1229. `overview', `content', or `all'. Before a local state change, it can have
  1230. the values `folded', `children', or `subtree'."
  1231. :group 'org-cycle
  1232. :type 'hook)
  1233. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1234. org-cycle-show-empty-lines
  1235. org-optimize-window-after-visibility-change)
  1236. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1237. The function(s) in this hook must accept a single argument which indicates
  1238. the new state that was set by the most recent `org-cycle' command. The
  1239. argument is a symbol. After a global state change, it can have the values
  1240. `overview', `contents', or `all'. After a local state change, it can have
  1241. the values `folded', `children', or `subtree'."
  1242. :group 'org-cycle
  1243. :type 'hook
  1244. :version "26.1"
  1245. :package-version '(Org . "8.3"))
  1246. (defgroup org-edit-structure nil
  1247. "Options concerning structure editing in Org mode."
  1248. :tag "Org Edit Structure"
  1249. :group 'org-structure)
  1250. (defcustom org-odd-levels-only nil
  1251. "Non-nil means skip even levels and only use odd levels for the outline.
  1252. This has the effect that two stars are being added/taken away in
  1253. promotion/demotion commands. It also influences how levels are
  1254. handled by the exporters.
  1255. Changing it requires restart of `font-lock-mode' to become effective
  1256. for fontification also in regions already fontified.
  1257. You may also set this on a per-file basis by adding one of the following
  1258. lines to the buffer:
  1259. #+STARTUP: odd
  1260. #+STARTUP: oddeven"
  1261. :group 'org-edit-structure
  1262. :group 'org-appearance
  1263. :type 'boolean)
  1264. (defcustom org-adapt-indentation t
  1265. "Non-nil means adapt indentation to outline node level.
  1266. When this variable is set, Org assumes that you write outlines by
  1267. indenting text in each node to align with the headline (after the
  1268. stars). The following issues are influenced by this variable:
  1269. - The indentation is increased by one space in a demotion
  1270. command, and decreased by one in a promotion command. However,
  1271. in the latter case, if shifting some line in the entry body
  1272. would alter document structure (e.g., insert a new headline),
  1273. indentation is not changed at all.
  1274. - Property drawers and planning information is inserted indented
  1275. when this variable is set. When nil, they will not be indented.
  1276. - TAB indents a line relative to current level. The lines below
  1277. a headline will be indented when this variable is set.
  1278. Note that this is all about true indentation, by adding and
  1279. removing space characters. See also \"org-indent.el\" which does
  1280. level-dependent indentation in a virtual way, i.e. at display
  1281. time in Emacs."
  1282. :group 'org-edit-structure
  1283. :type 'boolean
  1284. :safe #'booleanp)
  1285. (defcustom org-special-ctrl-a/e nil
  1286. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1287. When t, `C-a' will bring back the cursor to the beginning of the
  1288. headline text, i.e. after the stars and after a possible TODO
  1289. keyword. In an item, this will be the position after bullet and
  1290. check-box, if any. When the cursor is already at that position,
  1291. another `C-a' will bring it to the beginning of the line.
  1292. `C-e' will jump to the end of the headline, ignoring the presence
  1293. of tags in the headline. A second `C-e' will then jump to the
  1294. true end of the line, after any tags. This also means that, when
  1295. this variable is non-nil, `C-e' also will never jump beyond the
  1296. end of the heading of a folded section, i.e. not after the
  1297. ellipses.
  1298. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1299. normally, going to the true line boundary first. Only a directly
  1300. following, identical keypress will bring the cursor to the
  1301. special positions.
  1302. This may also be a cons cell where the behavior for `C-a' and
  1303. `C-e' is set separately."
  1304. :group 'org-edit-structure
  1305. :type '(choice
  1306. (const :tag "off" nil)
  1307. (const :tag "on: after stars/bullet and before tags first" t)
  1308. (const :tag "reversed: true line boundary first" reversed)
  1309. (cons :tag "Set C-a and C-e separately"
  1310. (choice :tag "Special C-a"
  1311. (const :tag "off" nil)
  1312. (const :tag "on: after stars/bullet first" t)
  1313. (const :tag "reversed: before stars/bullet first" reversed))
  1314. (choice :tag "Special C-e"
  1315. (const :tag "off" nil)
  1316. (const :tag "on: before tags first" t)
  1317. (const :tag "reversed: after tags first" reversed)))))
  1318. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1319. (defcustom org-special-ctrl-k nil
  1320. "Non-nil means `C-k' will behave specially in headlines.
  1321. When nil, `C-k' will call the default `kill-line' command.
  1322. When t, the following will happen while the cursor is in the headline:
  1323. - When the cursor is at the beginning of a headline, kill the entire
  1324. line and possible the folded subtree below the line.
  1325. - When in the middle of the headline text, kill the headline up to the tags.
  1326. - When after the headline text, kill the tags."
  1327. :group 'org-edit-structure
  1328. :type 'boolean)
  1329. (defcustom org-ctrl-k-protect-subtree nil
  1330. "Non-nil means, do not delete a hidden subtree with C-k.
  1331. When set to the symbol `error', simply throw an error when C-k is
  1332. used to kill (part-of) a headline that has hidden text behind it.
  1333. Any other non-nil value will result in a query to the user, if it is
  1334. OK to kill that hidden subtree. When nil, kill without remorse."
  1335. :group 'org-edit-structure
  1336. :version "24.1"
  1337. :type '(choice
  1338. (const :tag "Do not protect hidden subtrees" nil)
  1339. (const :tag "Protect hidden subtrees with a security query" t)
  1340. (const :tag "Never kill a hidden subtree with C-k" error)))
  1341. (defcustom org-special-ctrl-o t
  1342. "Non-nil means, make `C-o' insert a row in tables."
  1343. :group 'org-edit-structure
  1344. :type 'boolean)
  1345. (defcustom org-catch-invisible-edits nil
  1346. "Check if in invisible region before inserting or deleting a character.
  1347. Valid values are:
  1348. nil Do not check, so just do invisible edits.
  1349. error Throw an error and do nothing.
  1350. show Make point visible, and do the requested edit.
  1351. show-and-error Make point visible, then throw an error and abort the edit.
  1352. smart Make point visible, and do insertion/deletion if it is
  1353. adjacent to visible text and the change feels predictable.
  1354. Never delete a previously invisible character or add in the
  1355. middle or right after an invisible region. Basically, this
  1356. allows insertion and backward-delete right before ellipses.
  1357. FIXME: maybe in this case we should not even show?"
  1358. :group 'org-edit-structure
  1359. :version "24.1"
  1360. :type '(choice
  1361. (const :tag "Do not check" nil)
  1362. (const :tag "Throw error when trying to edit" error)
  1363. (const :tag "Unhide, but do not do the edit" show-and-error)
  1364. (const :tag "Show invisible part and do the edit" show)
  1365. (const :tag "Be smart and do the right thing" smart)))
  1366. (defcustom org-yank-folded-subtrees t
  1367. "Non-nil means when yanking subtrees, fold them.
  1368. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1369. it starts with a heading and all other headings in it are either children
  1370. or siblings, then fold all the subtrees. However, do this only if no
  1371. text after the yank would be swallowed into a folded tree by this action."
  1372. :group 'org-edit-structure
  1373. :type 'boolean)
  1374. (defcustom org-yank-adjusted-subtrees nil
  1375. "Non-nil means when yanking subtrees, adjust the level.
  1376. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1377. this function for details."
  1378. :group 'org-edit-structure
  1379. :type 'boolean)
  1380. (defcustom org-M-RET-may-split-line '((default . t))
  1381. "Non-nil means M-RET will split the line at the cursor position.
  1382. When nil, it will go to the end of the line before making a
  1383. new line.
  1384. You may also set this option in a different way for different
  1385. contexts. Valid contexts are:
  1386. headline when creating a new headline
  1387. item when creating a new item
  1388. table in a table field
  1389. default the value to be used for all contexts not explicitly
  1390. customized"
  1391. :group 'org-structure
  1392. :group 'org-table
  1393. :type '(choice
  1394. (const :tag "Always" t)
  1395. (const :tag "Never" nil)
  1396. (repeat :greedy t :tag "Individual contexts"
  1397. (cons
  1398. (choice :tag "Context"
  1399. (const headline)
  1400. (const item)
  1401. (const table)
  1402. (const default))
  1403. (boolean)))))
  1404. (defcustom org-insert-heading-respect-content nil
  1405. "Non-nil means insert new headings after the current subtree.
  1406. \\<org-mode-map>
  1407. When nil, the new heading is created directly after the current line.
  1408. The commands `\\[org-insert-heading-respect-content]' and \
  1409. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1410. for the duration of the command."
  1411. :group 'org-structure
  1412. :type 'boolean)
  1413. (defcustom org-blank-before-new-entry '((heading . auto)
  1414. (plain-list-item . auto))
  1415. "Should `org-insert-heading' leave a blank line before new heading/item?
  1416. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1417. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1418. which case Org will look at the surrounding headings/items and try to
  1419. make an intelligent decision whether to insert a blank line or not."
  1420. :group 'org-edit-structure
  1421. :type '(list
  1422. (cons (const heading)
  1423. (choice (const :tag "Never" nil)
  1424. (const :tag "Always" t)
  1425. (const :tag "Auto" auto)))
  1426. (cons (const plain-list-item)
  1427. (choice (const :tag "Never" nil)
  1428. (const :tag "Always" t)
  1429. (const :tag "Auto" auto)))))
  1430. (defcustom org-insert-heading-hook nil
  1431. "Hook being run after inserting a new heading."
  1432. :group 'org-edit-structure
  1433. :type 'hook)
  1434. (defcustom org-enable-fixed-width-editor t
  1435. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1436. This currently only means they are never auto-wrapped.
  1437. When nil, such lines will be treated like ordinary lines."
  1438. :group 'org-edit-structure
  1439. :type 'boolean)
  1440. (defgroup org-sparse-trees nil
  1441. "Options concerning sparse trees in Org mode."
  1442. :tag "Org Sparse Trees"
  1443. :group 'org-structure)
  1444. (defcustom org-highlight-sparse-tree-matches t
  1445. "Non-nil means highlight all matches that define a sparse tree.
  1446. The highlights will automatically disappear the next time the buffer is
  1447. changed by an edit command."
  1448. :group 'org-sparse-trees
  1449. :type 'boolean)
  1450. (defcustom org-remove-highlights-with-change t
  1451. "Non-nil means any change to the buffer will remove temporary highlights.
  1452. \\<org-mode-map>\
  1453. Such highlights are created by `org-occur' and `org-clock-display'.
  1454. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1455. to get rid of the highlights.
  1456. The highlights created by `org-toggle-latex-fragment' always need
  1457. `\\[org-toggle-latex-fragment]' to be removed."
  1458. :group 'org-sparse-trees
  1459. :group 'org-time
  1460. :type 'boolean)
  1461. (defcustom org-occur-case-fold-search t
  1462. "Non-nil means `org-occur' should be case-insensitive.
  1463. If set to `smart' the search will be case-insensitive only if it
  1464. doesn't specify any upper case character."
  1465. :group 'org-sparse-trees
  1466. :version "26.1"
  1467. :type '(choice
  1468. (const :tag "Case-sensitive" nil)
  1469. (const :tag "Case-insensitive" t)
  1470. (const :tag "Case-insensitive for lower case searches only" smart)))
  1471. (defcustom org-occur-hook '(org-first-headline-recenter)
  1472. "Hook that is run after `org-occur' has constructed a sparse tree.
  1473. This can be used to recenter the window to show as much of the structure
  1474. as possible."
  1475. :group 'org-sparse-trees
  1476. :type 'hook)
  1477. (defgroup org-table nil
  1478. "Options concerning tables in Org mode."
  1479. :tag "Org Table"
  1480. :group 'org)
  1481. (defcustom org-self-insert-cluster-for-undo nil
  1482. "Non-nil means cluster self-insert commands for undo when possible.
  1483. If this is set, then, like in the Emacs command loop, 20 consecutive
  1484. characters will be undone together.
  1485. This is configurable, because there is some impact on typing performance."
  1486. :group 'org-table
  1487. :type 'boolean)
  1488. (defcustom org-table-tab-recognizes-table.el t
  1489. "Non-nil means TAB will automatically notice a table.el table.
  1490. When it sees such a table, it moves point into it and - if necessary -
  1491. calls `table-recognize-table'."
  1492. :group 'org-table-editing
  1493. :type 'boolean)
  1494. (defgroup org-link nil
  1495. "Options concerning links in Org mode."
  1496. :tag "Org Link"
  1497. :group 'org)
  1498. (defvar-local org-link-abbrev-alist-local nil
  1499. "Buffer-local version of `org-link-abbrev-alist', which see.
  1500. The value of this is taken from the #+LINK lines.")
  1501. (defcustom org-link-parameters
  1502. '(("doi" :follow org--open-doi-link)
  1503. ("elisp" :follow org--open-elisp-link)
  1504. ("file" :complete org-file-complete-link)
  1505. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1506. ("help" :follow org--open-help-link)
  1507. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1508. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1509. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1510. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1511. ("shell" :follow org--open-shell-link))
  1512. "An alist of properties that defines all the links in Org mode.
  1513. The key in each association is a string of the link type.
  1514. Subsequent optional elements make up a p-list of link properties.
  1515. :follow - A function that takes the link path as an argument.
  1516. :export - A function that takes the link path, description and
  1517. export-backend as arguments.
  1518. :store - A function responsible for storing the link. See the
  1519. function `org-store-link-functions'.
  1520. :complete - A function that inserts a link with completion. The
  1521. function takes one optional prefix arg.
  1522. :face - A face for the link, or a function that returns a face.
  1523. The function takes one argument which is the link path. The
  1524. default face is `org-link'.
  1525. :mouse-face - The mouse-face. The default is `highlight'.
  1526. :display - `full' will not fold the link in descriptive
  1527. display. Default is `org-link'.
  1528. :help-echo - A string or function that takes (window object position)
  1529. as arguments and returns a string.
  1530. :keymap - A keymap that is active on the link. The default is
  1531. `org-mouse-map'.
  1532. :htmlize-link - A function for the htmlize-link. Defaults
  1533. to (list :uri \"type:path\")
  1534. :activate-func - A function to run at the end of font-lock
  1535. activation. The function must accept (link-start link-end path bracketp)
  1536. as arguments."
  1537. :group 'org-link
  1538. :type '(alist :tag "Link display parameters"
  1539. :value-type plist)
  1540. :version "26.1"
  1541. :package-version '(Org . "9.1"))
  1542. (defun org-link-get-parameter (type key)
  1543. "Get TYPE link property for KEY.
  1544. TYPE is a string and KEY is a plist keyword."
  1545. (plist-get
  1546. (cdr (assoc type org-link-parameters))
  1547. key))
  1548. (defun org-link-set-parameters (type &rest parameters)
  1549. "Set link TYPE properties to PARAMETERS.
  1550. PARAMETERS should be :key val pairs."
  1551. (let ((data (assoc type org-link-parameters)))
  1552. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1553. (push (cons type parameters) org-link-parameters)
  1554. (org-make-link-regexps)
  1555. (org-element-update-syntax))))
  1556. (defun org-link-types ()
  1557. "Return a list of known link types."
  1558. (mapcar #'car org-link-parameters))
  1559. (defcustom org-link-abbrev-alist nil
  1560. "Alist of link abbreviations.
  1561. The car of each element is a string, to be replaced at the start of a link.
  1562. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1563. links in Org buffers can have an optional tag after a double colon, e.g.,
  1564. [[linkkey:tag][description]]
  1565. The `linkkey' must be a single word, starting with a letter, followed
  1566. by letters, numbers, `-' or `_'.
  1567. If REPLACE is a string, the tag will simply be appended to create the link.
  1568. If the string contains \"%s\", the tag will be inserted there. If the string
  1569. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1570. at that point (see the function `url-hexify-string'). If the string contains
  1571. the specifier \"%(my-function)\", then the custom function `my-function' will
  1572. be invoked: this function takes the tag as its only argument and must return
  1573. a string.
  1574. REPLACE may also be a function that will be called with the tag as the
  1575. only argument to create the link, which should be returned as a string.
  1576. See the manual for examples."
  1577. :group 'org-link
  1578. :type '(repeat
  1579. (cons
  1580. (string :tag "Protocol")
  1581. (choice
  1582. (string :tag "Format")
  1583. (function)))))
  1584. (defcustom org-descriptive-links t
  1585. "Non-nil means Org will display descriptive links.
  1586. E.g. [[https://orgmode.org][Org website]] will be displayed as
  1587. \"Org Website\", hiding the link itself and just displaying its
  1588. description. When set to nil, Org will display the full links
  1589. literally.
  1590. You can interactively set the value of this variable by calling
  1591. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1592. :group 'org-link
  1593. :type 'boolean)
  1594. (defcustom org-link-file-path-type 'adaptive
  1595. "How the path name in file links should be stored.
  1596. Valid values are:
  1597. relative Relative to the current directory, i.e. the directory of the file
  1598. into which the link is being inserted.
  1599. absolute Absolute path, if possible with ~ for home directory.
  1600. noabbrev Absolute path, no abbreviation of home directory.
  1601. adaptive Use relative path for files in the current directory and sub-
  1602. directories of it. For other files, use an absolute path."
  1603. :group 'org-link
  1604. :type '(choice
  1605. (const relative)
  1606. (const absolute)
  1607. (const noabbrev)
  1608. (const adaptive)))
  1609. (defvaralias 'org-activate-links 'org-highlight-links)
  1610. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1611. "Types of links that should be highlighted in Org files.
  1612. This is a list of symbols, each one of them leading to the
  1613. highlighting of a certain link type.
  1614. You can still open links that are not highlighted.
  1615. In principle, it does not hurt to turn on highlighting for all
  1616. link types. There may be a small gain when turning off unused
  1617. link types. The types are:
  1618. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1619. angle Links in angular brackets that may contain whitespace like
  1620. <bbdb:Carsten Dominik>.
  1621. plain Plain links in normal text, no whitespace, like http://google.com.
  1622. radio Text that is matched by a radio target, see manual for details.
  1623. tag Tag settings in a headline (link to tag search).
  1624. date Time stamps (link to calendar).
  1625. footnote Footnote labels.
  1626. If you set this variable during an Emacs session, use `org-mode-restart'
  1627. in the Org buffer so that the change takes effect."
  1628. :group 'org-link
  1629. :group 'org-appearance
  1630. :type '(set :greedy t
  1631. (const :tag "Double bracket links" bracket)
  1632. (const :tag "Angular bracket links" angle)
  1633. (const :tag "Plain text links" plain)
  1634. (const :tag "Radio target matches" radio)
  1635. (const :tag "Tags" tag)
  1636. (const :tag "Timestamps" date)
  1637. (const :tag "Footnotes" footnote)))
  1638. (defcustom org-make-link-description-function nil
  1639. "Function to use for generating link descriptions from links.
  1640. This function must take two parameters: the first one is the
  1641. link, the second one is the description generated by
  1642. `org-insert-link'. The function should return the description to
  1643. use."
  1644. :group 'org-link
  1645. :type '(choice (const nil) (function)))
  1646. (defgroup org-link-store nil
  1647. "Options concerning storing links in Org mode."
  1648. :tag "Org Store Link"
  1649. :group 'org-link)
  1650. (defcustom org-url-hexify-p t
  1651. "When non-nil, hexify URL when creating a link."
  1652. :type 'boolean
  1653. :version "24.3"
  1654. :group 'org-link-store)
  1655. (defcustom org-email-link-description-format "Email %c: %.30s"
  1656. "Format of the description part of a link to an email or usenet message.
  1657. The following %-escapes will be replaced by corresponding information:
  1658. %F full \"From\" field
  1659. %f name, taken from \"From\" field, address if no name
  1660. %T full \"To\" field
  1661. %t first name in \"To\" field, address if no name
  1662. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1663. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1664. %s subject
  1665. %d date
  1666. %m message-id.
  1667. You may use normal field width specification between the % and the letter.
  1668. This is for example useful to limit the length of the subject.
  1669. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1670. :group 'org-link-store
  1671. :type 'string)
  1672. (defcustom org-from-is-user-regexp
  1673. (let (r1 r2)
  1674. (when (and user-mail-address (not (string= user-mail-address "")))
  1675. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1676. (when (and user-full-name (not (string= user-full-name "")))
  1677. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1678. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1679. "Regexp matched against the \"From:\" header of an email or usenet message.
  1680. It should match if the message is from the user him/herself."
  1681. :group 'org-link-store
  1682. :type 'regexp)
  1683. (defcustom org-context-in-file-links t
  1684. "Non-nil means file links from `org-store-link' contain context.
  1685. \\<org-mode-map>
  1686. A search string will be added to the file name with :: as separator
  1687. and used to find the context when the link is activated by the command
  1688. `org-open-at-point'. When this option is t, the entire active region
  1689. will be placed in the search string of the file link. If set to a
  1690. positive integer, only the first n lines of context will be stored.
  1691. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1692. \\[org-store-link]')
  1693. negates this setting for the duration of the command."
  1694. :group 'org-link-store
  1695. :type '(choice boolean integer))
  1696. (defcustom org-keep-stored-link-after-insertion nil
  1697. "Non-nil means keep link in list for entire session.
  1698. \\<org-mode-map>
  1699. The command `org-store-link' adds a link pointing to the current
  1700. location to an internal list. These links accumulate during a session.
  1701. The command `org-insert-link' can be used to insert links into any
  1702. Org file (offering completion for all stored links).
  1703. When this option is nil, every link which has been inserted once using
  1704. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1705. unused
  1706. links more efficient."
  1707. :group 'org-link-store
  1708. :type 'boolean)
  1709. (defgroup org-link-follow nil
  1710. "Options concerning following links in Org mode."
  1711. :tag "Org Follow Link"
  1712. :group 'org-link)
  1713. (defcustom org-link-translation-function nil
  1714. "Function to translate links with different syntax to Org syntax.
  1715. This can be used to translate links created for example by the Planner
  1716. or emacs-wiki packages to Org syntax.
  1717. The function must accept two parameters, a TYPE containing the link
  1718. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1719. which is everything after the link protocol. It should return a cons
  1720. with possibly modified values of type and path.
  1721. Org contains a function for this, so if you set this variable to
  1722. `org-translate-link-from-planner', you should be able follow many
  1723. links created by planner."
  1724. :group 'org-link-follow
  1725. :type '(choice (const nil) (function)))
  1726. (defcustom org-follow-link-hook nil
  1727. "Hook that is run after a link has been followed."
  1728. :group 'org-link-follow
  1729. :type 'hook)
  1730. (defcustom org-tab-follows-link nil
  1731. "Non-nil means on links TAB will follow the link.
  1732. Needs to be set before org.el is loaded.
  1733. This really should not be used, it does not make sense, and the
  1734. implementation is bad."
  1735. :group 'org-link-follow
  1736. :type 'boolean)
  1737. (defcustom org-return-follows-link nil
  1738. "Non-nil means on links RET will follow the link.
  1739. In tables, the special behavior of RET has precedence."
  1740. :group 'org-link-follow
  1741. :type 'boolean)
  1742. (defcustom org-mouse-1-follows-link
  1743. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1744. "Non-nil means mouse-1 on a link will follow the link.
  1745. A longer mouse click will still set point. Needs to be set
  1746. before org.el is loaded."
  1747. :group 'org-link-follow
  1748. :version "26.1"
  1749. :package-version '(Org . "8.3")
  1750. :type '(choice
  1751. (const :tag "A double click follows the link" double)
  1752. (const :tag "Unconditionally follow the link with mouse-1" t)
  1753. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1754. (defcustom org-mark-ring-length 4
  1755. "Number of different positions to be recorded in the ring.
  1756. Changing this requires a restart of Emacs to work correctly."
  1757. :group 'org-link-follow
  1758. :type 'integer)
  1759. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1760. "Non-nil means internal fuzzy links can only match headlines.
  1761. When nil, the a fuzzy link may point to a target or a named
  1762. construct in the document. When set to the special value
  1763. `query-to-create', offer to create a new headline when none
  1764. matched.
  1765. Spaces and statistics cookies are ignored during heading searches."
  1766. :group 'org-link-follow
  1767. :version "24.1"
  1768. :type '(choice
  1769. (const :tag "Use fuzzy text search" nil)
  1770. (const :tag "Match only exact headline" t)
  1771. (const :tag "Match exact headline or query to create it"
  1772. query-to-create))
  1773. :safe #'symbolp)
  1774. (defcustom org-link-frame-setup
  1775. '((vm . vm-visit-folder-other-frame)
  1776. (vm-imap . vm-visit-imap-folder-other-frame)
  1777. (gnus . org-gnus-no-new-news)
  1778. (file . find-file-other-window)
  1779. (wl . wl-other-frame))
  1780. "Setup the frame configuration for following links.
  1781. When following a link with Emacs, it may often be useful to display
  1782. this link in another window or frame. This variable can be used to
  1783. set this up for the different types of links.
  1784. For VM, use any of
  1785. `vm-visit-folder'
  1786. `vm-visit-folder-other-window'
  1787. `vm-visit-folder-other-frame'
  1788. For Gnus, use any of
  1789. `gnus'
  1790. `gnus-other-frame'
  1791. `org-gnus-no-new-news'
  1792. For FILE, use any of
  1793. `find-file'
  1794. `find-file-other-window'
  1795. `find-file-other-frame'
  1796. For Wanderlust use any of
  1797. `wl'
  1798. `wl-other-frame'
  1799. For the calendar, use the variable `calendar-setup'.
  1800. For BBDB, it is currently only possible to display the matches in
  1801. another window."
  1802. :group 'org-link-follow
  1803. :type '(list
  1804. (cons (const vm)
  1805. (choice
  1806. (const vm-visit-folder)
  1807. (const vm-visit-folder-other-window)
  1808. (const vm-visit-folder-other-frame)))
  1809. (cons (const vm-imap)
  1810. (choice
  1811. (const vm-visit-imap-folder)
  1812. (const vm-visit-imap-folder-other-window)
  1813. (const vm-visit-imap-folder-other-frame)))
  1814. (cons (const gnus)
  1815. (choice
  1816. (const gnus)
  1817. (const gnus-other-frame)
  1818. (const org-gnus-no-new-news)))
  1819. (cons (const file)
  1820. (choice
  1821. (const find-file)
  1822. (const find-file-other-window)
  1823. (const find-file-other-frame)))
  1824. (cons (const wl)
  1825. (choice
  1826. (const wl)
  1827. (const wl-other-frame)))))
  1828. (defcustom org-display-internal-link-with-indirect-buffer nil
  1829. "Non-nil means use indirect buffer to display infile links.
  1830. Activating internal links (from one location in a file to another location
  1831. in the same file) normally just jumps to the location. When the link is
  1832. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1833. is displayed in
  1834. another window. When this option is set, the other window actually displays
  1835. an indirect buffer clone of the current buffer, to avoid any visibility
  1836. changes to the current buffer."
  1837. :group 'org-link-follow
  1838. :type 'boolean)
  1839. (defcustom org-open-non-existing-files nil
  1840. "Non-nil means `org-open-file' will open non-existing files.
  1841. When nil, an error will be generated.
  1842. This variable applies only to external applications because they
  1843. might choke on non-existing files. If the link is to a file that
  1844. will be opened in Emacs, the variable is ignored."
  1845. :group 'org-link-follow
  1846. :type 'boolean)
  1847. (defcustom org-open-directory-means-index-dot-org nil
  1848. "Non-nil means a link to a directory really means to index.org.
  1849. When nil, following a directory link will run dired or open a finder/explorer
  1850. window on that directory."
  1851. :group 'org-link-follow
  1852. :type 'boolean)
  1853. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1854. "Non-nil means ask for confirmation before executing shell links.
  1855. Shell links can be dangerous: just think about a link
  1856. [[shell:rm -rf ~/*][Google Search]]
  1857. This link would show up in your Org document as \"Google Search\",
  1858. but really it would remove your entire home directory.
  1859. Therefore we advise against setting this variable to nil.
  1860. Just change it to `y-or-n-p' if you want to confirm with a
  1861. single keystroke rather than having to type \"yes\"."
  1862. :group 'org-link-follow
  1863. :type '(choice
  1864. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1865. (const :tag "with y-or-n (faster)" y-or-n-p)
  1866. (const :tag "no confirmation (dangerous)" nil)))
  1867. (put 'org-confirm-shell-link-function
  1868. 'safe-local-variable
  1869. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1870. (defcustom org-confirm-shell-link-not-regexp ""
  1871. "A regexp to skip confirmation for shell links."
  1872. :group 'org-link-follow
  1873. :version "24.1"
  1874. :type 'regexp)
  1875. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1876. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1877. Elisp links can be dangerous: just think about a link
  1878. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1879. This link would show up in your Org document as \"Google Search\",
  1880. but really it would remove your entire home directory.
  1881. Therefore we advise against setting this variable to nil.
  1882. Just change it to `y-or-n-p' if you want to confirm with a
  1883. single keystroke rather than having to type \"yes\"."
  1884. :group 'org-link-follow
  1885. :type '(choice
  1886. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1887. (const :tag "with y-or-n (faster)" y-or-n-p)
  1888. (const :tag "no confirmation (dangerous)" nil)))
  1889. (put 'org-confirm-shell-link-function
  1890. 'safe-local-variable
  1891. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1892. (defcustom org-confirm-elisp-link-not-regexp ""
  1893. "A regexp to skip confirmation for Elisp links."
  1894. :group 'org-link-follow
  1895. :version "24.1"
  1896. :type 'regexp)
  1897. (defconst org-file-apps-defaults-gnu
  1898. '((remote . emacs)
  1899. (system . mailcap)
  1900. (t . mailcap))
  1901. "Default file applications on a UNIX or GNU/Linux system.
  1902. See `org-file-apps'.")
  1903. (defconst org-file-apps-defaults-macosx
  1904. '((remote . emacs)
  1905. (system . "open %s")
  1906. ("ps.gz" . "gv %s")
  1907. ("eps.gz" . "gv %s")
  1908. ("dvi" . "xdvi %s")
  1909. ("fig" . "xfig %s")
  1910. (t . "open %s"))
  1911. "Default file applications on a macOS system.
  1912. The system \"open\" is known as a default, but we use X11 applications
  1913. for some files for which the OS does not have a good default.
  1914. See `org-file-apps'.")
  1915. (defconst org-file-apps-defaults-windowsnt
  1916. (list '(remote . emacs)
  1917. (cons 'system (lambda (file _path)
  1918. (with-no-warnings (w32-shell-execute "open" file))))
  1919. (cons t (lambda (file _path)
  1920. (with-no-warnings (w32-shell-execute "open" file)))))
  1921. "Default file applications on a Windows NT system.
  1922. The system \"open\" is used for most files.
  1923. See `org-file-apps'.")
  1924. (defcustom org-file-apps
  1925. '((auto-mode . emacs)
  1926. ("\\.mm\\'" . default)
  1927. ("\\.x?html?\\'" . default)
  1928. ("\\.pdf\\'" . default))
  1929. "External applications for opening `file:path' items in a document.
  1930. \\<org-mode-map>\
  1931. Org mode uses system defaults for different file types, but
  1932. you can use this variable to set the application for a given file
  1933. extension. The entries in this list are cons cells where the car identifies
  1934. files and the cdr the corresponding command.
  1935. Possible values for the file identifier are:
  1936. \"string\" A string as a file identifier can be interpreted in different
  1937. ways, depending on its contents:
  1938. - Alphanumeric characters only:
  1939. Match links with this file extension.
  1940. Example: (\"pdf\" . \"evince %s\")
  1941. to open PDFs with evince.
  1942. - Regular expression: Match links where the
  1943. filename matches the regexp. If you want to
  1944. use groups here, use shy groups.
  1945. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1946. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1947. to open *.html and *.xhtml with firefox.
  1948. - Regular expression which contains (non-shy) groups:
  1949. Match links where the whole link, including \"::\", and
  1950. anything after that, matches the regexp.
  1951. In a custom command string, %1, %2, etc. are replaced with
  1952. the parts of the link that were matched by the groups.
  1953. For backwards compatibility, if a command string is given
  1954. that does not use any of the group matches, this case is
  1955. handled identically to the second one (i.e. match against
  1956. file name only).
  1957. In a custom function, you can access the group matches with
  1958. (match-string n link).
  1959. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1960. \"evince -p %1 %s\")
  1961. to open [[file:document.pdf::5]] with evince at page 5.
  1962. `directory' Matches a directory
  1963. `remote' Matches a remote file, accessible through tramp or efs.
  1964. Remote files most likely should be visited through Emacs
  1965. because external applications cannot handle such paths.
  1966. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1967. so all files Emacs knows how to handle. Using this with
  1968. command `emacs' will open most files in Emacs. Beware that this
  1969. will also open html files inside Emacs, unless you add
  1970. (\"html\" . default) to the list as well.
  1971. `system' The system command to open files, like `open' on Windows
  1972. and macOS, and mailcap under GNU/Linux. This is the command
  1973. that will be selected if you call `org-open-at-point' with a
  1974. double prefix argument (`\\[universal-argument] \
  1975. \\[universal-argument] \\[org-open-at-point]').
  1976. t Default for files not matched by any of the other options.
  1977. Possible values for the command are:
  1978. `emacs' The file will be visited by the current Emacs process.
  1979. `default' Use the default application for this file type, which is the
  1980. association for t in the list, most likely in the system-specific
  1981. part. This can be used to overrule an unwanted setting in the
  1982. system-specific variable.
  1983. `system' Use the system command for opening files, like \"open\".
  1984. This command is specified by the entry whose car is `system'.
  1985. Most likely, the system-specific version of this variable
  1986. does define this command, but you can overrule/replace it
  1987. here.
  1988. `mailcap' Use command specified in the mailcaps.
  1989. string A command to be executed by a shell; %s will be replaced
  1990. by the path to the file.
  1991. function A Lisp function, which will be called with two arguments:
  1992. the file path and the original link string, without the
  1993. \"file:\" prefix.
  1994. For more examples, see the system specific constants
  1995. `org-file-apps-defaults-macosx'
  1996. `org-file-apps-defaults-windowsnt'
  1997. `org-file-apps-defaults-gnu'."
  1998. :group 'org-link-follow
  1999. :type '(repeat
  2000. (cons (choice :value ""
  2001. (string :tag "Extension")
  2002. (const :tag "System command to open files" system)
  2003. (const :tag "Default for unrecognized files" t)
  2004. (const :tag "Remote file" remote)
  2005. (const :tag "Links to a directory" directory)
  2006. (const :tag "Any files that have Emacs modes"
  2007. auto-mode))
  2008. (choice :value ""
  2009. (const :tag "Visit with Emacs" emacs)
  2010. (const :tag "Use default" default)
  2011. (const :tag "Use the system command" system)
  2012. (string :tag "Command")
  2013. (function :tag "Function")))))
  2014. (defcustom org-doi-server-url "http://dx.doi.org/"
  2015. "The URL of the DOI server."
  2016. :type 'string
  2017. :version "24.3"
  2018. :group 'org-link-follow)
  2019. (defgroup org-refile nil
  2020. "Options concerning refiling entries in Org mode."
  2021. :tag "Org Refile"
  2022. :group 'org)
  2023. (defcustom org-directory "~/org"
  2024. "Directory with Org files.
  2025. This is just a default location to look for Org files. There is no need
  2026. at all to put your files into this directory. It is used in the
  2027. following situations:
  2028. 1. When a capture template specifies a target file that is not an
  2029. absolute path. The path will then be interpreted relative to
  2030. `org-directory'
  2031. 2. When the value of variable `org-agenda-files' is a single file, any
  2032. relative paths in this file will be taken as relative to
  2033. `org-directory'."
  2034. :group 'org-refile
  2035. :group 'org-capture
  2036. :type 'directory)
  2037. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2038. "Default target for storing notes.
  2039. Used as a fall back file for org-capture.el, for templates that
  2040. do not specify a target file."
  2041. :group 'org-refile
  2042. :group 'org-capture
  2043. :type 'file)
  2044. (defcustom org-reverse-note-order nil
  2045. "Non-nil means store new notes at the beginning of a file or entry.
  2046. When nil, new notes will be filed to the end of a file or entry.
  2047. This can also be a list with cons cells of regular expressions that
  2048. are matched against file names, and values."
  2049. :group 'org-capture
  2050. :group 'org-refile
  2051. :type '(choice
  2052. (const :tag "Reverse always" t)
  2053. (const :tag "Reverse never" nil)
  2054. (repeat :tag "By file name regexp"
  2055. (cons regexp boolean))))
  2056. (defcustom org-log-refile nil
  2057. "Information to record when a task is refiled.
  2058. Possible values are:
  2059. nil Don't add anything
  2060. time Add a time stamp to the task
  2061. note Prompt for a note and add it with template `org-log-note-headings'
  2062. This option can also be set with on a per-file-basis with
  2063. #+STARTUP: nologrefile
  2064. #+STARTUP: logrefile
  2065. #+STARTUP: lognoterefile
  2066. You can have local logging settings for a subtree by setting the LOGGING
  2067. property to one or more of these keywords.
  2068. When bulk-refiling from the agenda, the value `note' is forbidden and
  2069. will temporarily be changed to `time'."
  2070. :group 'org-refile
  2071. :group 'org-progress
  2072. :version "24.1"
  2073. :type '(choice
  2074. (const :tag "No logging" nil)
  2075. (const :tag "Record timestamp" time)
  2076. (const :tag "Record timestamp with note." note)))
  2077. (defcustom org-refile-targets nil
  2078. "Targets for refiling entries with `\\[org-refile]'.
  2079. This is a list of cons cells. Each cell contains:
  2080. - a specification of the files to be considered, either a list of files,
  2081. or a symbol whose function or variable value will be used to retrieve
  2082. a file name or a list of file names. If you use `org-agenda-files' for
  2083. that, all agenda files will be scanned for targets. Nil means consider
  2084. headings in the current buffer.
  2085. - A specification of how to find candidate refile targets. This may be
  2086. any of:
  2087. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2088. This tag has to be present in all target headlines, inheritance will
  2089. not be considered.
  2090. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2091. todo keyword.
  2092. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2093. headlines that are refiling targets.
  2094. - a cons cell (:level . N). Any headline of level N is considered a target.
  2095. Note that, when `org-odd-levels-only' is set, level corresponds to
  2096. order in hierarchy, not to the number of stars.
  2097. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2098. Note that, when `org-odd-levels-only' is set, level corresponds to
  2099. order in hierarchy, not to the number of stars.
  2100. Each element of this list generates a set of possible targets.
  2101. The union of these sets is presented (with completion) to
  2102. the user by `org-refile'.
  2103. You can set the variable `org-refile-target-verify-function' to a function
  2104. to verify each headline found by the simple criteria above.
  2105. When this variable is nil, all top-level headlines in the current buffer
  2106. are used, equivalent to the value `((nil . (:level . 1))'."
  2107. :group 'org-refile
  2108. :type '(repeat
  2109. (cons
  2110. (choice :value org-agenda-files
  2111. (const :tag "All agenda files" org-agenda-files)
  2112. (const :tag "Current buffer" nil)
  2113. (function) (variable) (file))
  2114. (choice :tag "Identify target headline by"
  2115. (cons :tag "Specific tag" (const :value :tag) (string))
  2116. (cons :tag "TODO keyword" (const :value :todo) (string))
  2117. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2118. (cons :tag "Level number" (const :value :level) (integer))
  2119. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2120. (defcustom org-refile-target-verify-function nil
  2121. "Function to verify if the headline at point should be a refile target.
  2122. The function will be called without arguments, with point at the
  2123. beginning of the headline. It should return t and leave point
  2124. where it is if the headline is a valid target for refiling.
  2125. If the target should not be selected, the function must return nil.
  2126. In addition to this, it may move point to a place from where the search
  2127. should be continued. For example, the function may decide that the entire
  2128. subtree of the current entry should be excluded and move point to the end
  2129. of the subtree."
  2130. :group 'org-refile
  2131. :type '(choice
  2132. (const nil)
  2133. (function)))
  2134. (defcustom org-refile-use-cache nil
  2135. "Non-nil means cache refile targets to speed up the process.
  2136. \\<org-mode-map>\
  2137. The cache for a particular file will be updated automatically when
  2138. the buffer has been killed, or when any of the marker used for flagging
  2139. refile targets no longer points at a live buffer.
  2140. If you have added new entries to a buffer that might themselves be targets,
  2141. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2142. if you find that easier, \
  2143. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2144. \\[org-refile]'."
  2145. :group 'org-refile
  2146. :version "24.1"
  2147. :type 'boolean)
  2148. (defcustom org-refile-use-outline-path nil
  2149. "Non-nil means provide refile targets as paths.
  2150. So a level 3 headline will be available as level1/level2/level3.
  2151. When the value is `file', also include the file name (without directory)
  2152. into the path. In this case, you can also stop the completion after
  2153. the file name, to get entries inserted as top level in the file.
  2154. When `full-file-path', include the full file path.
  2155. When `buffer-name', use the buffer name."
  2156. :group 'org-refile
  2157. :type '(choice
  2158. (const :tag "Not" nil)
  2159. (const :tag "Yes" t)
  2160. (const :tag "Start with file name" file)
  2161. (const :tag "Start with full file path" full-file-path)
  2162. (const :tag "Start with buffer name" buffer-name)))
  2163. (defcustom org-outline-path-complete-in-steps t
  2164. "Non-nil means complete the outline path in hierarchical steps.
  2165. When Org uses the refile interface to select an outline path (see
  2166. `org-refile-use-outline-path'), the completion of the path can be
  2167. done in a single go, or it can be done in steps down the headline
  2168. hierarchy. Going in steps is probably the best if you do not use
  2169. a special completion package like `ido' or `icicles'. However,
  2170. when using these packages, going in one step can be very fast,
  2171. while still showing the whole path to the entry."
  2172. :group 'org-refile
  2173. :type 'boolean)
  2174. (defcustom org-refile-allow-creating-parent-nodes nil
  2175. "Non-nil means allow the creation of new nodes as refile targets.
  2176. New nodes are then created by adding \"/new node name\" to the completion
  2177. of an existing node. When the value of this variable is `confirm',
  2178. new node creation must be confirmed by the user (recommended).
  2179. When nil, the completion must match an existing entry.
  2180. Note that, if the new heading is not seen by the criteria
  2181. listed in `org-refile-targets', multiple instances of the same
  2182. heading would be created by trying again to file under the new
  2183. heading."
  2184. :group 'org-refile
  2185. :type '(choice
  2186. (const :tag "Never" nil)
  2187. (const :tag "Always" t)
  2188. (const :tag "Prompt for confirmation" confirm)))
  2189. (defcustom org-refile-active-region-within-subtree nil
  2190. "Non-nil means also refile active region within a subtree.
  2191. By default `org-refile' doesn't allow refiling regions if they
  2192. don't contain a set of subtrees, but it might be convenient to
  2193. do so sometimes: in that case, the first line of the region is
  2194. converted to a headline before refiling."
  2195. :group 'org-refile
  2196. :version "24.1"
  2197. :type 'boolean)
  2198. (defgroup org-todo nil
  2199. "Options concerning TODO items in Org mode."
  2200. :tag "Org TODO"
  2201. :group 'org)
  2202. (defgroup org-progress nil
  2203. "Options concerning Progress logging in Org mode."
  2204. :tag "Org Progress"
  2205. :group 'org-time)
  2206. (defvar org-todo-interpretation-widgets
  2207. '((:tag "Sequence (cycling hits every state)" sequence)
  2208. (:tag "Type (cycling directly to DONE)" type))
  2209. "The available interpretation symbols for customizing `org-todo-keywords'.
  2210. Interested libraries should add to this list.")
  2211. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2212. "List of TODO entry keyword sequences and their interpretation.
  2213. \\<org-mode-map>This is a list of sequences.
  2214. Each sequence starts with a symbol, either `sequence' or `type',
  2215. indicating if the keywords should be interpreted as a sequence of
  2216. action steps, or as different types of TODO items. The first
  2217. keywords are states requiring action - these states will select a headline
  2218. for inclusion into the global TODO list Org produces. If one of the
  2219. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2220. signify that no further action is necessary. If \"|\" is not found,
  2221. the last keyword is treated as the only DONE state of the sequence.
  2222. The command `\\[org-todo]' cycles an entry through these states, and one
  2223. additional state where no keyword is present. For details about this
  2224. cycling, see the manual.
  2225. TODO keywords and interpretation can also be set on a per-file basis with
  2226. the special #+SEQ_TODO and #+TYP_TODO lines.
  2227. Each keyword can optionally specify a character for fast state selection
  2228. \(in combination with the variable `org-use-fast-todo-selection')
  2229. and specifiers for state change logging, using the same syntax that
  2230. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2231. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2232. indicates to record a time stamp each time this state is selected.
  2233. Each keyword may also specify if a timestamp or a note should be
  2234. recorded when entering or leaving the state, by adding additional
  2235. characters in the parenthesis after the keyword. This looks like this:
  2236. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2237. record only the time of the state change. With X and Y being either
  2238. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2239. Y when leaving the state if and only if the *target* state does not
  2240. define X. You may omit any of the fast-selection key or X or /Y,
  2241. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2242. For backward compatibility, this variable may also be just a list
  2243. of keywords. In this case the interpretation (sequence or type) will be
  2244. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2245. :group 'org-todo
  2246. :group 'org-keywords
  2247. :type '(choice
  2248. (repeat :tag "Old syntax, just keywords"
  2249. (string :tag "Keyword"))
  2250. (repeat :tag "New syntax"
  2251. (cons
  2252. (choice
  2253. :tag "Interpretation"
  2254. ;;Quick and dirty way to see
  2255. ;;`org-todo-interpretations'. This takes the
  2256. ;;place of item arguments
  2257. :convert-widget
  2258. (lambda (widget)
  2259. (widget-put widget
  2260. :args (mapcar
  2261. (lambda (x)
  2262. (widget-convert
  2263. (cons 'const x)))
  2264. org-todo-interpretation-widgets))
  2265. widget))
  2266. (repeat
  2267. (string :tag "Keyword"))))))
  2268. (defvar-local org-todo-keywords-1 nil
  2269. "All TODO and DONE keywords active in a buffer.")
  2270. (defvar org-todo-keywords-for-agenda nil)
  2271. (defvar org-done-keywords-for-agenda nil)
  2272. (defvar org-todo-keyword-alist-for-agenda nil)
  2273. (defvar org-tag-alist-for-agenda nil
  2274. "Alist of all tags from all agenda files.")
  2275. (defvar org-tag-groups-alist-for-agenda nil
  2276. "Alist of all groups tags from all current agenda files.")
  2277. (defvar-local org-tag-groups-alist nil)
  2278. (defvar org-agenda-contributing-files nil)
  2279. (defvar-local org-current-tag-alist nil
  2280. "Alist of all tag groups in current buffer.
  2281. This variable takes into consideration `org-tag-alist',
  2282. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2283. (defvar-local org-not-done-keywords nil)
  2284. (defvar-local org-done-keywords nil)
  2285. (defvar-local org-todo-heads nil)
  2286. (defvar-local org-todo-sets nil)
  2287. (defvar-local org-todo-log-states nil)
  2288. (defvar-local org-todo-kwd-alist nil)
  2289. (defvar-local org-todo-key-alist nil)
  2290. (defvar-local org-todo-key-trigger nil)
  2291. (defcustom org-todo-interpretation 'sequence
  2292. "Controls how TODO keywords are interpreted.
  2293. This variable is in principle obsolete and is only used for
  2294. backward compatibility, if the interpretation of todo keywords is
  2295. not given already in `org-todo-keywords'. See that variable for
  2296. more information."
  2297. :group 'org-todo
  2298. :group 'org-keywords
  2299. :type '(choice (const sequence)
  2300. (const type)))
  2301. (defcustom org-use-fast-todo-selection t
  2302. "\\<org-mode-map>\
  2303. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2304. This variable describes if and under what circumstances the cycling
  2305. mechanism for TODO keywords will be replaced by a single-key, direct
  2306. selection scheme.
  2307. When nil, fast selection is never used.
  2308. When the symbol `prefix', it will be used when `org-todo' is called
  2309. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2310. in an Org buffer, and
  2311. `\\[universal-argument] t' in an agenda buffer.
  2312. When t, fast selection is used by default. In this case, the prefix
  2313. argument forces cycling instead.
  2314. In all cases, the special interface is only used if access keys have
  2315. actually been assigned by the user, i.e. if keywords in the configuration
  2316. are followed by a letter in parenthesis, like TODO(t)."
  2317. :group 'org-todo
  2318. :type '(choice
  2319. (const :tag "Never" nil)
  2320. (const :tag "By default" t)
  2321. (const :tag "Only with C-u C-c C-t" prefix)))
  2322. (defcustom org-provide-todo-statistics t
  2323. "Non-nil means update todo statistics after insert and toggle.
  2324. ALL-HEADLINES means update todo statistics by including headlines
  2325. with no TODO keyword as well, counting them as not done.
  2326. A list of TODO keywords means the same, but skip keywords that are
  2327. not in this list.
  2328. When set to a list of two lists, the first list contains keywords
  2329. to consider as TODO keywords, the second list contains keywords
  2330. to consider as DONE keywords.
  2331. When this is set, todo statistics is updated in the parent of the
  2332. current entry each time a todo state is changed."
  2333. :group 'org-todo
  2334. :type '(choice
  2335. (const :tag "Yes, only for TODO entries" t)
  2336. (const :tag "Yes, including all entries" all-headlines)
  2337. (repeat :tag "Yes, for TODOs in this list"
  2338. (string :tag "TODO keyword"))
  2339. (list :tag "Yes, for TODOs and DONEs in these lists"
  2340. (repeat (string :tag "TODO keyword"))
  2341. (repeat (string :tag "DONE keyword")))
  2342. (other :tag "No TODO statistics" nil)))
  2343. (defcustom org-hierarchical-todo-statistics t
  2344. "Non-nil means TODO statistics covers just direct children.
  2345. When nil, all entries in the subtree are considered.
  2346. This has only an effect if `org-provide-todo-statistics' is set.
  2347. To set this to nil for only a single subtree, use a COOKIE_DATA
  2348. property and include the word \"recursive\" into the value."
  2349. :group 'org-todo
  2350. :type 'boolean)
  2351. (defcustom org-after-todo-state-change-hook nil
  2352. "Hook which is run after the state of a TODO item was changed.
  2353. The new state (a string with a TODO keyword, or nil) is available in the
  2354. Lisp variable `org-state'."
  2355. :group 'org-todo
  2356. :type 'hook)
  2357. (defvar org-blocker-hook nil
  2358. "Hook for functions that are allowed to block a state change.
  2359. Functions in this hook should not modify the buffer.
  2360. Each function gets as its single argument a property list,
  2361. see `org-trigger-hook' for more information about this list.
  2362. If any of the functions in this hook returns nil, the state change
  2363. is blocked.")
  2364. (defvar org-trigger-hook nil
  2365. "Hook for functions that are triggered by a state change.
  2366. Each function gets as its single argument a property list with at
  2367. least the following elements:
  2368. (:type type-of-change :position pos-at-entry-start
  2369. :from old-state :to new-state)
  2370. Depending on the type, more properties may be present.
  2371. This mechanism is currently implemented for:
  2372. TODO state changes
  2373. ------------------
  2374. :type todo-state-change
  2375. :from previous state (keyword as a string), or nil, or a symbol
  2376. `todo' or `done', to indicate the general type of state.
  2377. :to new state, like in :from")
  2378. (defcustom org-enforce-todo-dependencies nil
  2379. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2380. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2381. be blocked if any prior sibling is not yet done.
  2382. Finally, if the parent is blocked because of ordered siblings of its own,
  2383. the child will also be blocked."
  2384. :set (lambda (var val)
  2385. (set var val)
  2386. (if val
  2387. (add-hook 'org-blocker-hook
  2388. 'org-block-todo-from-children-or-siblings-or-parent)
  2389. (remove-hook 'org-blocker-hook
  2390. 'org-block-todo-from-children-or-siblings-or-parent)))
  2391. :group 'org-todo
  2392. :type 'boolean)
  2393. (defcustom org-enforce-todo-checkbox-dependencies nil
  2394. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2395. When this is nil, checkboxes have no influence on switching TODO states.
  2396. When non-nil, you first need to check off all check boxes before the TODO
  2397. entry can be switched to DONE.
  2398. This variable needs to be set before org.el is loaded, and you need to
  2399. restart Emacs after a change to make the change effective. The only way
  2400. to change is while Emacs is running is through the customize interface."
  2401. :set (lambda (var val)
  2402. (set var val)
  2403. (if val
  2404. (add-hook 'org-blocker-hook
  2405. 'org-block-todo-from-checkboxes)
  2406. (remove-hook 'org-blocker-hook
  2407. 'org-block-todo-from-checkboxes)))
  2408. :group 'org-todo
  2409. :type 'boolean)
  2410. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2411. "Non-nil means inserting a TODO heading is treated as state change.
  2412. So when the command `\\[org-insert-todo-heading]' is used, state change
  2413. logging will apply if appropriate. When nil, the new TODO item will
  2414. be inserted directly, and no logging will take place."
  2415. :group 'org-todo
  2416. :type 'boolean)
  2417. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2418. "Non-nil means switching TODO states with S-cursor counts as state change.
  2419. This is the default behavior. However, setting this to nil allows a
  2420. convenient way to select a TODO state and bypass any logging associated
  2421. with that."
  2422. :group 'org-todo
  2423. :type 'boolean)
  2424. (defcustom org-todo-state-tags-triggers nil
  2425. "Tag changes that should be triggered by TODO state changes.
  2426. This is a list. Each entry is
  2427. (state-change (tag . flag) .......)
  2428. State-change can be a string with a state, and empty string to indicate the
  2429. state that has no TODO keyword, or it can be one of the symbols `todo'
  2430. or `done', meaning any not-done or done state, respectively."
  2431. :group 'org-todo
  2432. :group 'org-tags
  2433. :type '(repeat
  2434. (cons (choice :tag "When changing to"
  2435. (const :tag "Not-done state" todo)
  2436. (const :tag "Done state" done)
  2437. (string :tag "State"))
  2438. (repeat
  2439. (cons :tag "Tag action"
  2440. (string :tag "Tag")
  2441. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2442. (defcustom org-log-done nil
  2443. "Information to record when a task moves to the DONE state.
  2444. Possible values are:
  2445. nil Don't add anything, just change the keyword
  2446. time Add a time stamp to the task
  2447. note Prompt for a note and add it with template `org-log-note-headings'
  2448. This option can also be set with on a per-file-basis with
  2449. #+STARTUP: nologdone
  2450. #+STARTUP: logdone
  2451. #+STARTUP: lognotedone
  2452. You can have local logging settings for a subtree by setting the LOGGING
  2453. property to one or more of these keywords."
  2454. :group 'org-todo
  2455. :group 'org-progress
  2456. :type '(choice
  2457. (const :tag "No logging" nil)
  2458. (const :tag "Record CLOSED timestamp" time)
  2459. (const :tag "Record CLOSED timestamp with note." note)))
  2460. ;; Normalize old uses of org-log-done.
  2461. (cond
  2462. ((eq org-log-done t) (setq org-log-done 'time))
  2463. ((and (listp org-log-done) (memq 'done org-log-done))
  2464. (setq org-log-done 'note)))
  2465. (defcustom org-log-reschedule nil
  2466. "Information to record when the scheduling date of a tasks is modified.
  2467. Possible values are:
  2468. nil Don't add anything, just change the date
  2469. time Add a time stamp to the task
  2470. note Prompt for a note and add it with template `org-log-note-headings'
  2471. This option can also be set with on a per-file-basis with
  2472. #+STARTUP: nologreschedule
  2473. #+STARTUP: logreschedule
  2474. #+STARTUP: lognotereschedule"
  2475. :group 'org-todo
  2476. :group 'org-progress
  2477. :type '(choice
  2478. (const :tag "No logging" nil)
  2479. (const :tag "Record timestamp" time)
  2480. (const :tag "Record timestamp with note." note)))
  2481. (defcustom org-log-redeadline nil
  2482. "Information to record when the deadline date of a tasks is modified.
  2483. Possible values are:
  2484. nil Don't add anything, just change the date
  2485. time Add a time stamp to the task
  2486. note Prompt for a note and add it with template `org-log-note-headings'
  2487. This option can also be set with on a per-file-basis with
  2488. #+STARTUP: nologredeadline
  2489. #+STARTUP: logredeadline
  2490. #+STARTUP: lognoteredeadline
  2491. You can have local logging settings for a subtree by setting the LOGGING
  2492. property to one or more of these keywords."
  2493. :group 'org-todo
  2494. :group 'org-progress
  2495. :type '(choice
  2496. (const :tag "No logging" nil)
  2497. (const :tag "Record timestamp" time)
  2498. (const :tag "Record timestamp with note." note)))
  2499. (defcustom org-log-note-clock-out nil
  2500. "Non-nil means record a note when clocking out of an item.
  2501. This can also be configured on a per-file basis by adding one of
  2502. the following lines anywhere in the buffer:
  2503. #+STARTUP: lognoteclock-out
  2504. #+STARTUP: nolognoteclock-out"
  2505. :group 'org-todo
  2506. :group 'org-progress
  2507. :type 'boolean)
  2508. (defcustom org-log-done-with-time t
  2509. "Non-nil means the CLOSED time stamp will contain date and time.
  2510. When nil, only the date will be recorded."
  2511. :group 'org-progress
  2512. :type 'boolean)
  2513. (defcustom org-log-note-headings
  2514. '((done . "CLOSING NOTE %t")
  2515. (state . "State %-12s from %-12S %t")
  2516. (note . "Note taken on %t")
  2517. (reschedule . "Rescheduled from %S on %t")
  2518. (delschedule . "Not scheduled, was %S on %t")
  2519. (redeadline . "New deadline from %S on %t")
  2520. (deldeadline . "Removed deadline, was %S on %t")
  2521. (refile . "Refiled on %t")
  2522. (clock-out . ""))
  2523. "Headings for notes added to entries.
  2524. The value is an alist, with the car being a symbol indicating the
  2525. note context, and the cdr is the heading to be used. The heading
  2526. may also be the empty string. The following placeholders can be
  2527. used:
  2528. %t a time stamp.
  2529. %T an active time stamp instead the default inactive one
  2530. %d a short-format time stamp.
  2531. %D an active short-format time stamp.
  2532. %s the new TODO state or time stamp (inactive), in double quotes.
  2533. %S the old TODO state or time stamp (inactive), in double quotes.
  2534. %u the user name.
  2535. %U full user name.
  2536. In fact, it is not a good idea to change the `state' entry,
  2537. because Agenda Log mode depends on the format of these entries."
  2538. :group 'org-todo
  2539. :group 'org-progress
  2540. :type '(list :greedy t
  2541. (cons (const :tag "Heading when closing an item" done) string)
  2542. (cons (const :tag
  2543. "Heading when changing todo state (todo sequence only)"
  2544. state) string)
  2545. (cons (const :tag "Heading when just taking a note" note) string)
  2546. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2547. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2548. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2549. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2550. (cons (const :tag "Heading when refiling" refile) string)
  2551. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2552. (unless (assq 'note org-log-note-headings)
  2553. (push '(note . "%t") org-log-note-headings))
  2554. (defcustom org-log-into-drawer nil
  2555. "Non-nil means insert state change notes and time stamps into a drawer.
  2556. When nil, state changes notes will be inserted after the headline and
  2557. any scheduling and clock lines, but not inside a drawer.
  2558. The value of this variable should be the name of the drawer to use.
  2559. LOGBOOK is proposed as the default drawer for this purpose, you can
  2560. also set this to a string to define the drawer of your choice.
  2561. A value of t is also allowed, representing \"LOGBOOK\".
  2562. A value of t or nil can also be set with on a per-file-basis with
  2563. #+STARTUP: logdrawer
  2564. #+STARTUP: nologdrawer
  2565. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2566. will be ignored.
  2567. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2568. a subtree.
  2569. Do not check directly this variable in a Lisp program. Call
  2570. function `org-log-into-drawer' instead."
  2571. :group 'org-todo
  2572. :group 'org-progress
  2573. :type '(choice
  2574. (const :tag "Not into a drawer" nil)
  2575. (const :tag "LOGBOOK" t)
  2576. (string :tag "Other")))
  2577. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2578. (defun org-log-into-drawer ()
  2579. "Name of the log drawer, as a string, or nil.
  2580. This is the value of `org-log-into-drawer'. However, if the
  2581. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2582. be used instead of the default value."
  2583. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2584. (cond ((equal p "nil") nil)
  2585. ((equal p "t") "LOGBOOK")
  2586. ((stringp p) p)
  2587. (p "LOGBOOK")
  2588. ((stringp org-log-into-drawer) org-log-into-drawer)
  2589. (org-log-into-drawer "LOGBOOK"))))
  2590. (defcustom org-log-state-notes-insert-after-drawers nil
  2591. "Non-nil means insert state change notes after any drawers in entry.
  2592. Only the drawers that *immediately* follow the headline and the
  2593. deadline/scheduled line are skipped.
  2594. When nil, insert notes right after the heading and perhaps the line
  2595. with deadline/scheduling if present.
  2596. This variable will have no effect if `org-log-into-drawer' is
  2597. set."
  2598. :group 'org-todo
  2599. :group 'org-progress
  2600. :type 'boolean)
  2601. (defcustom org-log-states-order-reversed t
  2602. "Non-nil means the latest state note will be directly after heading.
  2603. When nil, the state change notes will be ordered according to time.
  2604. This option can also be set with on a per-file-basis with
  2605. #+STARTUP: logstatesreversed
  2606. #+STARTUP: nologstatesreversed"
  2607. :group 'org-todo
  2608. :group 'org-progress
  2609. :type 'boolean)
  2610. (defcustom org-todo-repeat-to-state nil
  2611. "The TODO state to which a repeater should return the repeating task.
  2612. By default this is the first task of a TODO sequence or the
  2613. previous state of a TYPE_TODO set. But you can specify to use
  2614. the previous state in a TODO sequence or a string.
  2615. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2616. entry, which has precedence over this option."
  2617. :group 'org-todo
  2618. :version "24.1"
  2619. :type '(choice (const :tag "Use the previous TODO state" t)
  2620. (const :tag "Use the head of the TODO sequence" nil)
  2621. (string :tag "Use a specific TODO state")))
  2622. (defcustom org-log-repeat 'time
  2623. "Non-nil means record moving through the DONE state when triggering repeat.
  2624. An auto-repeating task is immediately switched back to TODO when
  2625. marked DONE. If you are not logging state changes (by adding \"@\"
  2626. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2627. record a closing note, there will be no record of the task moving
  2628. through DONE. This variable forces taking a note anyway.
  2629. nil Don't force a record
  2630. time Record a time stamp
  2631. note Prompt for a note and add it with template `org-log-note-headings'
  2632. This option can also be set with on a per-file-basis with
  2633. #+STARTUP: nologrepeat
  2634. #+STARTUP: logrepeat
  2635. #+STARTUP: lognoterepeat
  2636. You can have local logging settings for a subtree by setting the LOGGING
  2637. property to one or more of these keywords."
  2638. :group 'org-todo
  2639. :group 'org-progress
  2640. :type '(choice
  2641. (const :tag "Don't force a record" nil)
  2642. (const :tag "Force recording the DONE state" time)
  2643. (const :tag "Force recording a note with the DONE state" note)))
  2644. (defgroup org-priorities nil
  2645. "Priorities in Org mode."
  2646. :tag "Org Priorities"
  2647. :group 'org-todo)
  2648. (defcustom org-enable-priority-commands t
  2649. "Non-nil means priority commands are active.
  2650. When nil, these commands will be disabled, so that you never accidentally
  2651. set a priority."
  2652. :group 'org-priorities
  2653. :type 'boolean)
  2654. (defcustom org-highest-priority ?A
  2655. "The highest priority of TODO items. A character like ?A, ?B etc.
  2656. Must have a smaller ASCII number than `org-lowest-priority'."
  2657. :group 'org-priorities
  2658. :type 'character)
  2659. (defcustom org-lowest-priority ?C
  2660. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2661. Must have a larger ASCII number than `org-highest-priority'."
  2662. :group 'org-priorities
  2663. :type 'character)
  2664. (defcustom org-default-priority ?B
  2665. "The default priority of TODO items.
  2666. This is the priority an item gets if no explicit priority is given.
  2667. When starting to cycle on an empty priority the first step in the cycle
  2668. depends on `org-priority-start-cycle-with-default'. The resulting first
  2669. step priority must not exceed the range from `org-highest-priority' to
  2670. `org-lowest-priority' which means that `org-default-priority' has to be
  2671. in this range exclusive or inclusive the range boundaries. Else the
  2672. first step refuses to set the default and the second will fall back
  2673. to (depending on the command used) the highest or lowest priority."
  2674. :group 'org-priorities
  2675. :type 'character)
  2676. (defcustom org-priority-start-cycle-with-default t
  2677. "Non-nil means start with default priority when starting to cycle.
  2678. When this is nil, the first step in the cycle will be (depending on the
  2679. command used) one higher or lower than the default priority.
  2680. See also `org-default-priority'."
  2681. :group 'org-priorities
  2682. :type 'boolean)
  2683. (defcustom org-get-priority-function nil
  2684. "Function to extract the priority from a string.
  2685. The string is normally the headline. If this is nil Org computes the
  2686. priority from the priority cookie like [#A] in the headline. It returns
  2687. an integer, increasing by 1000 for each priority level.
  2688. The user can set a different function here, which should take a string
  2689. as an argument and return the numeric priority."
  2690. :group 'org-priorities
  2691. :version "24.1"
  2692. :type '(choice
  2693. (const nil)
  2694. (function)))
  2695. (defgroup org-time nil
  2696. "Options concerning time stamps and deadlines in Org mode."
  2697. :tag "Org Time"
  2698. :group 'org)
  2699. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2700. "Number of minutes to round time stamps to.
  2701. \\<org-mode-map>\
  2702. These are two values, the first applies when first creating a time stamp.
  2703. The second applies when changing it with the commands `S-up' and `S-down'.
  2704. When changing the time stamp, this means that it will change in steps
  2705. of N minutes, as given by the second value.
  2706. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2707. numbers should be factors of 60, so for example 5, 10, 15.
  2708. When this is larger than 1, you can still force an exact time stamp by using
  2709. a double prefix argument to a time stamp command like \
  2710. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2711. and by using a prefix arg to `S-up/down' to specify the exact number
  2712. of minutes to shift."
  2713. :group 'org-time
  2714. :get (lambda (var) ; Make sure both elements are there
  2715. (if (integerp (default-value var))
  2716. (list (default-value var) 5)
  2717. (default-value var)))
  2718. :type '(list
  2719. (integer :tag "when inserting times")
  2720. (integer :tag "when modifying times")))
  2721. ;; Normalize old customizations of this variable.
  2722. (when (integerp org-time-stamp-rounding-minutes)
  2723. (setq org-time-stamp-rounding-minutes
  2724. (list org-time-stamp-rounding-minutes
  2725. org-time-stamp-rounding-minutes)))
  2726. (defcustom org-display-custom-times nil
  2727. "Non-nil means overlay custom formats over all time stamps.
  2728. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2729. To turn this on on a per-file basis, insert anywhere in the file:
  2730. #+STARTUP: customtime"
  2731. :group 'org-time
  2732. :set 'set-default
  2733. :type 'sexp)
  2734. (make-variable-buffer-local 'org-display-custom-times)
  2735. (defcustom org-time-stamp-custom-formats
  2736. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2737. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2738. These are overlaid over the default ISO format if the variable
  2739. `org-display-custom-times' is set. Time like %H:%M should be at the
  2740. end of the second format. The custom formats are also honored by export
  2741. commands, if custom time display is turned on at the time of export."
  2742. :group 'org-time
  2743. :type 'sexp)
  2744. (defun org-time-stamp-format (&optional long inactive)
  2745. "Get the right format for a time string."
  2746. (let ((f (if long (cdr org-time-stamp-formats)
  2747. (car org-time-stamp-formats))))
  2748. (if inactive
  2749. (concat "[" (substring f 1 -1) "]")
  2750. f)))
  2751. (defcustom org-deadline-warning-days 14
  2752. "Number of days before expiration during which a deadline becomes active.
  2753. This variable governs the display in sparse trees and in the agenda.
  2754. When 0 or negative, it means use this number (the absolute value of it)
  2755. even if a deadline has a different individual lead time specified.
  2756. Custom commands can set this variable in the options section."
  2757. :group 'org-time
  2758. :group 'org-agenda-daily/weekly
  2759. :type 'integer)
  2760. (defcustom org-scheduled-delay-days 0
  2761. "Number of days before a scheduled item becomes active.
  2762. This variable governs the display in sparse trees and in the agenda.
  2763. The default value (i.e. 0) means: don't delay scheduled item.
  2764. When negative, it means use this number (the absolute value of it)
  2765. even if a scheduled item has a different individual delay time
  2766. specified.
  2767. Custom commands can set this variable in the options section."
  2768. :group 'org-time
  2769. :group 'org-agenda-daily/weekly
  2770. :version "24.4"
  2771. :package-version '(Org . "8.0")
  2772. :type 'integer)
  2773. (defcustom org-read-date-prefer-future t
  2774. "Non-nil means assume future for incomplete date input from user.
  2775. This affects the following situations:
  2776. 1. The user gives a month but not a year.
  2777. For example, if it is April and you enter \"feb 2\", this will be read
  2778. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2779. 2. The user gives a day, but no month.
  2780. For example, if today is the 15th, and you enter \"3\", Org will read
  2781. this as the third of *next* month. However, if you enter \"17\",
  2782. it will be considered as *this* month.
  2783. If you set this variable to the symbol `time', then also the following
  2784. will work:
  2785. 3. If the user gives a time.
  2786. If the time is before now, it will be interpreted as tomorrow.
  2787. Currently none of this works for ISO week specifications.
  2788. When this option is nil, the current day, month and year will always be
  2789. used as defaults.
  2790. See also `org-agenda-jump-prefer-future'."
  2791. :group 'org-time
  2792. :type '(choice
  2793. (const :tag "Never" nil)
  2794. (const :tag "Check month and day" t)
  2795. (const :tag "Check month, day, and time" time)))
  2796. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2797. "Should the agenda jump command prefer the future for incomplete dates?
  2798. The default is to do the same as configured in `org-read-date-prefer-future'.
  2799. But you can also set a deviating value here.
  2800. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2801. :group 'org-agenda
  2802. :group 'org-time
  2803. :version "24.1"
  2804. :type '(choice
  2805. (const :tag "Use org-read-date-prefer-future"
  2806. org-read-date-prefer-future)
  2807. (const :tag "Never" nil)
  2808. (const :tag "Always" t)))
  2809. (defcustom org-read-date-force-compatible-dates t
  2810. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2811. Depending on the system Emacs is running on, certain dates cannot
  2812. be represented with the type used internally to represent time.
  2813. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2814. correctly. Some systems allow for earlier dates, some for later,
  2815. some for both. One way to find out it to insert any date into an
  2816. Org buffer, putting the cursor on the year and hitting S-up and
  2817. S-down to test the range.
  2818. When this variable is set to t, the date/time prompt will not let
  2819. you specify dates outside the 1970-2037 range, so it is certain that
  2820. these dates will work in whatever version of Emacs you are
  2821. running, and also that you can move a file from one Emacs implementation
  2822. to another. WHenever Org is forcing the year for you, it will display
  2823. a message and beep.
  2824. When this variable is nil, Org will check if the date is
  2825. representable in the specific Emacs implementation you are using.
  2826. If not, it will force a year, usually the current year, and beep
  2827. to remind you. Currently this setting is not recommended because
  2828. the likelihood that you will open your Org files in an Emacs that
  2829. has limited date range is not negligible.
  2830. A workaround for this problem is to use diary sexp dates for time
  2831. stamps outside of this range."
  2832. :group 'org-time
  2833. :version "24.1"
  2834. :type 'boolean)
  2835. (defcustom org-read-date-display-live t
  2836. "Non-nil means display current interpretation of date prompt live.
  2837. This display will be in an overlay, in the minibuffer."
  2838. :group 'org-time
  2839. :type 'boolean)
  2840. (defcustom org-read-date-popup-calendar t
  2841. "Non-nil means pop up a calendar when prompting for a date.
  2842. In the calendar, the date can be selected with mouse-1. However, the
  2843. minibuffer will also be active, and you can simply enter the date as well.
  2844. When nil, only the minibuffer will be available."
  2845. :group 'org-time
  2846. :type 'boolean)
  2847. (defvaralias 'org-popup-calendar-for-date-prompt
  2848. 'org-read-date-popup-calendar)
  2849. (defcustom org-extend-today-until 0
  2850. "The hour when your day really ends. Must be an integer.
  2851. This has influence for the following applications:
  2852. - When switching the agenda to \"today\". It it is still earlier than
  2853. the time given here, the day recognized as TODAY is actually yesterday.
  2854. - When a date is read from the user and it is still before the time given
  2855. here, the current date and time will be assumed to be yesterday, 23:59.
  2856. Also, timestamps inserted in capture templates follow this rule.
  2857. IMPORTANT: This is a feature whose implementation is and likely will
  2858. remain incomplete. Really, it is only here because past midnight seems to
  2859. be the favorite working time of John Wiegley :-)"
  2860. :group 'org-time
  2861. :type 'integer)
  2862. (defcustom org-use-effective-time nil
  2863. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2864. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2865. \"effective time\" of any timestamps between midnight and 8am will be
  2866. 23:59 of the previous day."
  2867. :group 'org-time
  2868. :version "24.1"
  2869. :type 'boolean)
  2870. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2871. "When non-nil, use the last clock out time for `org-todo'.
  2872. Note that this option has precedence over the combined use of
  2873. `org-use-effective-time' and `org-extend-today-until'."
  2874. :group 'org-time
  2875. :version "24.4"
  2876. :package-version '(Org . "8.0")
  2877. :type 'boolean)
  2878. (defcustom org-edit-timestamp-down-means-later nil
  2879. "Non-nil means S-down will increase the time in a time stamp.
  2880. When nil, S-up will increase."
  2881. :group 'org-time
  2882. :type 'boolean)
  2883. (defcustom org-calendar-follow-timestamp-change t
  2884. "Non-nil means make the calendar window follow timestamp changes.
  2885. When a timestamp is modified and the calendar window is visible, it will be
  2886. moved to the new date."
  2887. :group 'org-time
  2888. :type 'boolean)
  2889. (defgroup org-tags nil
  2890. "Options concerning tags in Org mode."
  2891. :tag "Org Tags"
  2892. :group 'org)
  2893. (defcustom org-tag-alist nil
  2894. "Default tags available in Org files.
  2895. The value of this variable is an alist. Associations either:
  2896. (TAG)
  2897. (TAG . SELECT)
  2898. (SPECIAL)
  2899. where TAG is a tag as a string, SELECT is character, used to
  2900. select that tag through the fast tag selection interface, and
  2901. SPECIAL is one of the following keywords: `:startgroup',
  2902. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2903. `:newline'. These keywords are used to define a hierarchy of
  2904. tags. See manual for details.
  2905. When this variable is nil, Org mode bases tag input on what is
  2906. already in the buffer. The value can be overridden locally by
  2907. using a TAGS keyword, e.g.,
  2908. #+TAGS: tag1 tag2
  2909. See also `org-tag-persistent-alist' to sidestep this behavior."
  2910. :group 'org-tags
  2911. :type '(repeat
  2912. (choice
  2913. (cons :tag "Tag with key"
  2914. (string :tag "Tag name")
  2915. (character :tag "Access char"))
  2916. (list :tag "Tag" (string :tag "Tag name"))
  2917. (const :tag "Start radio group" (:startgroup))
  2918. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2919. (const :tag "Group tags delimiter" (:grouptags))
  2920. (const :tag "End radio group" (:endgroup))
  2921. (const :tag "End tag group, non distinct" (:endgrouptag))
  2922. (const :tag "New line" (:newline)))))
  2923. (defcustom org-tag-persistent-alist nil
  2924. "Tags always available in Org files.
  2925. The value of this variable is an alist. Associations either:
  2926. (TAG)
  2927. (TAG . SELECT)
  2928. (SPECIAL)
  2929. where TAG is a tag as a string, SELECT is a character, used to
  2930. select that tag through the fast tag selection interface, and
  2931. SPECIAL is one of the following keywords: `:startgroup',
  2932. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2933. `:newline'. These keywords are used to define a hierarchy of
  2934. tags. See manual for details.
  2935. Unlike to `org-tag-alist', tags defined in this variable do not
  2936. depend on a local TAGS keyword. Instead, to disable these tags
  2937. on a per-file basis, insert anywhere in the file:
  2938. #+STARTUP: noptag"
  2939. :group 'org-tags
  2940. :type '(repeat
  2941. (choice
  2942. (cons :tag "Tag with key"
  2943. (string :tag "Tag name")
  2944. (character :tag "Access char"))
  2945. (list :tag "Tag" (string :tag "Tag name"))
  2946. (const :tag "Start radio group" (:startgroup))
  2947. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2948. (const :tag "Group tags delimiter" (:grouptags))
  2949. (const :tag "End radio group" (:endgroup))
  2950. (const :tag "End tag group, non distinct" (:endgrouptag))
  2951. (const :tag "New line" (:newline)))))
  2952. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2953. "If non-nil, always offer completion for all tags of all agenda files.
  2954. Instead of customizing this variable directly, you might want to
  2955. set it locally for capture buffers, because there no list of
  2956. tags in that file can be created dynamically (there are none).
  2957. (add-hook \\='org-capture-mode-hook
  2958. (lambda ()
  2959. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2960. :group 'org-tags
  2961. :version "24.1"
  2962. :type 'boolean)
  2963. (defvar org-file-tags nil
  2964. "List of tags that can be inherited by all entries in the file.
  2965. The tags will be inherited if the variable `org-use-tag-inheritance'
  2966. says they should be.
  2967. This variable is populated from #+FILETAGS lines.")
  2968. (defcustom org-use-fast-tag-selection 'auto
  2969. "Non-nil means use fast tag selection scheme.
  2970. This is a special interface to select and deselect tags with single keys.
  2971. When nil, fast selection is never used.
  2972. When the symbol `auto', fast selection is used if and only if selection
  2973. characters for tags have been configured, either through the variable
  2974. `org-tag-alist' or through a #+TAGS line in the buffer.
  2975. When t, fast selection is always used and selection keys are assigned
  2976. automatically if necessary."
  2977. :group 'org-tags
  2978. :type '(choice
  2979. (const :tag "Always" t)
  2980. (const :tag "Never" nil)
  2981. (const :tag "When selection characters are configured" auto)))
  2982. (defcustom org-fast-tag-selection-single-key nil
  2983. "Non-nil means fast tag selection exits after first change.
  2984. When nil, you have to press RET to exit it.
  2985. During fast tag selection, you can toggle this flag with `C-c'.
  2986. This variable can also have the value `expert'. In this case, the window
  2987. displaying the tags menu is not even shown, until you press C-c again."
  2988. :group 'org-tags
  2989. :type '(choice
  2990. (const :tag "No" nil)
  2991. (const :tag "Yes" t)
  2992. (const :tag "Expert" expert)))
  2993. (defvar org-fast-tag-selection-include-todo nil
  2994. "Non-nil means fast tags selection interface will also offer TODO states.
  2995. This is an undocumented feature, you should not rely on it.")
  2996. (defcustom org-tags-column -77
  2997. "The column to which tags should be indented in a headline.
  2998. If this number is positive, it specifies the column. If it is negative,
  2999. it means that the tags should be flushright to that column. For example,
  3000. -80 works well for a normal 80 character screen.
  3001. When 0, place tags directly after headline text, with only one space in
  3002. between."
  3003. :group 'org-tags
  3004. :type 'integer)
  3005. (defcustom org-auto-align-tags t
  3006. "Non-nil keeps tags aligned when modifying headlines.
  3007. Some operations (i.e. demoting) change the length of a headline and
  3008. therefore shift the tags around. With this option turned on, after
  3009. each such operation the tags are again aligned to `org-tags-column'."
  3010. :group 'org-tags
  3011. :type 'boolean)
  3012. (defcustom org-use-tag-inheritance t
  3013. "Non-nil means tags in levels apply also for sublevels.
  3014. When nil, only the tags directly given in a specific line apply there.
  3015. This may also be a list of tags that should be inherited, or a regexp that
  3016. matches tags that should be inherited. Additional control is possible
  3017. with the variable `org-tags-exclude-from-inheritance' which gives an
  3018. explicit list of tags to be excluded from inheritance, even if the value of
  3019. `org-use-tag-inheritance' would select it for inheritance.
  3020. If this option is t, a match early-on in a tree can lead to a large
  3021. number of matches in the subtree when constructing the agenda or creating
  3022. a sparse tree. If you only want to see the first match in a tree during
  3023. a search, check out the variable `org-tags-match-list-sublevels'."
  3024. :group 'org-tags
  3025. :type '(choice
  3026. (const :tag "Not" nil)
  3027. (const :tag "Always" t)
  3028. (repeat :tag "Specific tags" (string :tag "Tag"))
  3029. (regexp :tag "Tags matched by regexp")))
  3030. (defcustom org-tags-exclude-from-inheritance nil
  3031. "List of tags that should never be inherited.
  3032. This is a way to exclude a few tags from inheritance. For way to do
  3033. the opposite, to actively allow inheritance for selected tags,
  3034. see the variable `org-use-tag-inheritance'."
  3035. :group 'org-tags
  3036. :type '(repeat (string :tag "Tag")))
  3037. (defun org-tag-inherit-p (tag)
  3038. "Check if TAG is one that should be inherited."
  3039. (cond
  3040. ((member tag org-tags-exclude-from-inheritance) nil)
  3041. ((eq org-use-tag-inheritance t) t)
  3042. ((not org-use-tag-inheritance) nil)
  3043. ((stringp org-use-tag-inheritance)
  3044. (string-match org-use-tag-inheritance tag))
  3045. ((listp org-use-tag-inheritance)
  3046. (member tag org-use-tag-inheritance))
  3047. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3048. (defcustom org-tags-match-list-sublevels t
  3049. "Non-nil means list also sublevels of headlines matching a search.
  3050. This variable applies to tags/property searches, and also to stuck
  3051. projects because this search is based on a tags match as well.
  3052. When set to the symbol `indented', sublevels are indented with
  3053. leading dots.
  3054. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3055. the sublevels of a headline matching a tag search often also match
  3056. the same search. Listing all of them can create very long lists.
  3057. Setting this variable to nil causes subtrees of a match to be skipped.
  3058. This variable is semi-obsolete and probably should always be true. It
  3059. is better to limit inheritance to certain tags using the variables
  3060. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3061. :group 'org-tags
  3062. :type '(choice
  3063. (const :tag "No, don't list them" nil)
  3064. (const :tag "Yes, do list them" t)
  3065. (const :tag "List them, indented with leading dots" indented)))
  3066. (defcustom org-tags-sort-function nil
  3067. "When set, tags are sorted using this function as a comparator."
  3068. :group 'org-tags
  3069. :type '(choice
  3070. (const :tag "No sorting" nil)
  3071. (const :tag "Alphabetical" org-string-collate-lessp)
  3072. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  3073. (function :tag "Custom function" nil)))
  3074. (defvar org-tags-history nil
  3075. "History of minibuffer reads for tags.")
  3076. (defvar org-last-tags-completion-table nil
  3077. "The last used completion table for tags.")
  3078. (defvar org-after-tags-change-hook nil
  3079. "Hook that is run after the tags in a line have changed.")
  3080. (defgroup org-properties nil
  3081. "Options concerning properties in Org mode."
  3082. :tag "Org Properties"
  3083. :group 'org)
  3084. (defcustom org-property-format "%-10s %s"
  3085. "How property key/value pairs should be formatted by `indent-line'.
  3086. When `indent-line' hits a property definition, it will format the line
  3087. according to this format, mainly to make sure that the values are
  3088. lined-up with respect to each other."
  3089. :group 'org-properties
  3090. :type 'string)
  3091. (defcustom org-properties-postprocess-alist nil
  3092. "Alist of properties and functions to adjust inserted values.
  3093. Elements of this alist must be of the form
  3094. ([string] [function])
  3095. where [string] must be a property name and [function] must be a
  3096. lambda expression: this lambda expression must take one argument,
  3097. the value to adjust, and return the new value as a string.
  3098. For example, this element will allow the property \"Remaining\"
  3099. to be updated wrt the relation between the \"Effort\" property
  3100. and the clock summary:
  3101. ((\"Remaining\" (lambda(value)
  3102. (let ((clocksum (org-clock-sum-current-item))
  3103. (effort (org-duration-to-minutes
  3104. (org-entry-get (point) \"Effort\"))))
  3105. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3106. :group 'org-properties
  3107. :version "24.1"
  3108. :type '(alist :key-type (string :tag "Property")
  3109. :value-type (function :tag "Function")))
  3110. (defcustom org-use-property-inheritance nil
  3111. "Non-nil means properties apply also for sublevels.
  3112. This setting is chiefly used during property searches. Turning it on can
  3113. cause significant overhead when doing a search, which is why it is not
  3114. on by default.
  3115. When nil, only the properties directly given in the current entry count.
  3116. When t, every property is inherited. The value may also be a list of
  3117. properties that should have inheritance, or a regular expression matching
  3118. properties that should be inherited.
  3119. However, note that some special properties use inheritance under special
  3120. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3121. and the properties ending in \"_ALL\" when they are used as descriptor
  3122. for valid values of a property.
  3123. Note for programmers:
  3124. When querying an entry with `org-entry-get', you can control if inheritance
  3125. should be used. By default, `org-entry-get' looks only at the local
  3126. properties. You can request inheritance by setting the inherit argument
  3127. to t (to force inheritance) or to `selective' (to respect the setting
  3128. in this variable)."
  3129. :group 'org-properties
  3130. :type '(choice
  3131. (const :tag "Not" nil)
  3132. (const :tag "Always" t)
  3133. (repeat :tag "Specific properties" (string :tag "Property"))
  3134. (regexp :tag "Properties matched by regexp")))
  3135. (defun org-property-inherit-p (property)
  3136. "Return a non-nil value if PROPERTY should be inherited."
  3137. (cond
  3138. ((eq org-use-property-inheritance t) t)
  3139. ((not org-use-property-inheritance) nil)
  3140. ((stringp org-use-property-inheritance)
  3141. (string-match org-use-property-inheritance property))
  3142. ((listp org-use-property-inheritance)
  3143. (member-ignore-case property org-use-property-inheritance))
  3144. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3145. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3146. "The default column format, if no other format has been defined.
  3147. This variable can be set on the per-file basis by inserting a line
  3148. #+COLUMNS: %25ITEM ....."
  3149. :group 'org-properties
  3150. :type 'string)
  3151. (defcustom org-columns-ellipses ".."
  3152. "The ellipses to be used when a field in column view is truncated.
  3153. When this is the empty string, as many characters as possible are shown,
  3154. but then there will be no visual indication that the field has been truncated.
  3155. When this is a string of length N, the last N characters of a truncated
  3156. field are replaced by this string. If the column is narrower than the
  3157. ellipses string, only part of the ellipses string will be shown."
  3158. :group 'org-properties
  3159. :type 'string)
  3160. (defconst org-global-properties-fixed
  3161. '(("VISIBILITY_ALL" . "folded children content all")
  3162. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3163. "List of property/value pairs that can be inherited by any entry.
  3164. These are fixed values, for the preset properties. The user variable
  3165. that can be used to add to this list is `org-global-properties'.
  3166. The entries in this list are cons cells where the car is a property
  3167. name and cdr is a string with the value. If the value represents
  3168. multiple items like an \"_ALL\" property, separate the items by
  3169. spaces.")
  3170. (defcustom org-global-properties nil
  3171. "List of property/value pairs that can be inherited by any entry.
  3172. This list will be combined with the constant `org-global-properties-fixed'.
  3173. The entries in this list are cons cells where the car is a property
  3174. name and cdr is a string with the value.
  3175. You can set buffer-local values for the same purpose in the variable
  3176. `org-file-properties' this by adding lines like
  3177. #+PROPERTY: NAME VALUE"
  3178. :group 'org-properties
  3179. :type '(repeat
  3180. (cons (string :tag "Property")
  3181. (string :tag "Value"))))
  3182. (defvar-local org-file-properties nil
  3183. "List of property/value pairs that can be inherited by any entry.
  3184. Valid for the current buffer.
  3185. This variable is populated from #+PROPERTY lines.")
  3186. (defgroup org-agenda nil
  3187. "Options concerning agenda views in Org mode."
  3188. :tag "Org Agenda"
  3189. :group 'org)
  3190. (defvar-local org-category nil
  3191. "Variable used by Org files to set a category for agenda display.
  3192. Such files should use a file variable to set it, for example
  3193. # -*- mode: org; org-category: \"ELisp\"
  3194. or contain a special line
  3195. #+CATEGORY: ELisp
  3196. If the file does not specify a category, then file's base name
  3197. is used instead.")
  3198. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3199. (defcustom org-agenda-files nil
  3200. "The files to be used for agenda display.
  3201. If an entry is a directory, all files in that directory that are matched
  3202. by `org-agenda-file-regexp' will be part of the file list.
  3203. If the value of the variable is not a list but a single file name, then
  3204. the list of agenda files is actually stored and maintained in that file,
  3205. one agenda file per line. In this file paths can be given relative to
  3206. `org-directory'. Tilde expansion and environment variable substitution
  3207. are also made.
  3208. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3209. and removed with `\\[org-remove-file]'."
  3210. :group 'org-agenda
  3211. :type '(choice
  3212. (repeat :tag "List of files and directories" file)
  3213. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3214. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3215. "Regular expression to match files for `org-agenda-files'.
  3216. If any element in the list in that variable contains a directory instead
  3217. of a normal file, all files in that directory that are matched by this
  3218. regular expression will be included."
  3219. :group 'org-agenda
  3220. :type 'regexp)
  3221. (defcustom org-agenda-text-search-extra-files nil
  3222. "List of extra files to be searched by text search commands.
  3223. These files will be searched in addition to the agenda files by the
  3224. commands `org-search-view' (`\\[org-agenda] s') \
  3225. and `org-occur-in-agenda-files'.
  3226. Note that these files will only be searched for text search commands,
  3227. not for the other agenda views like todo lists, tag searches or the weekly
  3228. agenda. This variable is intended to list notes and possibly archive files
  3229. that should also be searched by these two commands.
  3230. In fact, if the first element in the list is the symbol `agenda-archives',
  3231. then all archive files of all agenda files will be added to the search
  3232. scope."
  3233. :group 'org-agenda
  3234. :type '(set :greedy t
  3235. (const :tag "Agenda Archives" agenda-archives)
  3236. (repeat :inline t (file))))
  3237. (defvaralias 'org-agenda-multi-occur-extra-files
  3238. 'org-agenda-text-search-extra-files)
  3239. (defcustom org-agenda-skip-unavailable-files nil
  3240. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3241. A nil value means to remove them, after a query, from the list."
  3242. :group 'org-agenda
  3243. :type 'boolean)
  3244. (defcustom org-agenda-diary-file 'diary-file
  3245. "File to which to add new entries with the `i' key in agenda and calendar.
  3246. When this is the symbol `diary-file', the functionality in the Emacs
  3247. calendar will be used to add entries to the `diary-file'. But when this
  3248. points to a file, `org-agenda-diary-entry' will be used instead."
  3249. :group 'org-agenda
  3250. :type '(choice
  3251. (const :tag "The standard Emacs diary file" diary-file)
  3252. (file :tag "Special Org file diary entries")))
  3253. (defgroup org-latex nil
  3254. "Options for embedding LaTeX code into Org mode."
  3255. :tag "Org LaTeX"
  3256. :group 'org)
  3257. (defcustom org-format-latex-options
  3258. '(:foreground default :background default :scale 1.0
  3259. :html-foreground "Black" :html-background "Transparent"
  3260. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3261. "Options for creating images from LaTeX fragments.
  3262. This is a property list with the following properties:
  3263. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3264. `default' means use the foreground of the default face.
  3265. `auto' means use the foreground from the text face.
  3266. :background the background color, or \"Transparent\".
  3267. `default' means use the background of the default face.
  3268. `auto' means use the background from the text face.
  3269. :scale a scaling factor for the size of the images, to get more pixels
  3270. :html-foreground, :html-background, :html-scale
  3271. the same numbers for HTML export.
  3272. :matchers a list indicating which matchers should be used to
  3273. find LaTeX fragments. Valid members of this list are:
  3274. \"begin\" find environments
  3275. \"$1\" find single characters surrounded by $.$
  3276. \"$\" find math expressions surrounded by $...$
  3277. \"$$\" find math expressions surrounded by $$....$$
  3278. \"\\(\" find math expressions surrounded by \\(...\\)
  3279. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3280. :group 'org-latex
  3281. :type 'plist)
  3282. (defcustom org-format-latex-signal-error t
  3283. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3284. When nil, just push out a message."
  3285. :group 'org-latex
  3286. :version "24.1"
  3287. :type 'boolean)
  3288. (defcustom org-latex-to-mathml-jar-file nil
  3289. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3290. Use this to specify additional executable file say a jar file.
  3291. When using MathToWeb as the converter, specify the full-path to
  3292. your mathtoweb.jar file."
  3293. :group 'org-latex
  3294. :version "24.1"
  3295. :type '(choice
  3296. (const :tag "None" nil)
  3297. (file :tag "JAR file" :must-match t)))
  3298. (defcustom org-latex-to-mathml-convert-command nil
  3299. "Command to convert LaTeX fragments to MathML.
  3300. Replace format-specifiers in the command as noted below and use
  3301. `shell-command' to convert LaTeX to MathML.
  3302. %j: Executable file in fully expanded form as specified by
  3303. `org-latex-to-mathml-jar-file'.
  3304. %I: Input LaTeX file in fully expanded form.
  3305. %i: The latex fragment to be converted.
  3306. %o: Output MathML file.
  3307. This command is used by `org-create-math-formula'.
  3308. When using MathToWeb as the converter, set this option to
  3309. \"java -jar %j -unicode -force -df %o %I\".
  3310. When using LaTeXML set this option to
  3311. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3312. :group 'org-latex
  3313. :version "24.1"
  3314. :type '(choice
  3315. (const :tag "None" nil)
  3316. (string :tag "\nShell command")))
  3317. (defcustom org-preview-latex-default-process 'dvipng
  3318. "The default process to convert LaTeX fragments to image files.
  3319. All available processes and theirs documents can be found in
  3320. `org-preview-latex-process-alist', which see."
  3321. :group 'org-latex
  3322. :version "26.1"
  3323. :package-version '(Org . "9.0")
  3324. :type 'symbol)
  3325. (defcustom org-preview-latex-process-alist
  3326. '((dvipng
  3327. :programs ("latex" "dvipng")
  3328. :description "dvi > png"
  3329. :message "you need to install the programs: latex and dvipng."
  3330. :image-input-type "dvi"
  3331. :image-output-type "png"
  3332. :image-size-adjust (1.0 . 1.0)
  3333. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3334. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3335. (dvisvgm
  3336. :programs ("latex" "dvisvgm")
  3337. :description "dvi > svg"
  3338. :message "you need to install the programs: latex and dvisvgm."
  3339. :use-xcolor t
  3340. :image-input-type "dvi"
  3341. :image-output-type "svg"
  3342. :image-size-adjust (1.7 . 1.5)
  3343. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3344. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3345. (imagemagick
  3346. :programs ("latex" "convert")
  3347. :description "pdf > png"
  3348. :message "you need to install the programs: latex and imagemagick."
  3349. :use-xcolor t
  3350. :image-input-type "pdf"
  3351. :image-output-type "png"
  3352. :image-size-adjust (1.0 . 1.0)
  3353. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3354. :image-converter
  3355. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3356. "Definitions of external processes for LaTeX previewing.
  3357. Org mode can use some external commands to generate TeX snippet's images for
  3358. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3359. `org-create-formula-image' how to call them.
  3360. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3361. PROPERTIES accepts the following attributes:
  3362. :programs list of strings, required programs.
  3363. :description string, describe the process.
  3364. :message string, message it when required programs cannot be found.
  3365. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3366. :image-output-type string, output file type of image converter (e.g., \"png\").
  3367. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3368. deal with background and foreground color of image.
  3369. Otherwise, dvipng style background and foreground color
  3370. format are generated. You may then refer to them in
  3371. command options with \"%F\" and \"%B\".
  3372. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3373. image size showed in buffer and the cdr element is for
  3374. HTML file. This option is only useful for process
  3375. developers, users should use variable
  3376. `org-format-latex-options' instead.
  3377. :post-clean list of strings, files matched are to be cleaned up once
  3378. the image is generated. When nil, the files with \".dvi\",
  3379. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3380. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3381. be cleaned up.
  3382. :latex-header list of strings, the LaTeX header of the snippet file.
  3383. When nil, the fallback value is used instead, which is
  3384. controlled by `org-format-latex-header',
  3385. `org-latex-default-packages-alist' and
  3386. `org-latex-packages-alist', which see.
  3387. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3388. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3389. replaced with values defined below.
  3390. :image-converter list of image converter commands strings. Each of them is
  3391. given to the shell and supports any of the following
  3392. place-holders defined below.
  3393. Place-holders used by `:image-converter' and `:latex-compiler':
  3394. %f input file name
  3395. %b base name of input file
  3396. %o base directory of input file
  3397. %O absolute output file name
  3398. Place-holders only used by `:image-converter':
  3399. %F foreground of image
  3400. %B background of image
  3401. %D dpi, which is used to adjust image size by some processing commands.
  3402. %S the image size scale ratio, which is used to adjust image size by some
  3403. processing commands."
  3404. :group 'org-latex
  3405. :version "26.1"
  3406. :package-version '(Org . "9.0")
  3407. :type '(alist :tag "LaTeX to image backends"
  3408. :value-type (plist)))
  3409. (defcustom org-preview-latex-image-directory "ltximg/"
  3410. "Path to store latex preview images.
  3411. A relative path here creates many directories relative to the
  3412. processed Org files paths. An absolute path puts all preview
  3413. images at the same place."
  3414. :group 'org-latex
  3415. :version "26.1"
  3416. :package-version '(Org . "9.0")
  3417. :type 'string)
  3418. (defun org-format-latex-mathml-available-p ()
  3419. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3420. (save-match-data
  3421. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3422. org-latex-to-mathml-convert-command)
  3423. (let ((executable (car (split-string
  3424. org-latex-to-mathml-convert-command))))
  3425. (when (executable-find executable)
  3426. (if (string-match
  3427. "%j" org-latex-to-mathml-convert-command)
  3428. (file-readable-p org-latex-to-mathml-jar-file)
  3429. t))))))
  3430. (defcustom org-format-latex-header "\\documentclass{article}
  3431. \\usepackage[usenames]{color}
  3432. \[PACKAGES]
  3433. \[DEFAULT-PACKAGES]
  3434. \\pagestyle{empty} % do not remove
  3435. % The settings below are copied from fullpage.sty
  3436. \\setlength{\\textwidth}{\\paperwidth}
  3437. \\addtolength{\\textwidth}{-3cm}
  3438. \\setlength{\\oddsidemargin}{1.5cm}
  3439. \\addtolength{\\oddsidemargin}{-2.54cm}
  3440. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3441. \\setlength{\\textheight}{\\paperheight}
  3442. \\addtolength{\\textheight}{-\\headheight}
  3443. \\addtolength{\\textheight}{-\\headsep}
  3444. \\addtolength{\\textheight}{-\\footskip}
  3445. \\addtolength{\\textheight}{-3cm}
  3446. \\setlength{\\topmargin}{1.5cm}
  3447. \\addtolength{\\topmargin}{-2.54cm}"
  3448. "The document header used for processing LaTeX fragments.
  3449. It is imperative that this header make sure that no page number
  3450. appears on the page. The package defined in the variables
  3451. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3452. will either replace the placeholder \"[PACKAGES]\" in this
  3453. header, or they will be appended."
  3454. :group 'org-latex
  3455. :type 'string)
  3456. (defun org-set-packages-alist (var val)
  3457. "Set the packages alist and make sure it has 3 elements per entry."
  3458. (set var (mapcar (lambda (x)
  3459. (if (and (consp x) (= (length x) 2))
  3460. (list (car x) (nth 1 x) t)
  3461. x))
  3462. val)))
  3463. (defun org-get-packages-alist (var)
  3464. "Get the packages alist and make sure it has 3 elements per entry."
  3465. (mapcar (lambda (x)
  3466. (if (and (consp x) (= (length x) 2))
  3467. (list (car x) (nth 1 x) t)
  3468. x))
  3469. (default-value var)))
  3470. (defcustom org-latex-default-packages-alist
  3471. '(("AUTO" "inputenc" t ("pdflatex"))
  3472. ("T1" "fontenc" t ("pdflatex"))
  3473. ("" "graphicx" t)
  3474. ("" "grffile" t)
  3475. ("" "longtable" nil)
  3476. ("" "wrapfig" nil)
  3477. ("" "rotating" nil)
  3478. ("normalem" "ulem" t)
  3479. ("" "amsmath" t)
  3480. ("" "textcomp" t)
  3481. ("" "amssymb" t)
  3482. ("" "capt-of" nil)
  3483. ("" "hyperref" nil))
  3484. "Alist of default packages to be inserted in the header.
  3485. Change this only if one of the packages here causes an
  3486. incompatibility with another package you are using.
  3487. The packages in this list are needed by one part or another of
  3488. Org mode to function properly:
  3489. - inputenc, fontenc: for basic font and character selection
  3490. - graphicx: for including images
  3491. - grffile: allow periods and spaces in graphics file names
  3492. - longtable: For multipage tables
  3493. - wrapfig: for figure placement
  3494. - rotating: for sideways figures and tables
  3495. - ulem: for underline and strike-through
  3496. - amsmath: for subscript and superscript and math environments
  3497. - textcomp, amssymb: for various symbols used
  3498. for interpreting the entities in `org-entities'. You can skip
  3499. some of these packages if you don't use any of their symbols.
  3500. - capt-of: for captions outside of floats
  3501. - hyperref: for cross references
  3502. Therefore you should not modify this variable unless you know
  3503. what you are doing. The one reason to change it anyway is that
  3504. you might be loading some other package that conflicts with one
  3505. of the default packages. Each element is either a cell or
  3506. a string.
  3507. A cell is of the format
  3508. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3509. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3510. when compiling LaTeX snippets into images for inclusion into
  3511. non-LaTeX output. COMPILERS is a list of compilers that should
  3512. include the package, see `org-latex-compiler'. If the document
  3513. compiler is not in the list, and the list is non-nil, the package
  3514. will not be inserted in the final document.
  3515. A string will be inserted as-is in the header of the document."
  3516. :group 'org-latex
  3517. :group 'org-export-latex
  3518. :set 'org-set-packages-alist
  3519. :get 'org-get-packages-alist
  3520. :version "26.1"
  3521. :package-version '(Org . "8.3")
  3522. :type '(repeat
  3523. (choice
  3524. (list :tag "options/package pair"
  3525. (string :tag "options")
  3526. (string :tag "package")
  3527. (boolean :tag "Snippet")
  3528. (choice
  3529. (const :tag "For all compilers" nil)
  3530. (repeat :tag "Allowed compiler" string)))
  3531. (string :tag "A line of LaTeX"))))
  3532. (defcustom org-latex-packages-alist nil
  3533. "Alist of packages to be inserted in every LaTeX header.
  3534. These will be inserted after `org-latex-default-packages-alist'.
  3535. Each element is either a cell or a string.
  3536. A cell is of the format:
  3537. (\"options\" \"package\" SNIPPET-FLAG)
  3538. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3539. needed when turning LaTeX snippets into images for inclusion into
  3540. non-LaTeX output.
  3541. A string will be inserted as-is in the header of the document.
  3542. Make sure that you only list packages here which:
  3543. - you want in every file;
  3544. - do not conflict with the setup in `org-format-latex-header';
  3545. - do not conflict with the default packages in
  3546. `org-latex-default-packages-alist'."
  3547. :group 'org-latex
  3548. :group 'org-export-latex
  3549. :set 'org-set-packages-alist
  3550. :get 'org-get-packages-alist
  3551. :type '(repeat
  3552. (choice
  3553. (list :tag "options/package pair"
  3554. (string :tag "options")
  3555. (string :tag "package")
  3556. (boolean :tag "Snippet"))
  3557. (string :tag "A line of LaTeX"))))
  3558. (defgroup org-appearance nil
  3559. "Settings for Org mode appearance."
  3560. :tag "Org Appearance"
  3561. :group 'org)
  3562. (defcustom org-level-color-stars-only nil
  3563. "Non-nil means fontify only the stars in each headline.
  3564. When nil, the entire headline is fontified.
  3565. Changing it requires restart of `font-lock-mode' to become effective
  3566. also in regions already fontified."
  3567. :group 'org-appearance
  3568. :type 'boolean)
  3569. (defcustom org-hide-leading-stars nil
  3570. "Non-nil means hide the first N-1 stars in a headline.
  3571. This works by using the face `org-hide' for these stars. This
  3572. face is white for a light background, and black for a dark
  3573. background. You may have to customize the face `org-hide' to
  3574. make this work.
  3575. Changing it requires restart of `font-lock-mode' to become effective
  3576. also in regions already fontified.
  3577. You may also set this on a per-file basis by adding one of the following
  3578. lines to the buffer:
  3579. #+STARTUP: hidestars
  3580. #+STARTUP: showstars"
  3581. :group 'org-appearance
  3582. :type 'boolean)
  3583. (defcustom org-hidden-keywords nil
  3584. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3585. For example, a value \\='(title) for this list makes the document's title
  3586. appear in the buffer without the initial \"#+TITLE:\" part."
  3587. :group 'org-appearance
  3588. :version "24.1"
  3589. :type '(set (const :tag "#+AUTHOR" author)
  3590. (const :tag "#+DATE" date)
  3591. (const :tag "#+EMAIL" email)
  3592. (const :tag "#+TITLE" title)))
  3593. (defcustom org-custom-properties nil
  3594. "List of properties (as strings) with a special meaning.
  3595. The default use of these custom properties is to let the user
  3596. hide them with `org-toggle-custom-properties-visibility'."
  3597. :group 'org-properties
  3598. :group 'org-appearance
  3599. :version "24.3"
  3600. :type '(repeat (string :tag "Property Name")))
  3601. (defcustom org-fontify-done-headline nil
  3602. "Non-nil means change the face of a headline if it is marked DONE.
  3603. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3604. When this is non-nil, the headline after the keyword is set to the
  3605. `org-headline-done' as an additional indication."
  3606. :group 'org-appearance
  3607. :type 'boolean)
  3608. (defcustom org-fontify-emphasized-text t
  3609. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3610. Changing this variable requires a restart of Emacs to take effect."
  3611. :group 'org-appearance
  3612. :type 'boolean)
  3613. (defcustom org-fontify-whole-heading-line nil
  3614. "Non-nil means fontify the whole line for headings.
  3615. This is useful when setting a background color for the
  3616. org-level-* faces."
  3617. :group 'org-appearance
  3618. :type 'boolean)
  3619. (defcustom org-highlight-latex-and-related nil
  3620. "Non-nil means highlight LaTeX related syntax in the buffer.
  3621. When non nil, the value should be a list containing any of the
  3622. following symbols:
  3623. `latex' Highlight LaTeX snippets and environments.
  3624. `script' Highlight subscript and superscript.
  3625. `entities' Highlight entities."
  3626. :group 'org-appearance
  3627. :version "24.4"
  3628. :package-version '(Org . "8.0")
  3629. :type '(choice
  3630. (const :tag "No highlighting" nil)
  3631. (set :greedy t :tag "Highlight"
  3632. (const :tag "LaTeX snippets and environments" latex)
  3633. (const :tag "Subscript and superscript" script)
  3634. (const :tag "Entities" entities))))
  3635. (defcustom org-hide-emphasis-markers nil
  3636. "Non-nil mean font-lock should hide the emphasis marker characters."
  3637. :group 'org-appearance
  3638. :type 'boolean)
  3639. (defcustom org-hide-macro-markers nil
  3640. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3641. :group 'org-appearance
  3642. :type 'boolean)
  3643. (defcustom org-pretty-entities nil
  3644. "Non-nil means show entities as UTF8 characters.
  3645. When nil, the \\name form remains in the buffer."
  3646. :group 'org-appearance
  3647. :version "24.1"
  3648. :type 'boolean)
  3649. (defcustom org-pretty-entities-include-sub-superscripts t
  3650. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3651. :group 'org-appearance
  3652. :version "24.1"
  3653. :type 'boolean)
  3654. (defvar org-emph-re nil
  3655. "Regular expression for matching emphasis.
  3656. After a match, the match groups contain these elements:
  3657. 0 The match of the full regular expression, including the characters
  3658. before and after the proper match
  3659. 1 The character before the proper match, or empty at beginning of line
  3660. 2 The proper match, including the leading and trailing markers
  3661. 3 The leading marker like * or /, indicating the type of highlighting
  3662. 4 The text between the emphasis markers, not including the markers
  3663. 5 The character after the match, empty at the end of a line")
  3664. (defvar org-verbatim-re nil
  3665. "Regular expression for matching verbatim text.")
  3666. (defvar org-emphasis-regexp-components) ; defined just below
  3667. (defvar org-emphasis-alist) ; defined just below
  3668. (defun org-set-emph-re (var val)
  3669. "Set variable and compute the emphasis regular expression."
  3670. (set var val)
  3671. (when (and (boundp 'org-emphasis-alist)
  3672. (boundp 'org-emphasis-regexp-components)
  3673. org-emphasis-alist org-emphasis-regexp-components)
  3674. (pcase-let*
  3675. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3676. (body (if (<= nl 0) body
  3677. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3678. (template
  3679. (format (concat "\\([%s]\\|^\\)" ;before markers
  3680. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3681. "\\([%s]\\|$\\)") ;after markers
  3682. pre border border body border post)))
  3683. (setq org-emph-re (format template "*/_+"))
  3684. (setq org-verbatim-re (format template "=~")))))
  3685. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3686. ;; set this option proved cumbersome. See this message/thread:
  3687. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3688. (defvar org-emphasis-regexp-components
  3689. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3690. "Components used to build the regular expression for emphasis.
  3691. This is a list with five entries. Terminology: In an emphasis string
  3692. like \" *strong word* \", we call the initial space PREMATCH, the final
  3693. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3694. and \"trong wor\" is the body. The different components in this variable
  3695. specify what is allowed/forbidden in each part:
  3696. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3697. post Chars allowed as postmatch. End of line will be allowed too.
  3698. border The chars *forbidden* as border characters.
  3699. body-regexp A regexp like \".\" to match a body character. Don't use
  3700. non-shy groups here, and don't allow newline here.
  3701. newline The maximum number of newlines allowed in an emphasis exp.
  3702. You need to reload Org or to restart Emacs after setting this.")
  3703. (defcustom org-emphasis-alist
  3704. '(("*" bold)
  3705. ("/" italic)
  3706. ("_" underline)
  3707. ("=" org-verbatim verbatim)
  3708. ("~" org-code verbatim)
  3709. ("+" (:strike-through t)))
  3710. "Alist of characters and faces to emphasize text.
  3711. Text starting and ending with a special character will be emphasized,
  3712. for example *bold*, _underlined_ and /italic/. This variable sets the
  3713. marker characters and the face to be used by font-lock for highlighting
  3714. in Org buffers.
  3715. You need to reload Org or to restart Emacs after customizing this."
  3716. :group 'org-appearance
  3717. :set 'org-set-emph-re
  3718. :version "24.4"
  3719. :package-version '(Org . "8.0")
  3720. :type '(repeat
  3721. (list
  3722. (string :tag "Marker character")
  3723. (choice
  3724. (face :tag "Font-lock-face")
  3725. (plist :tag "Face property list"))
  3726. (option (const verbatim)))))
  3727. (defvar org-protecting-blocks '("src" "example" "export")
  3728. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3729. This is needed for font-lock setup.")
  3730. ;;; Functions and variables from their packages
  3731. ;; Declared here to avoid compiler warnings
  3732. (defvar mark-active)
  3733. ;; Various packages
  3734. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3735. (declare-function calendar-forward-day "cal-move" (arg))
  3736. (declare-function calendar-goto-date "cal-move" (date))
  3737. (declare-function calendar-goto-today "cal-move" ())
  3738. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3739. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3740. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3741. (declare-function cdlatex-tab "ext:cdlatex" ())
  3742. (declare-function dired-get-filename
  3743. "dired"
  3744. (&optional localp no-error-if-not-filep))
  3745. (declare-function iswitchb-read-buffer
  3746. "iswitchb"
  3747. (prompt &optional
  3748. default require-match _predicate start matches-set))
  3749. (declare-function org-agenda-change-all-lines
  3750. "org-agenda"
  3751. (newhead hdmarker &optional fixface just-this))
  3752. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3753. "org-agenda"
  3754. (&optional end))
  3755. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3756. (declare-function org-agenda-format-item
  3757. "org-agenda"
  3758. (extra txt &optional level category tags dotime
  3759. remove-re habitp))
  3760. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3761. (declare-function org-agenda-save-markers-for-cut-and-paste
  3762. "org-agenda"
  3763. (beg end))
  3764. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3765. (declare-function org-agenda-skip "org-agenda" ())
  3766. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3767. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3768. (declare-function org-indent-mode "org-indent" (&optional arg))
  3769. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3770. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3771. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3772. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3773. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3774. (declare-function parse-time-string "parse-time" (string))
  3775. (defvar align-mode-rules-list)
  3776. (defvar calc-embedded-close-formula)
  3777. (defvar calc-embedded-open-formula)
  3778. (defvar calc-embedded-open-mode)
  3779. (defvar font-lock-unfontify-region-function)
  3780. (defvar iswitchb-temp-buflist)
  3781. (defvar org-agenda-tags-todo-honor-ignore-options)
  3782. (defvar remember-data-file)
  3783. (defvar texmathp-why)
  3784. ;;;###autoload
  3785. (defun turn-on-orgtbl ()
  3786. "Unconditionally turn on `orgtbl-mode'."
  3787. (require 'org-table)
  3788. (orgtbl-mode 1))
  3789. (defun org-at-table-p (&optional table-type)
  3790. "Non-nil if the cursor is inside an Org table.
  3791. If TABLE-TYPE is non-nil, also check for table.el-type tables."
  3792. (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
  3793. (or (not (derived-mode-p 'org-mode))
  3794. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3795. (and e (or table-type
  3796. (eq 'org (org-element-property :type e))))))))
  3797. (defun org-at-table.el-p ()
  3798. "Non-nil when point is at a table.el table."
  3799. (and (org-match-line "[ \t]*[|+]")
  3800. (let ((element (org-element-at-point)))
  3801. (and (eq (org-element-type element) 'table)
  3802. (eq (org-element-property :type element) 'table.el)))))
  3803. (defun org-at-table-hline-p ()
  3804. "Non-nil when point is inside a hline in a table.
  3805. Assume point is already in a table."
  3806. (org-match-line org-table-hline-regexp))
  3807. (defun org-table-map-tables (function &optional quietly)
  3808. "Apply FUNCTION to the start of all tables in the buffer."
  3809. (org-with-wide-buffer
  3810. (goto-char (point-min))
  3811. (while (re-search-forward org-table-any-line-regexp nil t)
  3812. (unless quietly
  3813. (message "Mapping tables: %d%%"
  3814. (floor (* 100.0 (point)) (buffer-size))))
  3815. (beginning-of-line 1)
  3816. (when (and (looking-at org-table-line-regexp)
  3817. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3818. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3819. (save-excursion (funcall function))
  3820. (or (looking-at org-table-line-regexp)
  3821. (forward-char 1)))
  3822. (re-search-forward org-table-any-border-regexp nil 1)))
  3823. (unless quietly (message "Mapping tables: done")))
  3824. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3825. (declare-function org-clock-update-mode-line "org-clock" ())
  3826. (declare-function org-resolve-clocks "org-clock"
  3827. (&optional also-non-dangling-p prompt last-valid))
  3828. (defun org-at-TBLFM-p (&optional pos)
  3829. "Non-nil when point (or POS) is in #+TBLFM line."
  3830. (save-excursion
  3831. (goto-char (or pos (point)))
  3832. (beginning-of-line)
  3833. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3834. (eq (org-element-type (org-element-at-point)) 'table))))
  3835. (defvar org-clock-start-time)
  3836. (defvar org-clock-marker (make-marker)
  3837. "Marker recording the last clock-in.")
  3838. (defvar org-clock-hd-marker (make-marker)
  3839. "Marker recording the last clock-in, but the headline position.")
  3840. (defvar org-clock-heading ""
  3841. "The heading of the current clock entry.")
  3842. (defun org-clock-is-active ()
  3843. "Return the buffer where the clock is currently running.
  3844. Return nil if no clock is running."
  3845. (marker-buffer org-clock-marker))
  3846. (defun org-check-running-clock ()
  3847. "Check if the current buffer contains the running clock.
  3848. If yes, offer to stop it and to save the buffer with the changes."
  3849. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3850. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3851. (buffer-name))))
  3852. (org-clock-out)
  3853. (when (y-or-n-p "Save changed buffer?")
  3854. (save-buffer))))
  3855. (defun org-clocktable-try-shift (dir n)
  3856. "Check if this line starts a clock table, if yes, shift the time block."
  3857. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3858. (org-clocktable-shift dir n)))
  3859. ;;;###autoload
  3860. (defun org-clock-persistence-insinuate ()
  3861. "Set up hooks for clock persistence."
  3862. (require 'org-clock)
  3863. (add-hook 'org-mode-hook 'org-clock-load)
  3864. (add-hook 'kill-emacs-hook 'org-clock-save))
  3865. (defgroup org-archive nil
  3866. "Options concerning archiving in Org mode."
  3867. :tag "Org Archive"
  3868. :group 'org-structure)
  3869. (defcustom org-archive-location "%s_archive::"
  3870. "The location where subtrees should be archived.
  3871. The value of this variable is a string, consisting of two parts,
  3872. separated by a double-colon. The first part is a filename and
  3873. the second part is a headline.
  3874. When the filename is omitted, archiving happens in the same file.
  3875. %s in the filename will be replaced by the current file
  3876. name (without the directory part). Archiving to a different file
  3877. is useful to keep archived entries from contributing to the
  3878. Org Agenda.
  3879. The archived entries will be filed as subtrees of the specified
  3880. headline. When the headline is omitted, the subtrees are simply
  3881. filed away at the end of the file, as top-level entries. Also in
  3882. the heading you can use %s to represent the file name, this can be
  3883. useful when using the same archive for a number of different files.
  3884. Here are a few examples:
  3885. \"%s_archive::\"
  3886. If the current file is Projects.org, archive in file
  3887. Projects.org_archive, as top-level trees. This is the default.
  3888. \"::* Archived Tasks\"
  3889. Archive in the current file, under the top-level headline
  3890. \"* Archived Tasks\".
  3891. \"~/org/archive.org::\"
  3892. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3893. \"~/org/archive.org::* From %s\"
  3894. Archive in file ~/org/archive.org (absolute path), under headlines
  3895. \"From FILENAME\" where file name is the current file name.
  3896. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3897. The \"datetree/\" string is special, signifying to archive
  3898. items to the datetree. Items are placed in either the CLOSED
  3899. date of the item, or the current date if there is no CLOSED date.
  3900. The heading will be a subentry to the current date. There doesn't
  3901. need to be a heading, but there always needs to be a slash after
  3902. datetree. For example, to store archived items directly in the
  3903. datetree, use \"~/org/datetree.org::datetree/\".
  3904. \"basement::** Finished Tasks\"
  3905. Archive in file ./basement (relative path), as level 3 trees
  3906. below the level 2 heading \"** Finished Tasks\".
  3907. You may set this option on a per-file basis by adding to the buffer a
  3908. line like
  3909. #+ARCHIVE: basement::** Finished Tasks
  3910. You may also define it locally for a subtree by setting an ARCHIVE property
  3911. in the entry. If such a property is found in an entry, or anywhere up
  3912. the hierarchy, it will be used."
  3913. :group 'org-archive
  3914. :type 'string)
  3915. (defcustom org-agenda-skip-archived-trees t
  3916. "Non-nil means the agenda will skip any items located in archived trees.
  3917. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3918. variable is no longer recommended, you should leave it at the value t.
  3919. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3920. :group 'org-archive
  3921. :group 'org-agenda-skip
  3922. :type 'boolean)
  3923. (defcustom org-columns-skip-archived-trees t
  3924. "Non-nil means ignore archived trees when creating column view."
  3925. :group 'org-archive
  3926. :group 'org-properties
  3927. :type 'boolean)
  3928. (defcustom org-cycle-open-archived-trees nil
  3929. "Non-nil means `org-cycle' will open archived trees.
  3930. An archived tree is a tree marked with the tag ARCHIVE.
  3931. When nil, archived trees will stay folded. You can still open them with
  3932. normal outline commands like `show-all', but not with the cycling commands."
  3933. :group 'org-archive
  3934. :group 'org-cycle
  3935. :type 'boolean)
  3936. (defcustom org-sparse-tree-open-archived-trees nil
  3937. "Non-nil means sparse tree construction shows matches in archived trees.
  3938. When nil, matches in these trees are highlighted, but the trees are kept in
  3939. collapsed state."
  3940. :group 'org-archive
  3941. :group 'org-sparse-trees
  3942. :type 'boolean)
  3943. (defcustom org-sparse-tree-default-date-type nil
  3944. "The default date type when building a sparse tree.
  3945. When this is nil, a date is a scheduled or a deadline timestamp.
  3946. Otherwise, these types are allowed:
  3947. all: all timestamps
  3948. active: only active timestamps (<...>)
  3949. inactive: only inactive timestamps ([...])
  3950. scheduled: only scheduled timestamps
  3951. deadline: only deadline timestamps"
  3952. :type '(choice (const :tag "Scheduled or deadline" nil)
  3953. (const :tag "All timestamps" all)
  3954. (const :tag "Only active timestamps" active)
  3955. (const :tag "Only inactive timestamps" inactive)
  3956. (const :tag "Only scheduled timestamps" scheduled)
  3957. (const :tag "Only deadline timestamps" deadline)
  3958. (const :tag "Only closed timestamps" closed))
  3959. :version "26.1"
  3960. :package-version '(Org . "8.3")
  3961. :group 'org-sparse-trees)
  3962. (defun org-cycle-hide-archived-subtrees (state)
  3963. "Re-hide all archived subtrees after a visibility state change.
  3964. STATE should be one of the symbols listed in the docstring of
  3965. `org-cycle-hook'."
  3966. (when (and (not org-cycle-open-archived-trees)
  3967. (not (memq state '(overview folded))))
  3968. (save-excursion
  3969. (let* ((globalp (memq state '(contents all)))
  3970. (beg (if globalp (point-min) (point)))
  3971. (end (if globalp (point-max) (org-end-of-subtree t))))
  3972. (org-hide-archived-subtrees beg end)
  3973. (goto-char beg)
  3974. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3975. (message "%s" (substitute-command-keys
  3976. "Subtree is archived and stays closed. Use \
  3977. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3978. (defun org-force-cycle-archived ()
  3979. "Cycle subtree even if it is archived."
  3980. (interactive)
  3981. (setq this-command 'org-cycle)
  3982. (let ((org-cycle-open-archived-trees t))
  3983. (call-interactively 'org-cycle)))
  3984. (defun org-hide-archived-subtrees (beg end)
  3985. "Re-hide all archived subtrees after a visibility state change."
  3986. (org-with-wide-buffer
  3987. (let ((case-fold-search nil)
  3988. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3989. (goto-char beg)
  3990. ;; Include headline point is currently on.
  3991. (beginning-of-line)
  3992. (while (and (< (point) end) (re-search-forward re end t))
  3993. (when (member org-archive-tag (org-get-tags nil t))
  3994. (org-flag-subtree t)
  3995. (org-end-of-subtree t))))))
  3996. (defun org-flag-subtree (flag)
  3997. (save-excursion
  3998. (org-back-to-heading t)
  3999. (org-flag-region (line-end-position)
  4000. (progn (org-end-of-subtree t) (point))
  4001. flag
  4002. 'outline)))
  4003. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4004. ;; Declare Column View Code
  4005. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4006. (declare-function org-columns-compute "org-colview" (property))
  4007. ;; Declare ID code
  4008. (declare-function org-id-store-link "org-id")
  4009. (declare-function org-id-locations-load "org-id")
  4010. (declare-function org-id-locations-save "org-id")
  4011. (defvar org-id-track-globally)
  4012. ;;; Variables for pre-computed regular expressions, all buffer local
  4013. (defvar-local org-todo-regexp nil
  4014. "Matches any of the TODO state keywords.
  4015. Since TODO keywords are case-sensitive, `case-fold-search' is
  4016. expected to be bound to nil when matching against this regexp.")
  4017. (defvar-local org-not-done-regexp nil
  4018. "Matches any of the TODO state keywords except the last one.
  4019. Since TODO keywords are case-sensitive, `case-fold-search' is
  4020. expected to be bound to nil when matching against this regexp.")
  4021. (defvar-local org-not-done-heading-regexp nil
  4022. "Matches a TODO headline that is not done.
  4023. Since TODO keywords are case-sensitive, `case-fold-search' is
  4024. expected to be bound to nil when matching against this regexp.")
  4025. (defvar-local org-todo-line-regexp nil
  4026. "Matches a headline and puts TODO state into group 2 if present.
  4027. Since TODO keywords are case-sensitive, `case-fold-search' is
  4028. expected to be bound to nil when matching against this regexp.")
  4029. (defvar-local org-complex-heading-regexp nil
  4030. "Matches a headline and puts everything into groups:
  4031. group 1: Stars
  4032. group 2: The TODO keyword, maybe
  4033. group 3: Priority cookie
  4034. group 4: True headline
  4035. group 5: Tags
  4036. Since TODO keywords are case-sensitive, `case-fold-search' is
  4037. expected to be bound to nil when matching against this regexp.")
  4038. (defvar-local org-complex-heading-regexp-format nil
  4039. "Printf format to make regexp to match an exact headline.
  4040. This regexp will match the headline of any node which has the
  4041. exact headline text that is put into the format, but may have any
  4042. TODO state, priority and tags.")
  4043. (defvar-local org-todo-line-tags-regexp nil
  4044. "Matches a headline and puts TODO state into group 2 if present.
  4045. Also put tags into group 4 if tags are present.")
  4046. (defconst org-plain-time-of-day-regexp
  4047. (concat
  4048. "\\(\\<[012]?[0-9]"
  4049. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4050. "\\(--?"
  4051. "\\(\\<[012]?[0-9]"
  4052. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4053. "\\)?")
  4054. "Regular expression to match a plain time or time range.
  4055. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4056. groups carry important information:
  4057. 0 the full match
  4058. 1 the first time, range or not
  4059. 8 the second time, if it is a range.")
  4060. (defconst org-plain-time-extension-regexp
  4061. (concat
  4062. "\\(\\<[012]?[0-9]"
  4063. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4064. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4065. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4066. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4067. groups carry important information:
  4068. 0 the full match
  4069. 7 hours of duration
  4070. 9 minutes of duration")
  4071. (defconst org-stamp-time-of-day-regexp
  4072. (concat
  4073. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4074. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4075. "\\(--?"
  4076. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4077. "Regular expression to match a timestamp time or time range.
  4078. After a match, the following groups carry important information:
  4079. 0 the full match
  4080. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4081. 2 the first time, range or not
  4082. 4 the second time, if it is a range.")
  4083. (defconst org-startup-options
  4084. '(("fold" org-startup-folded t)
  4085. ("overview" org-startup-folded t)
  4086. ("nofold" org-startup-folded nil)
  4087. ("showall" org-startup-folded nil)
  4088. ("showeverything" org-startup-folded showeverything)
  4089. ("content" org-startup-folded content)
  4090. ("indent" org-startup-indented t)
  4091. ("noindent" org-startup-indented nil)
  4092. ("hidestars" org-hide-leading-stars t)
  4093. ("showstars" org-hide-leading-stars nil)
  4094. ("odd" org-odd-levels-only t)
  4095. ("oddeven" org-odd-levels-only nil)
  4096. ("align" org-startup-align-all-tables t)
  4097. ("noalign" org-startup-align-all-tables nil)
  4098. ("shrink" org-startup-shrink-all-tables t)
  4099. ("inlineimages" org-startup-with-inline-images t)
  4100. ("noinlineimages" org-startup-with-inline-images nil)
  4101. ("latexpreview" org-startup-with-latex-preview t)
  4102. ("nolatexpreview" org-startup-with-latex-preview nil)
  4103. ("customtime" org-display-custom-times t)
  4104. ("logdone" org-log-done time)
  4105. ("lognotedone" org-log-done note)
  4106. ("nologdone" org-log-done nil)
  4107. ("lognoteclock-out" org-log-note-clock-out t)
  4108. ("nolognoteclock-out" org-log-note-clock-out nil)
  4109. ("logrepeat" org-log-repeat state)
  4110. ("lognoterepeat" org-log-repeat note)
  4111. ("logdrawer" org-log-into-drawer t)
  4112. ("nologdrawer" org-log-into-drawer nil)
  4113. ("logstatesreversed" org-log-states-order-reversed t)
  4114. ("nologstatesreversed" org-log-states-order-reversed nil)
  4115. ("nologrepeat" org-log-repeat nil)
  4116. ("logreschedule" org-log-reschedule time)
  4117. ("lognotereschedule" org-log-reschedule note)
  4118. ("nologreschedule" org-log-reschedule nil)
  4119. ("logredeadline" org-log-redeadline time)
  4120. ("lognoteredeadline" org-log-redeadline note)
  4121. ("nologredeadline" org-log-redeadline nil)
  4122. ("logrefile" org-log-refile time)
  4123. ("lognoterefile" org-log-refile note)
  4124. ("nologrefile" org-log-refile nil)
  4125. ("fninline" org-footnote-define-inline t)
  4126. ("nofninline" org-footnote-define-inline nil)
  4127. ("fnlocal" org-footnote-section nil)
  4128. ("fnauto" org-footnote-auto-label t)
  4129. ("fnprompt" org-footnote-auto-label nil)
  4130. ("fnconfirm" org-footnote-auto-label confirm)
  4131. ("fnplain" org-footnote-auto-label plain)
  4132. ("fnadjust" org-footnote-auto-adjust t)
  4133. ("nofnadjust" org-footnote-auto-adjust nil)
  4134. ("constcgs" constants-unit-system cgs)
  4135. ("constSI" constants-unit-system SI)
  4136. ("noptag" org-tag-persistent-alist nil)
  4137. ("hideblocks" org-hide-block-startup t)
  4138. ("nohideblocks" org-hide-block-startup nil)
  4139. ("beamer" org-startup-with-beamer-mode t)
  4140. ("entitiespretty" org-pretty-entities t)
  4141. ("entitiesplain" org-pretty-entities nil))
  4142. "Variable associated with STARTUP options for Org.
  4143. Each element is a list of three items: the startup options (as written
  4144. in the #+STARTUP line), the corresponding variable, and the value to set
  4145. this variable to if the option is found. An optional forth element PUSH
  4146. means to push this value onto the list in the variable.")
  4147. (defcustom org-group-tags t
  4148. "When non-nil (the default), use group tags.
  4149. This can be turned on/off through `org-toggle-tags-groups'."
  4150. :group 'org-tags
  4151. :group 'org-startup
  4152. :type 'boolean)
  4153. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4154. (defun org-toggle-tags-groups ()
  4155. "Toggle support for group tags.
  4156. Support for group tags is controlled by the option
  4157. `org-group-tags', which is non-nil by default."
  4158. (interactive)
  4159. (setq org-group-tags (not org-group-tags))
  4160. (cond ((and (derived-mode-p 'org-agenda-mode)
  4161. org-group-tags)
  4162. (org-agenda-redo))
  4163. ((derived-mode-p 'org-mode)
  4164. (let ((org-inhibit-startup t)) (org-mode))))
  4165. (message "Groups tags support has been turned %s"
  4166. (if org-group-tags "on" "off")))
  4167. (defun org--tag-add-to-alist (alist1 alist2)
  4168. "Merge tags from ALIST1 into ALIST2.
  4169. Duplicates tags outside a group are removed. Keywords and order
  4170. are preserved.
  4171. The function assumes ALIST1 and ALIST2 are proper tag alists.
  4172. See `org-tag-alist' for their structure."
  4173. (cond
  4174. ((null alist2) alist1)
  4175. ((null alist1) alist2)
  4176. (t
  4177. (let ((to-add nil)
  4178. (group-flag nil))
  4179. (dolist (tag-pair alist1)
  4180. (pcase tag-pair
  4181. (`(,(or :startgrouptag :startgroup))
  4182. (setq group-flag t)
  4183. (push tag-pair to-add))
  4184. (`(,(or :endgrouptag :endgroup))
  4185. (setq group-flag nil)
  4186. (push tag-pair to-add))
  4187. (`(,(or :grouptags :newline))
  4188. (push tag-pair to-add))
  4189. (`(,tag . ,_)
  4190. ;; Remove duplicates from ALIST1, unless they are in
  4191. ;; a group. Indeed, it makes sense to have a tag appear in
  4192. ;; multiple groups.
  4193. (when (or group-flag (not (assoc tag alist2)))
  4194. (push tag-pair to-add)))
  4195. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  4196. ;; Preserve order of ALIST1.
  4197. (append (nreverse to-add) alist2)))))
  4198. (defun org-set-regexps-and-options (&optional tags-only)
  4199. "Precompute regular expressions used in the current buffer.
  4200. When optional argument TAGS-ONLY is non-nil, only compute tags
  4201. related expressions."
  4202. (when (derived-mode-p 'org-mode)
  4203. (let ((alist (org--setup-collect-keywords
  4204. (org-make-options-regexp
  4205. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4206. (and (not tags-only)
  4207. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4208. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4209. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4210. ;; Startup options. Get this early since it does change
  4211. ;; behavior for other options (e.g., tags).
  4212. (let ((startup (cdr (assq 'startup alist))))
  4213. (dolist (option startup)
  4214. (let ((entry (assoc-string option org-startup-options t)))
  4215. (when entry
  4216. (let ((var (nth 1 entry))
  4217. (val (nth 2 entry)))
  4218. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4219. (unless (listp (symbol-value var))
  4220. (set (make-local-variable var) nil))
  4221. (add-to-list var val)))))))
  4222. (setq-local org-file-tags
  4223. (mapcar #'org-add-prop-inherited
  4224. (cdr (assq 'filetags alist))))
  4225. (setq org-current-tag-alist
  4226. (org--tag-add-to-alist
  4227. org-tag-persistent-alist
  4228. (let ((tags (cdr (assq 'tags alist))))
  4229. (if tags (org-tag-string-to-alist tags)
  4230. org-tag-alist))))
  4231. (setq org-tag-groups-alist
  4232. (org-tag-alist-to-groups org-current-tag-alist))
  4233. (unless tags-only
  4234. ;; File properties.
  4235. (setq-local org-file-properties (cdr (assq 'property alist)))
  4236. ;; Archive location.
  4237. (let ((archive (cdr (assq 'archive alist))))
  4238. (when archive (setq-local org-archive-location archive)))
  4239. ;; Category.
  4240. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4241. (when cat
  4242. (setq-local org-category (intern cat))
  4243. (setq-local org-file-properties
  4244. (org--update-property-plist
  4245. "CATEGORY" cat org-file-properties))))
  4246. ;; Columns.
  4247. (let ((column (cdr (assq 'columns alist))))
  4248. (when column (setq-local org-columns-default-format column)))
  4249. ;; Constants.
  4250. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4251. ;; Link abbreviations.
  4252. (let ((links (cdr (assq 'link alist))))
  4253. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4254. ;; Priorities.
  4255. (let ((priorities (cdr (assq 'priorities alist))))
  4256. (when priorities
  4257. (setq-local org-highest-priority (nth 0 priorities))
  4258. (setq-local org-lowest-priority (nth 1 priorities))
  4259. (setq-local org-default-priority (nth 2 priorities))))
  4260. ;; Scripts.
  4261. (let ((scripts (assq 'scripts alist)))
  4262. (when scripts
  4263. (setq-local org-use-sub-superscripts (cdr scripts))))
  4264. ;; TODO keywords.
  4265. (setq-local org-todo-kwd-alist nil)
  4266. (setq-local org-todo-key-alist nil)
  4267. (setq-local org-todo-key-trigger nil)
  4268. (setq-local org-todo-keywords-1 nil)
  4269. (setq-local org-done-keywords nil)
  4270. (setq-local org-todo-heads nil)
  4271. (setq-local org-todo-sets nil)
  4272. (setq-local org-todo-log-states nil)
  4273. (let ((todo-sequences
  4274. (or (nreverse (cdr (assq 'todo alist)))
  4275. (let ((d (default-value 'org-todo-keywords)))
  4276. (if (not (stringp (car d))) d
  4277. ;; XXX: Backward compatibility code.
  4278. (list (cons org-todo-interpretation d)))))))
  4279. (dolist (sequence todo-sequences)
  4280. (let* ((sequence (or (run-hook-with-args-until-success
  4281. 'org-todo-setup-filter-hook sequence)
  4282. sequence))
  4283. (sequence-type (car sequence))
  4284. (keywords (cdr sequence))
  4285. (sep (member "|" keywords))
  4286. names alist)
  4287. (dolist (k (remove "|" keywords))
  4288. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4289. k)
  4290. (error "Invalid TODO keyword %s" k))
  4291. (let ((name (match-string 1 k))
  4292. (key (match-string 2 k))
  4293. (log (org-extract-log-state-settings k)))
  4294. (push name names)
  4295. (push (cons name (and key (string-to-char key))) alist)
  4296. (when log (push log org-todo-log-states))))
  4297. (let* ((names (nreverse names))
  4298. (done (if sep (org-remove-keyword-keys (cdr sep))
  4299. (last names)))
  4300. (head (car names))
  4301. (tail (list sequence-type head (car done) (org-last done))))
  4302. (add-to-list 'org-todo-heads head 'append)
  4303. (push names org-todo-sets)
  4304. (setq org-done-keywords (append org-done-keywords done nil))
  4305. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4306. (setq org-todo-key-alist
  4307. (append org-todo-key-alist
  4308. (and alist
  4309. (append '((:startgroup))
  4310. (nreverse alist)
  4311. '((:endgroup))))))
  4312. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4313. (setq org-todo-sets (nreverse org-todo-sets)
  4314. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4315. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4316. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4317. ;; Compute the regular expressions and other local variables.
  4318. ;; Using `org-outline-regexp-bol' would complicate them much,
  4319. ;; because of the fixed white space at the end of that string.
  4320. (unless org-done-keywords
  4321. (setq org-done-keywords
  4322. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4323. (setq org-not-done-keywords
  4324. (org-delete-all org-done-keywords
  4325. (copy-sequence org-todo-keywords-1))
  4326. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4327. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4328. org-not-done-heading-regexp
  4329. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4330. org-todo-line-regexp
  4331. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4332. org-complex-heading-regexp
  4333. (concat "^\\(\\*+\\)"
  4334. "\\(?: +" org-todo-regexp "\\)?"
  4335. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4336. "\\(?: +\\(.*?\\)\\)??"
  4337. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4338. "[ \t]*$")
  4339. org-complex-heading-regexp-format
  4340. (concat "^\\(\\*+\\)"
  4341. "\\(?: +" org-todo-regexp "\\)?"
  4342. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4343. "\\(?: +"
  4344. ;; Stats cookies can be stuck to body.
  4345. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4346. "\\(%s\\)"
  4347. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4348. "\\)"
  4349. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4350. "[ \t]*$")
  4351. org-todo-line-tags-regexp
  4352. (concat "^\\(\\*+\\)"
  4353. "\\(?: +" org-todo-regexp "\\)?"
  4354. "\\(?: +\\(.*?\\)\\)??"
  4355. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4356. "[ \t]*$"))
  4357. (org-compute-latex-and-related-regexp)))))
  4358. (defun org--setup-collect-keywords (regexp &optional files alist)
  4359. "Return setup keywords values as an alist.
  4360. REGEXP matches a subset of setup keywords. FILES is a list of
  4361. file names already visited. It is used to avoid circular setup
  4362. files. ALIST, when non-nil, is the alist computed so far.
  4363. Return value contains the following keys: `archive', `category',
  4364. `columns', `constants', `filetags', `link', `priorities',
  4365. `property', `scripts', `startup', `tags' and `todo'."
  4366. (org-with-wide-buffer
  4367. (goto-char (point-min))
  4368. (let ((case-fold-search t))
  4369. (while (re-search-forward regexp nil t)
  4370. (let ((element (org-element-at-point)))
  4371. (when (eq (org-element-type element) 'keyword)
  4372. (let ((key (org-element-property :key element))
  4373. (value (org-element-property :value element)))
  4374. (cond
  4375. ((equal key "ARCHIVE")
  4376. (when (org-string-nw-p value)
  4377. (push (cons 'archive value) alist)))
  4378. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4379. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4380. ((equal key "CONSTANTS")
  4381. (let* ((constants (assq 'constants alist))
  4382. (store (cdr constants)))
  4383. (dolist (pair (split-string value))
  4384. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4385. pair)
  4386. (let* ((name (match-string 1 pair))
  4387. (value (match-string 2 pair))
  4388. (old (assoc name store)))
  4389. (if old (setcdr old value)
  4390. (push (cons name value) store)))))
  4391. (if constants (setcdr constants store)
  4392. (push (cons 'constants store) alist))))
  4393. ((equal key "FILETAGS")
  4394. (when (org-string-nw-p value)
  4395. (let ((old (assq 'filetags alist))
  4396. (new (apply #'nconc
  4397. (mapcar (lambda (x) (org-split-string x ":"))
  4398. (split-string value)))))
  4399. (if old (setcdr old (append new (cdr old)))
  4400. (push (cons 'filetags new) alist)))))
  4401. ((equal key "LINK")
  4402. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4403. (let ((links (assq 'link alist))
  4404. (pair (cons (match-string-no-properties 1 value)
  4405. (match-string-no-properties 2 value))))
  4406. (if links (push pair (cdr links))
  4407. (push (list 'link pair) alist)))))
  4408. ((equal key "OPTIONS")
  4409. (when (and (org-string-nw-p value)
  4410. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4411. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4412. ((equal key "PRIORITIES")
  4413. (push (cons 'priorities
  4414. (let ((prio (split-string value)))
  4415. (if (< (length prio) 3) '(?A ?C ?B)
  4416. (mapcar #'string-to-char prio))))
  4417. alist))
  4418. ((equal key "PROPERTY")
  4419. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4420. (let* ((property (assq 'property alist))
  4421. (value (org--update-property-plist
  4422. (match-string-no-properties 1 value)
  4423. (match-string-no-properties 2 value)
  4424. (cdr property))))
  4425. (if property (setcdr property value)
  4426. (push (cons 'property value) alist)))))
  4427. ((equal key "STARTUP")
  4428. (let ((startup (assq 'startup alist)))
  4429. (if startup
  4430. (setcdr startup
  4431. (append (cdr startup) (split-string value)))
  4432. (push (cons 'startup (split-string value)) alist))))
  4433. ((equal key "TAGS")
  4434. (let ((tag-cell (assq 'tags alist)))
  4435. (if tag-cell
  4436. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4437. (push (cons 'tags value) alist))))
  4438. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4439. (let ((todo (assq 'todo alist))
  4440. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4441. (split-string value))))
  4442. (if todo (push value (cdr todo))
  4443. (push (list 'todo value) alist))))
  4444. ((equal key "SETUPFILE")
  4445. (unless buffer-read-only ; Do not check in Gnus messages.
  4446. (let ((f (and (org-string-nw-p value)
  4447. (expand-file-name
  4448. (org-unbracket-string "\"" "\"" value)))))
  4449. (when (and f (file-readable-p f) (not (member f files)))
  4450. (with-temp-buffer
  4451. (setq default-directory (file-name-directory f))
  4452. (insert-file-contents f)
  4453. (setq alist
  4454. ;; Fake Org mode to benefit from cache
  4455. ;; without recurring needlessly.
  4456. (let ((major-mode 'org-mode))
  4457. (org--setup-collect-keywords
  4458. regexp (cons f files) alist)))))))))))))))
  4459. alist)
  4460. (defun org-tag-string-to-alist (s)
  4461. "Return tag alist associated to string S.
  4462. S is a value for TAGS keyword or produced with
  4463. `org-tag-alist-to-string'. Return value is an alist suitable for
  4464. `org-tag-alist' or `org-tag-persistent-alist'."
  4465. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4466. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  4467. "\\(?:(\\(.\\))\\)?\\'"))
  4468. alist group-flag)
  4469. (dolist (tokens lines (cdr (nreverse alist)))
  4470. (push '(:newline) alist)
  4471. (while tokens
  4472. (let ((token (pop tokens)))
  4473. (pcase token
  4474. ("{"
  4475. (push '(:startgroup) alist)
  4476. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4477. ("}"
  4478. (push '(:endgroup) alist)
  4479. (setq group-flag nil))
  4480. ("["
  4481. (push '(:startgrouptag) alist)
  4482. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4483. ("]"
  4484. (push '(:endgrouptag) alist)
  4485. (setq group-flag nil))
  4486. (":"
  4487. (push '(:grouptags) alist))
  4488. ((guard (string-match tag-re token))
  4489. (let ((tag (match-string 1 token))
  4490. (key (and (match-beginning 2)
  4491. (string-to-char (match-string 2 token)))))
  4492. ;; Push all tags in groups, no matter if they already
  4493. ;; appear somewhere else in the list.
  4494. (when (or group-flag (not (assoc tag alist)))
  4495. (push (cons tag key) alist))))))))))
  4496. (defun org-tag-alist-to-string (alist &optional skip-key)
  4497. "Return tag string associated to ALIST.
  4498. ALIST is an alist, as defined in `org-tag-alist' or
  4499. `org-tag-persistent-alist', or produced with
  4500. `org-tag-string-to-alist'.
  4501. Return value is a string suitable as a value for \"TAGS\"
  4502. keyword.
  4503. When optional argument SKIP-KEY is non-nil, skip selection keys
  4504. next to tags."
  4505. (mapconcat (lambda (token)
  4506. (pcase token
  4507. (`(:startgroup) "{")
  4508. (`(:endgroup) "}")
  4509. (`(:startgrouptag) "[")
  4510. (`(:endgrouptag) "]")
  4511. (`(:grouptags) ":")
  4512. (`(:newline) "\\n")
  4513. ((and
  4514. (guard (not skip-key))
  4515. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4516. (format "%s(%c)" tag key))
  4517. (`(,(and tag (pred stringp)) . ,_) tag)
  4518. (_ (user-error "Invalid tag token: %S" token))))
  4519. alist
  4520. " "))
  4521. (defun org-tag-alist-to-groups (alist)
  4522. "Return group alist from tag ALIST.
  4523. ALIST is an alist, as defined in `org-tag-alist' or
  4524. `org-tag-persistent-alist', or produced with
  4525. `org-tag-string-to-alist'. Return value is an alist following
  4526. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4527. a string, summarizing TAGS, as a list of strings."
  4528. (let (groups group-status current-group)
  4529. (dolist (token alist (nreverse groups))
  4530. (pcase token
  4531. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4532. (`(,(or :endgroup :endgrouptag))
  4533. (when (eq group-status 'append)
  4534. (push (nreverse current-group) groups))
  4535. (setq group-status nil current-group nil))
  4536. (`(:grouptags) (setq group-status 'append))
  4537. ((and `(,tag . ,_) (guard group-status))
  4538. (if (eq group-status 'append) (push tag current-group)
  4539. (setq current-group (list tag))))
  4540. (_ nil)))))
  4541. (defvar org--file-cache (make-hash-table :test #'equal)
  4542. "Hash table to store contents of files referenced via a URL.
  4543. This is the cache of file URLs read using `org-file-contents'.")
  4544. (defun org-reset-file-cache ()
  4545. "Reset the cache of files downloaded by `org-file-contents'."
  4546. (clrhash org--file-cache))
  4547. (defun org-file-url-p (file)
  4548. "Non-nil if FILE is a URL."
  4549. (require 'ffap)
  4550. (string-match-p ffap-url-regexp file))
  4551. (defun org-file-contents (file &optional noerror nocache)
  4552. "Return the contents of FILE, as a string.
  4553. FILE can be a file name or URL.
  4554. If FILE is a URL, download the contents. If the URL contents are
  4555. already cached in the `org--file-cache' hash table, the download step
  4556. is skipped.
  4557. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4558. from file or URL.
  4559. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4560. is available. This option applies only if FILE is a URL."
  4561. (let* ((is-url (org-file-url-p file))
  4562. (cache (and is-url
  4563. (not nocache)
  4564. (gethash file org--file-cache))))
  4565. (cond
  4566. (cache)
  4567. (is-url
  4568. (with-current-buffer (url-retrieve-synchronously file)
  4569. (goto-char (point-min))
  4570. ;; Move point to after the url-retrieve header.
  4571. (search-forward "\n\n" nil :move)
  4572. ;; Search for the success code only in the url-retrieve header.
  4573. (if (save-excursion
  4574. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4575. ;; Update the cache `org--file-cache' and return contents.
  4576. (puthash file
  4577. (buffer-substring-no-properties (point) (point-max))
  4578. org--file-cache)
  4579. (funcall (if noerror #'message #'user-error)
  4580. "Unable to fetch file from %S"
  4581. file))))
  4582. (t
  4583. (with-temp-buffer
  4584. (condition-case nil
  4585. (progn
  4586. (insert-file-contents file)
  4587. (buffer-string))
  4588. (file-error
  4589. (funcall (if noerror #'message #'user-error)
  4590. "Unable to read file %S"
  4591. file))))))))
  4592. (defun org-extract-log-state-settings (x)
  4593. "Extract the log state setting from a TODO keyword string.
  4594. This will extract info from a string like \"WAIT(w@/!)\"."
  4595. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4596. (let ((kw (match-string 1 x))
  4597. (log1 (and (match-end 3) (match-string 3 x)))
  4598. (log2 (and (match-end 4) (match-string 4 x))))
  4599. (and (or log1 log2)
  4600. (list kw
  4601. (and log1 (if (equal log1 "!") 'time 'note))
  4602. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4603. (defun org-remove-keyword-keys (list)
  4604. "Remove a pair of parenthesis at the end of each string in LIST."
  4605. (mapcar (lambda (x)
  4606. (if (string-match "(.*)$" x)
  4607. (substring x 0 (match-beginning 0))
  4608. x))
  4609. list))
  4610. (defun org-assign-fast-keys (alist)
  4611. "Assign fast keys to a keyword-key alist.
  4612. Respect keys that are already there."
  4613. (let (new e (alt ?0))
  4614. (while (setq e (pop alist))
  4615. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4616. (cdr e)) ;; Key already assigned.
  4617. (push e new)
  4618. (let ((clist (string-to-list (downcase (car e))))
  4619. (used (append new alist)))
  4620. (when (= (car clist) ?@)
  4621. (pop clist))
  4622. (while (and clist (rassoc (car clist) used))
  4623. (pop clist))
  4624. (unless clist
  4625. (while (rassoc alt used)
  4626. (cl-incf alt)))
  4627. (push (cons (car e) (or (car clist) alt)) new))))
  4628. (nreverse new)))
  4629. ;;; Some variables used in various places
  4630. (defvar org-window-configuration nil
  4631. "Used in various places to store a window configuration.")
  4632. (defvar org-selected-window nil
  4633. "Used in various places to store a window configuration.")
  4634. (defvar org-finish-function nil
  4635. "Function to be called when `C-c C-c' is used.
  4636. This is for getting out of special buffers like capture.")
  4637. (defvar org-last-state)
  4638. ;; Defined somewhere in this file, but used before definition.
  4639. (defvar org-entities) ;; defined in org-entities.el
  4640. (defvar org-struct-menu)
  4641. (defvar org-org-menu)
  4642. (defvar org-tbl-menu)
  4643. ;;;; Define the Org mode
  4644. ;; We use a before-change function to check if a table might need
  4645. ;; an update.
  4646. (defvar org-table-may-need-update t
  4647. "Indicates that a table might need an update.
  4648. This variable is set by `org-before-change-function'.
  4649. `org-table-align' sets it back to nil.")
  4650. (defun org-before-change-function (_beg _end)
  4651. "Every change indicates that a table might need an update."
  4652. (setq org-table-may-need-update t))
  4653. (defvar org-mode-map)
  4654. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4655. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4656. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4657. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4658. (defvar org-table-buffer-is-an nil)
  4659. (defvar bidi-paragraph-direction)
  4660. (defvar buffer-face-mode-face)
  4661. (require 'outline)
  4662. ;; Other stuff we need.
  4663. (require 'time-date)
  4664. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4665. (require 'easymenu)
  4666. (autoload 'easy-menu-add "easymenu")
  4667. (require 'overlay)
  4668. ;; (require 'org-macs) moved higher up in the file before it is first used
  4669. (require 'org-entities)
  4670. ;; (require 'org-compat) moved higher up in the file before it is first used
  4671. (require 'org-faces)
  4672. (require 'org-list)
  4673. (require 'org-pcomplete)
  4674. (require 'org-src)
  4675. (require 'org-footnote)
  4676. (require 'org-macro)
  4677. ;; babel
  4678. (require 'ob)
  4679. ;;;###autoload
  4680. (define-derived-mode org-mode outline-mode "Org"
  4681. "Outline-based notes management and organizer, alias
  4682. \"Carsten's outline-mode for keeping track of everything.\"
  4683. Org mode develops organizational tasks around a NOTES file which
  4684. contains information about projects as plain text. Org mode is
  4685. implemented on top of Outline mode, which is ideal to keep the content
  4686. of large files well structured. It supports ToDo items, deadlines and
  4687. time stamps, which magically appear in the diary listing of the Emacs
  4688. calendar. Tables are easily created with a built-in table editor.
  4689. Plain text URL-like links connect to websites, emails (VM), Usenet
  4690. messages (Gnus), BBDB entries, and any files related to the project.
  4691. For printing and sharing of notes, an Org file (or a part of it)
  4692. can be exported as a structured ASCII or HTML file.
  4693. The following commands are available:
  4694. \\{org-mode-map}"
  4695. ;; Get rid of Outline menus, they are not needed
  4696. ;; Need to do this here because define-derived-mode sets up
  4697. ;; the keymap so late. Still, it is a waste to call this each time
  4698. ;; we switch another buffer into Org mode.
  4699. (define-key org-mode-map [menu-bar headings] 'undefined)
  4700. (define-key org-mode-map [menu-bar hide] 'undefined)
  4701. (define-key org-mode-map [menu-bar show] 'undefined)
  4702. (org-load-modules-maybe)
  4703. (org-install-agenda-files-menu)
  4704. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4705. (add-to-invisibility-spec '(org-hide-block . t))
  4706. (add-to-invisibility-spec '(org-hide-drawer . t))
  4707. (setq-local outline-regexp org-outline-regexp)
  4708. (setq-local outline-level 'org-outline-level)
  4709. (setq bidi-paragraph-direction 'left-to-right)
  4710. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4711. (unless org-display-table
  4712. (setq org-display-table (make-display-table)))
  4713. (set-display-table-slot
  4714. org-display-table 4
  4715. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4716. org-ellipsis)))
  4717. (setq buffer-display-table org-display-table))
  4718. (org-set-regexps-and-options)
  4719. (org-set-font-lock-defaults)
  4720. (when (and org-tag-faces (not org-tags-special-faces-re))
  4721. ;; tag faces set outside customize.... force initialization.
  4722. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4723. ;; Calc embedded
  4724. (setq-local calc-embedded-open-mode "# ")
  4725. ;; Modify a few syntax entries
  4726. (modify-syntax-entry ?\" "\"")
  4727. (modify-syntax-entry ?\\ "_")
  4728. (modify-syntax-entry ?~ "_")
  4729. (modify-syntax-entry ?< "(>")
  4730. (modify-syntax-entry ?> ")<")
  4731. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4732. ;; Activate before-change-function
  4733. (setq-local org-table-may-need-update t)
  4734. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4735. ;; Check for running clock before killing a buffer
  4736. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4737. ;; Initialize macros templates.
  4738. (org-macro-initialize-templates)
  4739. ;; Initialize radio targets.
  4740. (org-update-radio-target-regexp)
  4741. ;; Indentation.
  4742. (setq-local indent-line-function 'org-indent-line)
  4743. (setq-local indent-region-function 'org-indent-region)
  4744. ;; Filling and auto-filling.
  4745. (org-setup-filling)
  4746. ;; Comments.
  4747. (org-setup-comments-handling)
  4748. ;; Initialize cache.
  4749. (org-element-cache-reset)
  4750. ;; Beginning/end of defun
  4751. (setq-local beginning-of-defun-function 'org-backward-element)
  4752. (setq-local end-of-defun-function
  4753. (lambda ()
  4754. (if (not (org-at-heading-p))
  4755. (org-forward-element)
  4756. (org-forward-element)
  4757. (forward-char -1))))
  4758. ;; Next error for sparse trees
  4759. (setq-local next-error-function 'org-occur-next-match)
  4760. ;; Make sure dependence stuff works reliably, even for users who set it
  4761. ;; too late :-(
  4762. (if org-enforce-todo-dependencies
  4763. (add-hook 'org-blocker-hook
  4764. 'org-block-todo-from-children-or-siblings-or-parent)
  4765. (remove-hook 'org-blocker-hook
  4766. 'org-block-todo-from-children-or-siblings-or-parent))
  4767. (if org-enforce-todo-checkbox-dependencies
  4768. (add-hook 'org-blocker-hook
  4769. 'org-block-todo-from-checkboxes)
  4770. (remove-hook 'org-blocker-hook
  4771. 'org-block-todo-from-checkboxes))
  4772. ;; Align options lines
  4773. (setq-local
  4774. align-mode-rules-list
  4775. '((org-in-buffer-settings
  4776. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4777. (modes . '(org-mode)))))
  4778. ;; Imenu
  4779. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4780. ;; Make isearch reveal context
  4781. (setq-local outline-isearch-open-invisible-function
  4782. (lambda (&rest _) (org-show-context 'isearch)))
  4783. ;; Setup the pcomplete hooks
  4784. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4785. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4786. (setq-local pcomplete-default-completion-function 'ignore)
  4787. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4788. (setq-local pcomplete-termination-string "")
  4789. (setq-local buffer-face-mode-face 'org-default)
  4790. ;; If empty file that did not turn on Org mode automatically, make
  4791. ;; it to.
  4792. (when (and org-insert-mode-line-in-empty-file
  4793. (called-interactively-p 'any)
  4794. (= (point-min) (point-max)))
  4795. (insert "# -*- mode: org -*-\n\n"))
  4796. (unless org-inhibit-startup
  4797. (org-unmodified
  4798. (when org-startup-with-beamer-mode (org-beamer-mode))
  4799. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4800. (org-table-map-tables
  4801. (cond ((and org-startup-align-all-tables
  4802. org-startup-shrink-all-tables)
  4803. (lambda () (org-table-align) (org-table-shrink)))
  4804. (org-startup-align-all-tables #'org-table-align)
  4805. (t #'org-table-shrink))
  4806. t))
  4807. (when org-startup-with-inline-images (org-display-inline-images))
  4808. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4809. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4810. (when org-startup-truncated (setq truncate-lines t))
  4811. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4812. (org-refresh-effort-properties)))
  4813. ;; Try to set `org-hide' face correctly.
  4814. (let ((foreground (org-find-invisible-foreground)))
  4815. (when foreground
  4816. (set-face-foreground 'org-hide foreground))))
  4817. ;; Update `customize-package-emacs-version-alist'
  4818. (add-to-list 'customize-package-emacs-version-alist
  4819. '(Org ("8.0" . "24.4")
  4820. ("8.1" . "24.4")
  4821. ("8.2" . "24.4")
  4822. ("8.2.7" . "24.4")
  4823. ("8.3" . "26.1")
  4824. ("9.0" . "26.1")
  4825. ("9.1" . "26.1")
  4826. ("9.2" . "27.1")))
  4827. (defvar org-mode-transpose-word-syntax-table
  4828. (let ((st (make-syntax-table text-mode-syntax-table)))
  4829. (dolist (c org-emphasis-alist st)
  4830. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4831. (when (fboundp 'abbrev-table-put)
  4832. (abbrev-table-put org-mode-abbrev-table
  4833. :parents (list text-mode-abbrev-table)))
  4834. (defun org-find-invisible-foreground ()
  4835. (let ((candidates (remove
  4836. "unspecified-bg"
  4837. (nconc
  4838. (list (face-background 'default)
  4839. (face-background 'org-default))
  4840. (mapcar
  4841. (lambda (alist)
  4842. (when (boundp alist)
  4843. (cdr (assq 'background-color (symbol-value alist)))))
  4844. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4845. (list (face-foreground 'org-hide))))))
  4846. (car (remove nil candidates))))
  4847. (defun org-current-time (&optional rounding-minutes past)
  4848. "Current time, possibly rounded to ROUNDING-MINUTES.
  4849. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4850. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4851. the rounding returns a past time."
  4852. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4853. (car org-time-stamp-rounding-minutes)))
  4854. (time (decode-time)) res)
  4855. (if (< r 1)
  4856. (current-time)
  4857. (setq res
  4858. (apply 'encode-time
  4859. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4860. (nthcdr 2 time))))
  4861. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4862. (seconds-to-time (- (float-time res) (* r 60)))
  4863. res))))
  4864. (defun org-today ()
  4865. "Return today date, considering `org-extend-today-until'."
  4866. (time-to-days
  4867. (time-subtract (current-time)
  4868. (list 0 (* 3600 org-extend-today-until) 0))))
  4869. ;;;; Font-Lock stuff, including the activators
  4870. (defvar org-mouse-map (make-sparse-keymap))
  4871. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4872. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4873. (when org-mouse-1-follows-link
  4874. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4875. (when org-tab-follows-link
  4876. (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
  4877. (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
  4878. (require 'font-lock)
  4879. (defconst org-non-link-chars "]\t\n\r<>")
  4880. (defvar org-link-types-re nil
  4881. "Matches a link that has a url-like prefix like \"http:\"")
  4882. (defvar org-link-re-with-space nil
  4883. "Matches a link with spaces, optional angular brackets around it.")
  4884. (defvar org-link-re-with-space2 nil
  4885. "Matches a link with spaces, optional angular brackets around it.")
  4886. (defvar org-link-re-with-space3 nil
  4887. "Matches a link with spaces, only for internal part in bracket links.")
  4888. (defvar org-angle-link-re nil
  4889. "Matches link with angular brackets, spaces are allowed.")
  4890. (defvar org-plain-link-re nil
  4891. "Matches plain link, without spaces.")
  4892. (defvar org-bracket-link-regexp nil
  4893. "Matches a link in double brackets.")
  4894. (defvar org-bracket-link-analytic-regexp nil
  4895. "Regular expression used to analyze links.
  4896. Here is what the match groups contain after a match:
  4897. 1: http:
  4898. 2: http
  4899. 3: path
  4900. 4: [desc]
  4901. 5: desc")
  4902. (defvar org-bracket-link-analytic-regexp++ nil
  4903. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4904. (defvar org-any-link-re nil
  4905. "Regular expression matching any link.")
  4906. (defconst org-match-sexp-depth 3
  4907. "Number of stacked braces for sub/superscript matching.")
  4908. (defun org-create-multibrace-regexp (left right n)
  4909. "Create a regular expression which will match a balanced sexp.
  4910. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4911. as single character strings.
  4912. The regexp returned will match the entire expression including the
  4913. delimiters. It will also define a single group which contains the
  4914. match except for the outermost delimiters. The maximum depth of
  4915. stacked delimiters is N. Escaping delimiters is not possible."
  4916. (let* ((nothing (concat "[^" left right "]*?"))
  4917. (or "\\|")
  4918. (re nothing)
  4919. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4920. (while (> n 1)
  4921. (setq n (1- n)
  4922. re (concat re or next)
  4923. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4924. (concat left "\\(" re "\\)" right)))
  4925. (defconst org-match-substring-regexp
  4926. (concat
  4927. "\\(\\S-\\)\\([_^]\\)\\("
  4928. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4929. "\\|"
  4930. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4931. "\\|"
  4932. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4933. "The regular expression matching a sub- or superscript.")
  4934. (defconst org-match-substring-with-braces-regexp
  4935. (concat
  4936. "\\(\\S-\\)\\([_^]\\)"
  4937. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4938. "The regular expression matching a sub- or superscript, forcing braces.")
  4939. (defun org-make-link-regexps ()
  4940. "Update the link regular expressions.
  4941. This should be called after the variable `org-link-parameters' has changed."
  4942. (let ((types-re (regexp-opt (org-link-types) t)))
  4943. (setq org-link-types-re
  4944. (concat "\\`" types-re ":")
  4945. org-link-re-with-space
  4946. (concat "<?" types-re ":"
  4947. "\\([^" org-non-link-chars " ]"
  4948. "[^" org-non-link-chars "]*"
  4949. "[^" org-non-link-chars " ]\\)>?")
  4950. org-link-re-with-space2
  4951. (concat "<?" types-re ":"
  4952. "\\([^" org-non-link-chars " ]"
  4953. "[^\t\n\r]*"
  4954. "[^" org-non-link-chars " ]\\)>?")
  4955. org-link-re-with-space3
  4956. (concat "<?" types-re ":"
  4957. "\\([^" org-non-link-chars " ]"
  4958. "[^\t\n\r]*\\)")
  4959. org-angle-link-re
  4960. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  4961. types-re)
  4962. org-plain-link-re
  4963. (concat
  4964. "\\<" types-re ":"
  4965. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  4966. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  4967. org-bracket-link-regexp
  4968. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  4969. org-bracket-link-analytic-regexp
  4970. (concat
  4971. "\\[\\["
  4972. "\\(" types-re ":\\)?"
  4973. "\\([^]]+\\)"
  4974. "\\]"
  4975. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4976. "\\]")
  4977. org-bracket-link-analytic-regexp++
  4978. (concat
  4979. "\\[\\["
  4980. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  4981. "\\([^]]+\\)"
  4982. "\\]"
  4983. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4984. "\\]")
  4985. org-any-link-re
  4986. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  4987. org-angle-link-re "\\)\\|\\("
  4988. org-plain-link-re "\\)"))))
  4989. (org-make-link-regexps)
  4990. (defvar org-emph-face nil)
  4991. (defun org-do-emphasis-faces (limit)
  4992. "Run through the buffer and emphasize strings."
  4993. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4994. (car org-emphasis-regexp-components))))
  4995. (catch :exit
  4996. (while (re-search-forward quick-re limit t)
  4997. (let* ((marker (match-string 2))
  4998. (verbatim? (member marker '("~" "="))))
  4999. (when (save-excursion
  5000. (goto-char (match-beginning 0))
  5001. (and
  5002. ;; Do not match table hlines.
  5003. (not (and (equal marker "+")
  5004. (org-match-line
  5005. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  5006. ;; Do not match headline stars. Do not consider
  5007. ;; stars of a headline as closing marker for bold
  5008. ;; markup either.
  5009. (not (and (equal marker "*")
  5010. (save-excursion
  5011. (forward-char)
  5012. (skip-chars-backward "*")
  5013. (looking-at-p org-outline-regexp-bol))))
  5014. ;; Match full emphasis markup regexp.
  5015. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  5016. ;; Do not span over paragraph boundaries.
  5017. (not (string-match-p org-element-paragraph-separate
  5018. (match-string 2)))
  5019. ;; Do not span over cells in table rows.
  5020. (not (and (save-match-data (org-match-line "[ \t]*|"))
  5021. (string-match-p "|" (match-string 4))))))
  5022. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  5023. (font-lock-prepend-text-property
  5024. (match-beginning 2) (match-end 2) 'face face)
  5025. (when verbatim?
  5026. (org-remove-flyspell-overlays-in
  5027. (match-beginning 0) (match-end 0)))
  5028. (add-text-properties (match-beginning 2) (match-end 2)
  5029. '(font-lock-multiline t org-emphasis t))
  5030. (when org-hide-emphasis-markers
  5031. (add-text-properties (match-end 4) (match-beginning 5)
  5032. '(invisible org-link))
  5033. (add-text-properties (match-beginning 3) (match-end 3)
  5034. '(invisible org-link)))
  5035. (throw :exit t))))))))
  5036. (defun org-emphasize (&optional char)
  5037. "Insert or change an emphasis, i.e. a font like bold or italic.
  5038. If there is an active region, change that region to a new emphasis.
  5039. If there is no region, just insert the marker characters and position
  5040. the cursor between them.
  5041. CHAR should be the marker character. If it is a space, it means to
  5042. remove the emphasis of the selected region.
  5043. If CHAR is not given (for example in an interactive call) it will be
  5044. prompted for."
  5045. (interactive)
  5046. (let ((erc org-emphasis-regexp-components)
  5047. (string "") beg end move s)
  5048. (if (org-region-active-p)
  5049. (setq beg (region-beginning)
  5050. end (region-end)
  5051. string (buffer-substring beg end))
  5052. (setq move t))
  5053. (unless char
  5054. (message "Emphasis marker or tag: [%s]"
  5055. (mapconcat #'car org-emphasis-alist ""))
  5056. (setq char (read-char-exclusive)))
  5057. (if (equal char ?\s)
  5058. (setq s ""
  5059. move nil)
  5060. (unless (assoc (char-to-string char) org-emphasis-alist)
  5061. (user-error "No such emphasis marker: \"%c\"" char))
  5062. (setq s (char-to-string char)))
  5063. (while (and (> (length string) 1)
  5064. (equal (substring string 0 1) (substring string -1))
  5065. (assoc (substring string 0 1) org-emphasis-alist))
  5066. (setq string (substring string 1 -1)))
  5067. (setq string (concat s string s))
  5068. (when beg (delete-region beg end))
  5069. (unless (or (bolp)
  5070. (string-match (concat "[" (nth 0 erc) "\n]")
  5071. (char-to-string (char-before (point)))))
  5072. (insert " "))
  5073. (unless (or (eobp)
  5074. (string-match (concat "[" (nth 1 erc) "\n]")
  5075. (char-to-string (char-after (point)))))
  5076. (insert " ") (backward-char 1))
  5077. (insert string)
  5078. (and move (backward-char 1))))
  5079. (defconst org-nonsticky-props
  5080. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5081. (defsubst org-rear-nonsticky-at (pos)
  5082. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5083. (defun org-activate-links (limit)
  5084. "Add link properties to links.
  5085. This includes angle, plain, and bracket links."
  5086. (catch :exit
  5087. (while (re-search-forward org-any-link-re limit t)
  5088. (let* ((start (match-beginning 0))
  5089. (end (match-end 0))
  5090. (style (cond ((eq ?< (char-after start)) 'angle)
  5091. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5092. (t 'plain))))
  5093. (when (and (memq style org-highlight-links)
  5094. ;; Do not confuse plain links with tags.
  5095. (not (and (eq style 'plain)
  5096. (let ((face (get-text-property
  5097. (max (1- start) (point-min)) 'face)))
  5098. (if (consp face) (memq 'org-tag face)
  5099. (eq 'org-tag face))))))
  5100. (let* ((link-object (save-excursion
  5101. (goto-char start)
  5102. (save-match-data (org-element-link-parser))))
  5103. (link (org-element-property :raw-link link-object))
  5104. (type (org-element-property :type link-object))
  5105. (path (org-element-property :path link-object))
  5106. (properties ;for link's visible part
  5107. (list
  5108. 'face (pcase (org-link-get-parameter type :face)
  5109. ((and (pred functionp) face) (funcall face path))
  5110. ((and (pred facep) face) face)
  5111. ((and (pred consp) face) face) ;anonymous
  5112. (_ 'org-link))
  5113. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5114. 'highlight)
  5115. 'keymap (or (org-link-get-parameter type :keymap)
  5116. org-mouse-map)
  5117. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5118. ((and (pred stringp) echo) echo)
  5119. ((and (pred functionp) echo) echo)
  5120. (_ (concat "LINK: " link)))
  5121. 'htmlize-link (pcase (org-link-get-parameter type
  5122. :htmlize-link)
  5123. ((and (pred functionp) f) (funcall f))
  5124. (_ `(:uri ,link)))
  5125. 'font-lock-multiline t)))
  5126. (org-remove-flyspell-overlays-in start end)
  5127. (org-rear-nonsticky-at end)
  5128. (if (not (eq 'bracket style))
  5129. (add-text-properties start end properties)
  5130. ;; Handle invisible parts in bracket links.
  5131. (remove-text-properties start end '(invisible nil))
  5132. (let ((hidden
  5133. (append `(invisible
  5134. ,(or (org-link-get-parameter type :display)
  5135. 'org-link))
  5136. properties))
  5137. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5138. (visible-end (or (match-end 4) (match-end 2))))
  5139. (add-text-properties start visible-start hidden)
  5140. (add-text-properties visible-start visible-end properties)
  5141. (add-text-properties visible-end end hidden)
  5142. (org-rear-nonsticky-at visible-start)
  5143. (org-rear-nonsticky-at visible-end)))
  5144. (let ((f (org-link-get-parameter type :activate-func)))
  5145. (when (functionp f)
  5146. (funcall f start end path (eq style 'bracket))))
  5147. (throw :exit t))))) ;signal success
  5148. nil))
  5149. (defun org-activate-code (limit)
  5150. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5151. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5152. (remove-text-properties (match-beginning 0) (match-end 0)
  5153. '(display t invisible t intangible t))
  5154. t))
  5155. (defcustom org-src-fontify-natively t
  5156. "When non-nil, fontify code in code blocks.
  5157. See also the `org-block' face."
  5158. :type 'boolean
  5159. :version "26.1"
  5160. :package-version '(Org . "8.3")
  5161. :group 'org-appearance
  5162. :group 'org-babel)
  5163. (defcustom org-allow-promoting-top-level-subtree nil
  5164. "When non-nil, allow promoting a top level subtree.
  5165. The leading star of the top level headline will be replaced
  5166. by a #."
  5167. :type 'boolean
  5168. :version "24.1"
  5169. :group 'org-appearance)
  5170. (defun org-fontify-meta-lines-and-blocks (limit)
  5171. (condition-case nil
  5172. (org-fontify-meta-lines-and-blocks-1 limit)
  5173. (error (message "Org mode fontification error in %S at %d"
  5174. (current-buffer)
  5175. (line-number-at-pos)))))
  5176. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5177. "Fontify #+ lines and blocks."
  5178. (let ((case-fold-search t))
  5179. (when (re-search-forward
  5180. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5181. limit t)
  5182. (let ((beg (match-beginning 0))
  5183. (block-start (match-end 0))
  5184. (block-end nil)
  5185. (lang (match-string 7))
  5186. (beg1 (line-beginning-position 2))
  5187. (dc1 (downcase (match-string 2)))
  5188. (dc3 (downcase (match-string 3)))
  5189. end end1 quoting block-type)
  5190. (cond
  5191. ((and (match-end 4) (equal dc3 "+begin"))
  5192. ;; Truly a block
  5193. (setq block-type (downcase (match-string 5))
  5194. quoting (member block-type org-protecting-blocks))
  5195. (when (re-search-forward
  5196. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5197. nil t) ;; on purpose, we look further than LIMIT
  5198. (setq end (min (point-max) (match-end 0))
  5199. end1 (min (point-max) (1- (match-beginning 0))))
  5200. (setq block-end (match-beginning 0))
  5201. (when quoting
  5202. (org-remove-flyspell-overlays-in beg1 end1)
  5203. (remove-text-properties beg end
  5204. '(display t invisible t intangible t)))
  5205. (add-text-properties
  5206. beg end '(font-lock-fontified t font-lock-multiline t))
  5207. (add-text-properties beg beg1 '(face org-meta-line))
  5208. (org-remove-flyspell-overlays-in beg beg1)
  5209. (add-text-properties ; For end_src
  5210. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5211. (org-remove-flyspell-overlays-in end1 end)
  5212. (cond
  5213. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5214. (org-src-font-lock-fontify-block lang block-start block-end)
  5215. (add-text-properties beg1 block-end '(src-block t)))
  5216. (quoting
  5217. (add-text-properties beg1 (min (point-max) (1+ end1))
  5218. (list 'face
  5219. (list :inherit
  5220. (let ((face-name
  5221. (intern (format "org-block-%s" lang))))
  5222. (append (and (facep face-name) (list face-name))
  5223. '(org-block))))))) ; end of source block
  5224. ((not org-fontify-quote-and-verse-blocks))
  5225. ((string= block-type "quote")
  5226. (add-face-text-property
  5227. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5228. ((string= block-type "verse")
  5229. (add-face-text-property
  5230. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5231. (add-text-properties beg beg1 '(face org-block-begin-line))
  5232. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5233. '(face org-block-end-line))
  5234. t))
  5235. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5236. (org-remove-flyspell-overlays-in
  5237. (match-beginning 0)
  5238. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5239. (add-text-properties
  5240. beg (match-end 3)
  5241. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5242. '(font-lock-fontified t invisible t)
  5243. '(font-lock-fontified t face org-document-info-keyword)))
  5244. (add-text-properties
  5245. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5246. (if (string-equal dc1 "+title:")
  5247. '(font-lock-fontified t face org-document-title)
  5248. '(font-lock-fontified t face org-document-info))))
  5249. ((string-prefix-p "+caption" dc1)
  5250. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5251. (remove-text-properties (match-beginning 0) (match-end 0)
  5252. '(display t invisible t intangible t))
  5253. ;; Handle short captions.
  5254. (save-excursion
  5255. (beginning-of-line)
  5256. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5257. (add-text-properties (line-beginning-position) (match-end 1)
  5258. '(font-lock-fontified t face org-meta-line))
  5259. (add-text-properties (match-end 0) (line-end-position)
  5260. '(font-lock-fontified t face org-block))
  5261. t)
  5262. ((member dc3 '(" " ""))
  5263. (org-remove-flyspell-overlays-in beg (match-end 0))
  5264. (add-text-properties
  5265. beg (match-end 0)
  5266. '(font-lock-fontified t face font-lock-comment-face)))
  5267. (t ;; just any other in-buffer setting, but not indented
  5268. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5269. (remove-text-properties (match-beginning 0) (match-end 0)
  5270. '(display t invisible t intangible t))
  5271. (add-text-properties beg (match-end 0)
  5272. '(font-lock-fontified t face org-meta-line))
  5273. t))))))
  5274. (defun org-fontify-drawers (limit)
  5275. "Fontify drawers."
  5276. (when (re-search-forward org-drawer-regexp limit t)
  5277. (add-text-properties
  5278. (match-beginning 0) (match-end 0)
  5279. '(font-lock-fontified t face org-special-keyword))
  5280. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5281. t))
  5282. (defun org-fontify-macros (limit)
  5283. "Fontify macros."
  5284. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  5285. (let ((begin (match-beginning 0))
  5286. (opening-end (match-beginning 1)))
  5287. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  5288. (match-string 1))
  5289. (let ((end (match-end 1))
  5290. (closing-start (match-beginning 1)))
  5291. (add-text-properties
  5292. begin end
  5293. '(font-lock-multiline t font-lock-fontified t face org-macro))
  5294. (org-remove-flyspell-overlays-in begin end)
  5295. (when org-hide-macro-markers
  5296. (add-text-properties begin opening-end '(invisible t))
  5297. (add-text-properties closing-start end '(invisible t)))
  5298. t)))))
  5299. (defun org-activate-footnote-links (limit)
  5300. "Add text properties for footnotes."
  5301. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5302. (when fn
  5303. (let* ((beg (nth 1 fn))
  5304. (end (nth 2 fn))
  5305. (label (car fn))
  5306. (referencep (/= (line-beginning-position) beg)))
  5307. (when (and referencep (nth 3 fn))
  5308. (save-excursion
  5309. (goto-char beg)
  5310. (search-forward (or label "fn:"))
  5311. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5312. (add-text-properties beg end
  5313. (list 'mouse-face 'highlight
  5314. 'keymap org-mouse-map
  5315. 'help-echo
  5316. (if referencep "Footnote reference"
  5317. "Footnote definition")
  5318. 'font-lock-fontified t
  5319. 'font-lock-multiline t
  5320. 'face 'org-footnote))))))
  5321. (defun org-activate-dates (limit)
  5322. "Add text properties for dates."
  5323. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5324. (not (equal (char-before (match-beginning 0)) 91)))
  5325. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5326. (add-text-properties (match-beginning 0) (match-end 0)
  5327. (list 'mouse-face 'highlight
  5328. 'keymap org-mouse-map))
  5329. (org-rear-nonsticky-at (match-end 0))
  5330. (when org-display-custom-times
  5331. ;; If it's a date range, activate custom time for second date.
  5332. (when (match-end 3)
  5333. (org-display-custom-time (match-beginning 3) (match-end 3)))
  5334. (org-display-custom-time (match-beginning 1) (match-end 1)))
  5335. t))
  5336. (defvar-local org-target-link-regexp nil
  5337. "Regular expression matching radio targets in plain text.")
  5338. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5339. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5340. border border border))
  5341. "Regular expression matching a link target.")
  5342. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5343. "Regular expression matching a radio target.")
  5344. (defconst org-any-target-regexp
  5345. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5346. "Regular expression matching any target.")
  5347. (defun org-activate-target-links (limit)
  5348. "Add text properties for target matches."
  5349. (when org-target-link-regexp
  5350. (let ((case-fold-search t))
  5351. (when (re-search-forward org-target-link-regexp limit t)
  5352. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5353. (add-text-properties (match-beginning 1) (match-end 1)
  5354. (list 'mouse-face 'highlight
  5355. 'keymap org-mouse-map
  5356. 'help-echo "Radio target link"
  5357. 'org-linked-text t))
  5358. (org-rear-nonsticky-at (match-end 1))
  5359. t))))
  5360. (defun org-update-radio-target-regexp ()
  5361. "Find all radio targets in this file and update the regular expression.
  5362. Also refresh fontification if needed."
  5363. (interactive)
  5364. (let ((old-regexp org-target-link-regexp)
  5365. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5366. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5367. (targets
  5368. (org-with-wide-buffer
  5369. (goto-char (point-min))
  5370. (let (rtn)
  5371. (while (re-search-forward org-radio-target-regexp nil t)
  5372. ;; Make sure point is really within the object.
  5373. (backward-char)
  5374. (let ((obj (org-element-context)))
  5375. (when (eq (org-element-type obj) 'radio-target)
  5376. (cl-pushnew (org-element-property :value obj) rtn
  5377. :test #'equal))))
  5378. rtn))))
  5379. (setq org-target-link-regexp
  5380. (and targets
  5381. (concat before-re
  5382. (mapconcat
  5383. (lambda (x)
  5384. (replace-regexp-in-string
  5385. " +" "\\s-+" (regexp-quote x) t t))
  5386. targets
  5387. "\\|")
  5388. after-re)))
  5389. (unless (equal old-regexp org-target-link-regexp)
  5390. ;; Clean-up cache.
  5391. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5392. ((not org-target-link-regexp) old-regexp)
  5393. (t
  5394. (concat before-re
  5395. (mapconcat
  5396. (lambda (re)
  5397. (substring re (length before-re)
  5398. (- (length after-re))))
  5399. (list old-regexp org-target-link-regexp)
  5400. "\\|")
  5401. after-re)))))
  5402. (org-with-wide-buffer
  5403. (goto-char (point-min))
  5404. (while (re-search-forward regexp nil t)
  5405. (org-element-cache-refresh (match-beginning 1)))))
  5406. ;; Re fontify buffer.
  5407. (when (memq 'radio org-highlight-links)
  5408. (org-restart-font-lock)))))
  5409. (defvar org-latex-and-related-regexp nil
  5410. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5411. (defun org-compute-latex-and-related-regexp ()
  5412. "Compute regular expression for LaTeX, entities and sub/superscript.
  5413. Result depends on variable `org-highlight-latex-and-related'."
  5414. (setq-local
  5415. org-latex-and-related-regexp
  5416. (let* ((re-sub
  5417. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5418. ((eq org-use-sub-superscripts '{})
  5419. (list org-match-substring-with-braces-regexp))
  5420. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5421. (re-latex
  5422. (when (memq 'latex org-highlight-latex-and-related)
  5423. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5424. (delq nil
  5425. (mapcar (lambda (x)
  5426. (and (member (car x) matchers) (nth 1 x)))
  5427. org-latex-regexps)))))
  5428. (re-entities
  5429. (when (memq 'entities org-highlight-latex-and-related)
  5430. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5431. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5432. (defun org-do-latex-and-related (limit)
  5433. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5434. LIMIT bounds the search for syntax to highlight. Stop at first
  5435. highlighted object, if any. Return t if some highlighting was
  5436. done, nil otherwise."
  5437. (when (org-string-nw-p org-latex-and-related-regexp)
  5438. (catch 'found
  5439. (while (re-search-forward org-latex-and-related-regexp limit t)
  5440. (unless
  5441. (cl-some
  5442. (lambda (f)
  5443. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5444. (save-excursion
  5445. (goto-char (1+ (match-beginning 0)))
  5446. (face-at-point nil t)))
  5447. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5448. '(?_ ?^))
  5449. 1
  5450. 0)))
  5451. (font-lock-prepend-text-property
  5452. (+ offset (match-beginning 0)) (match-end 0)
  5453. 'face 'org-latex-and-related)
  5454. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5455. '(font-lock-multiline t)))
  5456. (throw 'found t)))
  5457. nil)))
  5458. (defun org-restart-font-lock ()
  5459. "Restart `font-lock-mode', to force refontification."
  5460. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5461. (font-lock-mode -1)
  5462. (font-lock-mode 1)))
  5463. (defun org-activate-tags (limit)
  5464. (when (re-search-forward org-tag-line-re limit t)
  5465. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5466. (add-text-properties (match-beginning 1) (match-end 1)
  5467. (list 'mouse-face 'highlight
  5468. 'keymap org-mouse-map))
  5469. (org-rear-nonsticky-at (match-end 1))
  5470. t))
  5471. (defun org-outline-level ()
  5472. "Compute the outline level of the heading at point.
  5473. If this is called at a normal headline, the level is the number
  5474. of stars. Use `org-reduced-level' to remove the effect of
  5475. `org-odd-levels'. Unlike to `org-current-level', this function
  5476. takes into consideration inlinetasks."
  5477. (org-with-wide-buffer
  5478. (end-of-line)
  5479. (if (re-search-backward org-outline-regexp-bol nil t)
  5480. (1- (- (match-end 0) (match-beginning 0)))
  5481. 0)))
  5482. (defvar org-font-lock-keywords nil)
  5483. (defsubst org-re-property (property &optional literal allow-null value)
  5484. "Return a regexp matching a PROPERTY line.
  5485. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5486. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5487. non-nil, match properties even without a value.
  5488. Match group 3 is set to the value when it exists. If there is no
  5489. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5490. With optional argument VALUE, match only property lines with
  5491. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5492. unless LITERAL is non-nil."
  5493. (concat
  5494. "^\\(?4:[ \t]*\\)"
  5495. (format "\\(?1::\\(?2:%s\\):\\)"
  5496. (if literal property (regexp-quote property)))
  5497. (cond (value
  5498. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5499. (if literal value (regexp-quote value))))
  5500. (allow-null
  5501. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5502. (t
  5503. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5504. (defconst org-property-re
  5505. (org-re-property "\\S-+" 'literal t)
  5506. "Regular expression matching a property line.
  5507. There are four matching groups:
  5508. 1: :PROPKEY: including the leading and trailing colon,
  5509. 2: PROPKEY without the leading and trailing colon,
  5510. 3: PROPVAL without leading or trailing spaces,
  5511. 4: the indentation of the current line,
  5512. 5: trailing whitespace.")
  5513. (defvar org-font-lock-hook nil
  5514. "Functions to be called for special font lock stuff.")
  5515. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5516. (defvar org-font-lock-set-keywords-hook nil
  5517. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5518. This is called after `org-font-lock-extra-keywords' is defined, but before
  5519. it is installed to be used by font lock. This can be useful if something
  5520. needs to be inserted at a specific position in the font-lock sequence.")
  5521. (defun org-font-lock-hook (limit)
  5522. "Run `org-font-lock-hook' within LIMIT."
  5523. (run-hook-with-args 'org-font-lock-hook limit))
  5524. (defun org-set-font-lock-defaults ()
  5525. "Set font lock defaults for the current buffer."
  5526. (let* ((em org-fontify-emphasized-text)
  5527. (lk org-highlight-links)
  5528. (org-font-lock-extra-keywords
  5529. (list
  5530. ;; Call the hook
  5531. '(org-font-lock-hook)
  5532. ;; Headlines
  5533. `(,(if org-fontify-whole-heading-line
  5534. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5535. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5536. (1 (org-get-level-face 1))
  5537. (2 (org-get-level-face 2))
  5538. (3 (org-get-level-face 3)))
  5539. ;; Table lines
  5540. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5541. (1 'org-table t))
  5542. ;; Table internals
  5543. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5544. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5545. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5546. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5547. ;; Drawers
  5548. '(org-fontify-drawers)
  5549. ;; Properties
  5550. (list org-property-re
  5551. '(1 'org-special-keyword t)
  5552. '(3 'org-property-value t))
  5553. ;; Link related fontification.
  5554. '(org-activate-links)
  5555. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5556. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5557. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5558. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5559. ;; Targets.
  5560. (list org-any-target-regexp '(0 'org-target t))
  5561. ;; Diary sexps.
  5562. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5563. ;; Macro
  5564. '(org-fontify-macros)
  5565. ;; TODO keyword
  5566. (list (format org-heading-keyword-regexp-format
  5567. org-todo-regexp)
  5568. '(2 (org-get-todo-face 2) t))
  5569. ;; DONE
  5570. (if org-fontify-done-headline
  5571. (list (format org-heading-keyword-regexp-format
  5572. (concat
  5573. "\\(?:"
  5574. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5575. "\\)"))
  5576. '(2 'org-headline-done t))
  5577. nil)
  5578. ;; Priorities
  5579. '(org-font-lock-add-priority-faces)
  5580. ;; Tags
  5581. '(org-font-lock-add-tag-faces)
  5582. ;; Tags groups
  5583. (when (and org-group-tags org-tag-groups-alist)
  5584. (list (concat org-outline-regexp-bol ".+\\(:"
  5585. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5586. ":\\).*$")
  5587. '(1 'org-tag-group prepend)))
  5588. ;; Special keywords
  5589. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5590. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5591. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5592. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5593. ;; Emphasis
  5594. (when em '(org-do-emphasis-faces))
  5595. ;; Checkboxes
  5596. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5597. 1 'org-checkbox prepend)
  5598. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5599. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5600. (0 (org-get-checkbox-statistics-face) t)))
  5601. ;; Description list items
  5602. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5603. 1 'org-list-dt prepend)
  5604. ;; ARCHIVEd headings
  5605. (list (concat
  5606. org-outline-regexp-bol
  5607. "\\(.*:" org-archive-tag ":.*\\)")
  5608. '(1 'org-archived prepend))
  5609. ;; Specials
  5610. '(org-do-latex-and-related)
  5611. '(org-fontify-entities)
  5612. '(org-raise-scripts)
  5613. ;; Code
  5614. '(org-activate-code (1 'org-code t))
  5615. ;; COMMENT
  5616. (list (format
  5617. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5618. org-todo-regexp
  5619. org-comment-string)
  5620. '(9 'org-special-keyword t))
  5621. ;; Blocks and meta lines
  5622. '(org-fontify-meta-lines-and-blocks))))
  5623. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5624. (run-hooks 'org-font-lock-set-keywords-hook)
  5625. ;; Now set the full font-lock-keywords
  5626. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5627. (setq-local font-lock-defaults
  5628. '(org-font-lock-keywords t nil nil backward-paragraph))
  5629. (kill-local-variable 'font-lock-keywords)
  5630. nil))
  5631. (defun org-toggle-pretty-entities ()
  5632. "Toggle the composition display of entities as UTF8 characters."
  5633. (interactive)
  5634. (setq-local org-pretty-entities (not org-pretty-entities))
  5635. (org-restart-font-lock)
  5636. (if org-pretty-entities
  5637. (message "Entities are now displayed as UTF8 characters")
  5638. (save-restriction
  5639. (widen)
  5640. (decompose-region (point-min) (point-max))
  5641. (message "Entities are now displayed as plain text"))))
  5642. (defvar-local org-custom-properties-overlays nil
  5643. "List of overlays used for custom properties.")
  5644. (defun org-toggle-custom-properties-visibility ()
  5645. "Display or hide properties in `org-custom-properties'."
  5646. (interactive)
  5647. (if org-custom-properties-overlays
  5648. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5649. (setq org-custom-properties-overlays nil))
  5650. (when org-custom-properties
  5651. (org-with-wide-buffer
  5652. (goto-char (point-min))
  5653. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5654. (while (re-search-forward regexp nil t)
  5655. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5656. (when (and end (< (point) end))
  5657. ;; Hide first custom property in current drawer.
  5658. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5659. (overlay-put o 'invisible t)
  5660. (overlay-put o 'org-custom-property t)
  5661. (push o org-custom-properties-overlays))
  5662. ;; Hide additional custom properties in the same drawer.
  5663. (while (re-search-forward regexp end t)
  5664. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5665. (overlay-put o 'invisible t)
  5666. (overlay-put o 'org-custom-property t)
  5667. (push o org-custom-properties-overlays)))))
  5668. ;; Each entry is limited to a single property drawer.
  5669. (outline-next-heading)))))))
  5670. (defun org-fontify-entities (limit)
  5671. "Find an entity to fontify."
  5672. (let (ee)
  5673. (when org-pretty-entities
  5674. (catch 'match
  5675. ;; "\_ "-family is left out on purpose. Only the first one,
  5676. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5677. ;; confusing when adding a second white space character.
  5678. (while (re-search-forward
  5679. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5680. limit t)
  5681. (when (and (not (org-at-comment-p))
  5682. (setq ee (org-entity-get (match-string 1)))
  5683. (= (length (nth 6 ee)) 1))
  5684. (let* ((end (if (equal (match-string 2) "{}")
  5685. (match-end 2)
  5686. (match-end 1))))
  5687. (add-text-properties
  5688. (match-beginning 0) end
  5689. (list 'font-lock-fontified t))
  5690. (compose-region (match-beginning 0) end
  5691. (nth 6 ee) nil)
  5692. (backward-char 1)
  5693. (throw 'match t))))
  5694. nil))))
  5695. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5696. "Fontify string S like in Org mode."
  5697. (with-temp-buffer
  5698. (insert s)
  5699. (let ((org-odd-levels-only odd-levels))
  5700. (org-mode)
  5701. (org-font-lock-ensure)
  5702. (buffer-string))))
  5703. (defvar org-m nil)
  5704. (defvar org-l nil)
  5705. (defvar org-f nil)
  5706. (defun org-get-level-face (n)
  5707. "Get the right face for match N in font-lock matching of headlines."
  5708. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5709. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5710. (if org-cycle-level-faces
  5711. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5712. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5713. (cond
  5714. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5715. ((eq n 2) org-f)
  5716. (t (unless org-level-color-stars-only org-f))))
  5717. (defun org-face-from-face-or-color (context inherit face-or-color)
  5718. "Create a face list that inherits INHERIT, but sets the foreground color.
  5719. When FACE-OR-COLOR is not a string, just return it."
  5720. (if (stringp face-or-color)
  5721. (list :inherit inherit
  5722. (cdr (assoc context org-faces-easy-properties))
  5723. face-or-color)
  5724. face-or-color))
  5725. (defun org-get-todo-face (kwd)
  5726. "Get the right face for a TODO keyword KWD.
  5727. If KWD is a number, get the corresponding match group."
  5728. (when (numberp kwd) (setq kwd (match-string kwd)))
  5729. (or (org-face-from-face-or-color
  5730. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5731. (and (member kwd org-done-keywords) 'org-done)
  5732. 'org-todo))
  5733. (defun org-get-priority-face (priority)
  5734. "Get the right face for PRIORITY.
  5735. PRIORITY is a character."
  5736. (or (org-face-from-face-or-color
  5737. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5738. 'org-priority))
  5739. (defun org-get-tag-face (tag)
  5740. "Get the right face for TAG.
  5741. If TAG is a number, get the corresponding match group."
  5742. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5743. (or (org-face-from-face-or-color
  5744. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5745. 'org-tag)))
  5746. (defun org-font-lock-add-priority-faces (limit)
  5747. "Add the special priority faces."
  5748. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5749. (add-text-properties
  5750. (match-beginning 1) (match-end 1)
  5751. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5752. 'font-lock-fontified t))))
  5753. (defun org-font-lock-add-tag-faces (limit)
  5754. "Add the special tag faces."
  5755. (when (and org-tag-faces org-tags-special-faces-re)
  5756. (while (re-search-forward org-tags-special-faces-re limit t)
  5757. (add-text-properties (match-beginning 1) (match-end 1)
  5758. (list 'face (org-get-tag-face 1)
  5759. 'font-lock-fontified t))
  5760. (backward-char 1))))
  5761. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5762. "Remove fontification and activation overlays from links."
  5763. (font-lock-default-unfontify-region beg end)
  5764. (let* ((buffer-undo-list t)
  5765. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5766. (inhibit-modification-hooks t)
  5767. deactivate-mark buffer-file-name buffer-file-truename)
  5768. (decompose-region beg end)
  5769. (remove-text-properties beg end
  5770. '(mouse-face t keymap t org-linked-text t
  5771. invisible t intangible t
  5772. org-emphasis t))
  5773. (org-remove-font-lock-display-properties beg end)))
  5774. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5775. ((raise 0.3) (height 0.7))
  5776. ((raise -0.5))
  5777. ((raise 0.5)))
  5778. "Display properties for showing superscripts and subscripts.")
  5779. (defun org-remove-font-lock-display-properties (beg end)
  5780. "Remove specific display properties that have been added by font lock.
  5781. The will remove the raise properties that are used to show superscripts
  5782. and subscripts."
  5783. (let (next prop)
  5784. (while (< beg end)
  5785. (setq next (next-single-property-change beg 'display nil end)
  5786. prop (get-text-property beg 'display))
  5787. (when (member prop org-script-display)
  5788. (put-text-property beg next 'display nil))
  5789. (setq beg next))))
  5790. (defun org-raise-scripts (limit)
  5791. "Add raise properties to sub/superscripts."
  5792. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5793. (re-search-forward
  5794. (if (eq org-use-sub-superscripts t)
  5795. org-match-substring-regexp
  5796. org-match-substring-with-braces-regexp)
  5797. limit t))
  5798. (let* ((pos (point)) table-p comment-p
  5799. (mpos (match-beginning 3))
  5800. (emph-p (get-text-property mpos 'org-emphasis))
  5801. (link-p (get-text-property mpos 'mouse-face))
  5802. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5803. (goto-char (point-at-bol))
  5804. (setq table-p (looking-at-p org-table-dataline-regexp)
  5805. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5806. (goto-char pos)
  5807. ;; Handle a_b^c
  5808. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5809. (unless (or comment-p emph-p link-p keyw-p)
  5810. (put-text-property (match-beginning 3) (match-end 0)
  5811. 'display
  5812. (if (equal (char-after (match-beginning 2)) ?^)
  5813. (nth (if table-p 3 1) org-script-display)
  5814. (nth (if table-p 2 0) org-script-display)))
  5815. (add-text-properties (match-beginning 2) (match-end 2)
  5816. (list 'invisible t))
  5817. (when (and (eq (char-after (match-beginning 3)) ?{)
  5818. (eq (char-before (match-end 3)) ?}))
  5819. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5820. (list 'invisible t))
  5821. (add-text-properties (1- (match-end 3)) (match-end 3)
  5822. (list 'invisible t))))
  5823. t)))
  5824. (defun org-remove-empty-overlays-at (pos)
  5825. "Remove outline overlays that do not contain non-white stuff."
  5826. (dolist (o (overlays-at pos))
  5827. (and (eq 'outline (overlay-get o 'invisible))
  5828. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5829. (overlay-end o))))
  5830. (delete-overlay o))))
  5831. (defun org-show-empty-lines-in-parent ()
  5832. "Move to the parent and re-show empty lines before visible headlines."
  5833. (save-excursion
  5834. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5835. (org-cycle-show-empty-lines context))))
  5836. (defun org-files-list ()
  5837. "Return `org-agenda-files' list, plus all open Org files.
  5838. This is useful for operations that need to scan all of a user's
  5839. open and agenda-wise Org files."
  5840. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5841. (dolist (buf (buffer-list))
  5842. (with-current-buffer buf
  5843. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5844. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5845. :test #'equal))))
  5846. files))
  5847. (defsubst org-entry-beginning-position ()
  5848. "Return the beginning position of the current entry."
  5849. (save-excursion (org-back-to-heading t) (point)))
  5850. (defsubst org-entry-end-position ()
  5851. "Return the end position of the current entry."
  5852. (save-excursion (outline-next-heading) (point)))
  5853. (defun org-subtree-end-visible-p ()
  5854. "Is the end of the current subtree visible?"
  5855. (pos-visible-in-window-p
  5856. (save-excursion (org-end-of-subtree t) (point))))
  5857. (defun org-first-headline-recenter ()
  5858. "Move cursor to the first headline and recenter the headline."
  5859. (let ((window (get-buffer-window)))
  5860. (when window
  5861. (goto-char (point-min))
  5862. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5863. (set-window-start window (line-beginning-position))))))
  5864. ;;; Visibility (headlines, blocks, drawers)
  5865. ;;;; Headlines visibility
  5866. (defun org-show-entry ()
  5867. "Show the body directly following this heading.
  5868. Show the heading too, if it is currently invisible."
  5869. (interactive)
  5870. (save-excursion
  5871. (ignore-errors
  5872. (org-back-to-heading t)
  5873. (org-flag-region
  5874. (line-end-position 0)
  5875. (save-excursion
  5876. (if (re-search-forward
  5877. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5878. (match-beginning 1)
  5879. (point-max)))
  5880. nil
  5881. 'outline))))
  5882. (defun org-show-children (&optional level)
  5883. "Show all direct subheadings of this heading.
  5884. Prefix arg LEVEL is how many levels below the current level
  5885. should be shown. Default is enough to cause the following
  5886. heading to appear."
  5887. (interactive "p")
  5888. (save-excursion
  5889. (org-back-to-heading t)
  5890. (let* ((current-level (funcall outline-level))
  5891. (max-level (org-get-valid-level
  5892. current-level
  5893. (if level (prefix-numeric-value level) 1)))
  5894. (end (save-excursion (org-end-of-subtree t t)))
  5895. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5896. (past-first-child nil)
  5897. ;; Make sure to skip inlinetasks.
  5898. (re (format regexp-fmt
  5899. current-level
  5900. (cond
  5901. ((not (featurep 'org-inlinetask)) "")
  5902. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5903. 3))
  5904. (t (1- org-inlinetask-min-level))))))
  5905. ;; Display parent heading.
  5906. (org-flag-heading nil)
  5907. (forward-line)
  5908. ;; Display children. First child may be deeper than expected
  5909. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5910. ;; MAX-LEVEL accordingly.
  5911. (while (re-search-forward re end t)
  5912. (unless past-first-child
  5913. (setq re (format regexp-fmt
  5914. current-level
  5915. (max (funcall outline-level) max-level)))
  5916. (setq past-first-child t))
  5917. (org-flag-heading nil)))))
  5918. (defun org-show-subtree ()
  5919. "Show everything after this heading at deeper levels."
  5920. (interactive)
  5921. (org-flag-region
  5922. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5923. ;;;; Blocks visibility
  5924. (defun org-hide-block-toggle-maybe ()
  5925. "Toggle visibility of block at point.
  5926. Unlike to `org-hide-block-toggle', this function does not throw
  5927. an error. Return a non-nil value when toggling is successful."
  5928. (interactive)
  5929. (ignore-errors (org-hide-block-toggle)))
  5930. (defun org-hide-block-toggle (&optional force)
  5931. "Toggle the visibility of the current block.
  5932. When optional argument FORCE is `off', make block visible. If it
  5933. is non-nil, hide it unconditionally. Throw an error when not at
  5934. a block. Return a non-nil value when toggling is successful."
  5935. (interactive)
  5936. (let ((element (org-element-at-point)))
  5937. (unless (memq (org-element-type element)
  5938. '(center-block comment-block dynamic-block example-block
  5939. export-block quote-block special-block
  5940. src-block verse-block))
  5941. (user-error "Not at a block"))
  5942. (let* ((post (org-element-property :post-affiliated element))
  5943. (start (save-excursion
  5944. (goto-char post)
  5945. (line-end-position)))
  5946. (end (save-excursion
  5947. (goto-char (org-element-property :end element))
  5948. (skip-chars-backward " \t\n")
  5949. (line-end-position))))
  5950. ;; Do nothing when not before or at the block opening line or at
  5951. ;; the block closing line.
  5952. (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
  5953. (cond ((eq force 'off)
  5954. (org-flag-region start end nil 'org-hide-block))
  5955. (force
  5956. (org-flag-region start end t 'org-hide-block))
  5957. ((eq (get-char-property start 'invisible) 'org-hide-block)
  5958. (org-flag-region start end nil 'org-hide-block))
  5959. (t
  5960. (org-flag-region start end t 'org-hide-block)))
  5961. ;; When the block is hidden away, make sure point is left in
  5962. ;; a visible part of the buffer.
  5963. (when (invisible-p (max (1- (point)) (point-min)))
  5964. (goto-char post))
  5965. ;; Signal success.
  5966. t))))
  5967. (defun org-hide-block-toggle-all ()
  5968. "Toggle the visibility of all blocks in the current buffer."
  5969. (org-block-map 'org-hide-block-toggle))
  5970. (defun org-hide-block-all ()
  5971. "Fold all blocks in the current buffer."
  5972. (interactive)
  5973. (org-show-all '(blocks))
  5974. (org-block-map 'org-hide-block-toggle-maybe))
  5975. ;;;; Drawers visibility
  5976. (defun org-cycle-hide-drawers (state &optional exceptions)
  5977. "Re-hide all drawers after a visibility state change.
  5978. STATE should be one of the symbols listed in the docstring of
  5979. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  5980. a list of strings specifying which drawers should not be hidden."
  5981. (when (and (derived-mode-p 'org-mode)
  5982. (not (memq state '(overview folded contents))))
  5983. (save-excursion
  5984. (let* ((globalp (eq state 'all))
  5985. (beg (if globalp (point-min) (point)))
  5986. (end (if globalp (point-max)
  5987. (if (eq state 'children)
  5988. (save-excursion (outline-next-heading) (point))
  5989. (org-end-of-subtree t)))))
  5990. (goto-char beg)
  5991. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  5992. (unless (member-ignore-case (match-string 1) exceptions)
  5993. (let ((drawer (org-element-at-point)))
  5994. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5995. (org-flag-drawer t drawer)
  5996. ;; Make sure to skip drawer entirely or we might flag
  5997. ;; it another time when matching its ending line with
  5998. ;; `org-drawer-regexp'.
  5999. (goto-char (org-element-property :end drawer))))))))))
  6000. (defun org-flag-drawer (flag &optional element)
  6001. "When FLAG is non-nil, hide the drawer we are at.
  6002. Otherwise make it visible. When optional argument ELEMENT is
  6003. a parsed drawer, as returned by `org-element-at-point', hide or
  6004. show that drawer instead."
  6005. (let ((drawer (or element
  6006. (and (save-excursion
  6007. (beginning-of-line)
  6008. (looking-at-p org-drawer-regexp))
  6009. (org-element-at-point)))))
  6010. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6011. (let ((post (org-element-property :post-affiliated drawer)))
  6012. (org-flag-region
  6013. (save-excursion (goto-char post) (line-end-position))
  6014. (save-excursion (goto-char (org-element-property :end drawer))
  6015. (skip-chars-backward " \t\n")
  6016. (line-end-position))
  6017. flag 'org-hide-drawer)
  6018. ;; When the drawer is hidden away, make sure point lies in
  6019. ;; a visible part of the buffer.
  6020. (when (invisible-p (max (1- (point)) (point-min)))
  6021. (goto-char post))))))
  6022. ;;;; Visibility cycling
  6023. (defvar-local org-cycle-global-status nil)
  6024. (put 'org-cycle-global-status 'org-state t)
  6025. (defvar-local org-cycle-subtree-status nil)
  6026. (put 'org-cycle-subtree-status 'org-state t)
  6027. (defun org-show-all (&optional types)
  6028. "Show all contents in the visible part of the buffer.
  6029. By default, the function expands headings, blocks and drawers.
  6030. When optional argument TYPE is a list of symbols among `blocks',
  6031. `drawers' and `headings', to only expand one specific type."
  6032. (dolist (type (or types '(blocks drawers headings)))
  6033. (org-flag-region (point-min) (point-max) nil
  6034. (pcase type
  6035. (`blocks 'org-hide-block)
  6036. (`drawers 'org-hide-drawer)
  6037. (`headings 'outline)
  6038. (_ (error "Invalid type: %S" type))))))
  6039. ;;;###autoload
  6040. (defun org-cycle (&optional arg)
  6041. "TAB-action and visibility cycling for Org mode.
  6042. This is the command invoked in Org mode by the `TAB' key. Its main
  6043. purpose is outline visibility cycling, but it also invokes other actions
  6044. in special contexts.
  6045. When this function is called with a `\\[universal-argument]' prefix, rotate \
  6046. the entire
  6047. buffer through 3 states (global cycling)
  6048. 1. OVERVIEW: Show only top-level headlines.
  6049. 2. CONTENTS: Show all headlines of all levels, but no body text.
  6050. 3. SHOW ALL: Show everything.
  6051. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  6052. switch to the startup visibility,
  6053. determined by the variable `org-startup-folded', and by any VISIBILITY
  6054. properties in the buffer.
  6055. With a `\\[universal-argument] \\[universal-argument] \
  6056. \\[universal-argument]' prefix argument, show the entire buffer, including
  6057. any drawers.
  6058. When inside a table, re-align the table and move to the next field.
  6059. When point is at the beginning of a headline, rotate the subtree started
  6060. by this line through 3 different states (local cycling)
  6061. 1. FOLDED: Only the main headline is shown.
  6062. 2. CHILDREN: The main headline and the direct children are shown.
  6063. From this state, you can move to one of the children
  6064. and zoom in further.
  6065. 3. SUBTREE: Show the entire subtree, including body text.
  6066. If there is no subtree, switch directly from CHILDREN to FOLDED.
  6067. When point is at the beginning of an empty headline and the variable
  6068. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  6069. of the headline by demoting and promoting it to likely levels. This
  6070. speeds up creation document structure by pressing `TAB' once or several
  6071. times right after creating a new headline.
  6072. When there is a numeric prefix, go up to a heading with level ARG, do
  6073. a `show-subtree' and return to the previous cursor position. If ARG
  6074. is negative, go up that many levels.
  6075. When point is not at the beginning of a headline, execute the global
  6076. binding for `TAB', which is re-indenting the line. See the option
  6077. `org-cycle-emulate-tab' for details.
  6078. As a special case, if point is at the beginning of the buffer and there is
  6079. no headline in line 1, this function will act as if called with prefix arg
  6080. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  6081. prefix arg, but only
  6082. if the variable `org-cycle-global-at-bob' is t."
  6083. (interactive "P")
  6084. (org-load-modules-maybe)
  6085. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  6086. (and org-cycle-level-after-item/entry-creation
  6087. (or (org-cycle-level)
  6088. (org-cycle-item-indentation))))
  6089. (let* ((limit-level
  6090. (or org-cycle-max-level
  6091. (and (boundp 'org-inlinetask-min-level)
  6092. org-inlinetask-min-level
  6093. (1- org-inlinetask-min-level))))
  6094. (nstars (and limit-level
  6095. (if org-odd-levels-only
  6096. (and limit-level (1- (* limit-level 2)))
  6097. limit-level)))
  6098. (org-outline-regexp
  6099. (if (not (derived-mode-p 'org-mode))
  6100. outline-regexp
  6101. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  6102. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  6103. (not (looking-at org-outline-regexp))))
  6104. (org-cycle-hook
  6105. (if bob-special
  6106. (delq 'org-optimize-window-after-visibility-change
  6107. (copy-sequence org-cycle-hook))
  6108. org-cycle-hook))
  6109. (pos (point)))
  6110. (cond
  6111. ((equal arg '(16))
  6112. (setq last-command 'dummy)
  6113. (org-set-startup-visibility)
  6114. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  6115. ((equal arg '(64))
  6116. (org-show-all)
  6117. (org-unlogged-message "Entire buffer visible, including drawers"))
  6118. ((equal arg '(4)) (org-cycle-internal-global))
  6119. ;; Try hiding block at point.
  6120. ((org-hide-block-toggle-maybe))
  6121. ;; Try cdlatex TAB completion
  6122. ((org-try-cdlatex-tab))
  6123. ;; Table: enter it or move to the next field.
  6124. ((org-at-table-p 'any)
  6125. (if (org-at-table.el-p)
  6126. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6127. Use `\\[org-edit-special]' to edit table.el tables"))
  6128. (if arg (org-table-edit-field t)
  6129. (org-table-justify-field-maybe)
  6130. (call-interactively 'org-table-next-field))))
  6131. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  6132. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6133. (bob-special (org-cycle-internal-global))
  6134. ;; Drawers: delegate to `org-flag-drawer'.
  6135. ((save-excursion
  6136. (beginning-of-line 1)
  6137. (looking-at org-drawer-regexp))
  6138. (org-flag-drawer ; toggle block visibility
  6139. (not (get-char-property (match-end 0) 'invisible))))
  6140. ;; Show-subtree, ARG levels up from here.
  6141. ((integerp arg)
  6142. (save-excursion
  6143. (org-back-to-heading)
  6144. (outline-up-heading (if (< arg 0) (- arg)
  6145. (- (funcall outline-level) arg)))
  6146. (org-show-subtree)))
  6147. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6148. ((and (featurep 'org-inlinetask)
  6149. (org-inlinetask-at-task-p)
  6150. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6151. (org-inlinetask-toggle-visibility))
  6152. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6153. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6154. (save-excursion (move-beginning-of-line 1)
  6155. (looking-at org-outline-regexp)))
  6156. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6157. (org-cycle-internal-local))
  6158. ;; From there: TAB emulation and template completion.
  6159. (buffer-read-only (org-back-to-heading))
  6160. ((run-hook-with-args-until-success
  6161. 'org-tab-after-check-for-cycling-hook))
  6162. ((run-hook-with-args-until-success
  6163. 'org-tab-before-tab-emulation-hook))
  6164. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6165. (or (not (bolp))
  6166. (not (looking-at org-outline-regexp))))
  6167. (call-interactively (global-key-binding "\t")))
  6168. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6169. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6170. (or (and (eq org-cycle-emulate-tab 'white)
  6171. (= (match-end 0) (point-at-eol)))
  6172. (and (eq org-cycle-emulate-tab 'whitestart)
  6173. (>= (match-end 0) pos))))
  6174. t
  6175. (eq org-cycle-emulate-tab t))
  6176. (call-interactively (global-key-binding "\t")))
  6177. (t (save-excursion
  6178. (org-back-to-heading)
  6179. (org-cycle)))))))
  6180. (defun org-cycle-internal-global ()
  6181. "Do the global cycling action."
  6182. ;; Hack to avoid display of messages for .org attachments in Gnus
  6183. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6184. (cond
  6185. ((and (eq last-command this-command)
  6186. (eq org-cycle-global-status 'overview))
  6187. ;; We just created the overview - now do table of contents
  6188. ;; This can be slow in very large buffers, so indicate action
  6189. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6190. (unless ga (org-unlogged-message "CONTENTS..."))
  6191. (org-content)
  6192. (unless ga (org-unlogged-message "CONTENTS...done"))
  6193. (setq org-cycle-global-status 'contents)
  6194. (run-hook-with-args 'org-cycle-hook 'contents))
  6195. ((and (eq last-command this-command)
  6196. (eq org-cycle-global-status 'contents))
  6197. ;; We just showed the table of contents - now show everything
  6198. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6199. (org-show-all '(headings blocks))
  6200. (unless ga (org-unlogged-message "SHOW ALL"))
  6201. (setq org-cycle-global-status 'all)
  6202. (run-hook-with-args 'org-cycle-hook 'all))
  6203. (t
  6204. ;; Default action: go to overview
  6205. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6206. (org-overview)
  6207. (unless ga (org-unlogged-message "OVERVIEW"))
  6208. (setq org-cycle-global-status 'overview)
  6209. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6210. (defvar org-called-with-limited-levels nil
  6211. "Non-nil when `org-with-limited-levels' is currently active.")
  6212. (defun org-cycle-internal-local ()
  6213. "Do the local cycling action."
  6214. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6215. ;; First, determine end of headline (EOH), end of subtree or item
  6216. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6217. (save-excursion
  6218. (if (org-at-item-p)
  6219. (progn
  6220. (beginning-of-line)
  6221. (setq struct (org-list-struct))
  6222. (setq eoh (point-at-eol))
  6223. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6224. (setq has-children (org-list-has-child-p (point) struct)))
  6225. (org-back-to-heading)
  6226. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6227. (setq eos (save-excursion (org-end-of-subtree t t)
  6228. (when (bolp) (backward-char)) (point)))
  6229. (setq has-children
  6230. (or (save-excursion
  6231. (let ((level (funcall outline-level)))
  6232. (outline-next-heading)
  6233. (and (org-at-heading-p t)
  6234. (> (funcall outline-level) level))))
  6235. (save-excursion
  6236. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6237. ;; Determine end invisible part of buffer (EOL)
  6238. (beginning-of-line 2)
  6239. (while (and (not (eobp)) ;This is like `next-line'.
  6240. (get-char-property (1- (point)) 'invisible))
  6241. (goto-char (next-single-char-property-change (point) 'invisible))
  6242. (and (eolp) (beginning-of-line 2)))
  6243. (setq eol (point)))
  6244. ;; Find out what to do next and set `this-command'
  6245. (cond
  6246. ((= eos eoh)
  6247. ;; Nothing is hidden behind this heading
  6248. (unless (org-before-first-heading-p)
  6249. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6250. (org-unlogged-message "EMPTY ENTRY")
  6251. (setq org-cycle-subtree-status nil)
  6252. (save-excursion
  6253. (goto-char eos)
  6254. (outline-next-heading)
  6255. (when (org-invisible-p) (org-flag-heading nil))))
  6256. ((and (or (>= eol eos)
  6257. (not (string-match "\\S-" (buffer-substring eol eos))))
  6258. (or has-children
  6259. (not (setq children-skipped
  6260. org-cycle-skip-children-state-if-no-children))))
  6261. ;; Entire subtree is hidden in one line: children view
  6262. (unless (org-before-first-heading-p)
  6263. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6264. (if (org-at-item-p)
  6265. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6266. (org-show-entry)
  6267. (org-with-limited-levels (org-show-children))
  6268. (org-show-set-visibility 'canonical)
  6269. ;; Fold every list in subtree to top-level items.
  6270. (when (eq org-cycle-include-plain-lists 'integrate)
  6271. (save-excursion
  6272. (org-back-to-heading)
  6273. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6274. (beginning-of-line 1)
  6275. (let* ((struct (org-list-struct))
  6276. (prevs (org-list-prevs-alist struct))
  6277. (end (org-list-get-bottom-point struct)))
  6278. (dolist (e (org-list-get-all-items (point) struct prevs))
  6279. (org-list-set-item-visibility e struct 'folded))
  6280. (goto-char (if (< end eos) end eos)))))))
  6281. (org-unlogged-message "CHILDREN")
  6282. (save-excursion
  6283. (goto-char eos)
  6284. (outline-next-heading)
  6285. (when (org-invisible-p) (org-flag-heading nil)))
  6286. (setq org-cycle-subtree-status 'children)
  6287. (unless (org-before-first-heading-p)
  6288. (run-hook-with-args 'org-cycle-hook 'children)))
  6289. ((or children-skipped
  6290. (and (eq last-command this-command)
  6291. (eq org-cycle-subtree-status 'children)))
  6292. ;; We just showed the children, or no children are there,
  6293. ;; now show everything.
  6294. (unless (org-before-first-heading-p)
  6295. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6296. (org-flag-region eoh eos nil 'outline)
  6297. (org-unlogged-message
  6298. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6299. (setq org-cycle-subtree-status 'subtree)
  6300. (unless (org-before-first-heading-p)
  6301. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6302. (t
  6303. ;; Default action: hide the subtree.
  6304. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6305. (org-flag-region eoh eos t 'outline)
  6306. (org-unlogged-message "FOLDED")
  6307. (setq org-cycle-subtree-status 'folded)
  6308. (unless (org-before-first-heading-p)
  6309. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6310. ;;;###autoload
  6311. (defun org-global-cycle (&optional arg)
  6312. "Cycle the global visibility. For details see `org-cycle'.
  6313. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6314. With a numeric prefix, show all headlines up to that level."
  6315. (interactive "P")
  6316. (let ((org-cycle-include-plain-lists
  6317. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6318. (cond
  6319. ((integerp arg)
  6320. (org-show-all '(headings blocks))
  6321. (outline-hide-sublevels arg)
  6322. (setq org-cycle-global-status 'contents))
  6323. ((equal arg '(4))
  6324. (org-set-startup-visibility)
  6325. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6326. (t
  6327. (org-cycle '(4))))))
  6328. (defun org-set-startup-visibility ()
  6329. "Set the visibility required by startup options and properties."
  6330. (cond
  6331. ((eq org-startup-folded t)
  6332. (org-overview))
  6333. ((eq org-startup-folded 'content)
  6334. (org-content))
  6335. ((or (eq org-startup-folded 'showeverything)
  6336. (eq org-startup-folded nil))
  6337. (org-show-all)))
  6338. (unless (eq org-startup-folded 'showeverything)
  6339. (when org-hide-block-startup (org-hide-block-all))
  6340. (org-set-visibility-according-to-property)
  6341. (org-cycle-hide-archived-subtrees 'all)
  6342. (org-cycle-hide-drawers 'all)
  6343. (org-cycle-show-empty-lines t)))
  6344. (defun org-set-visibility-according-to-property ()
  6345. "Switch subtree visibilities according to :VISIBILITY: property."
  6346. (interactive)
  6347. (org-with-wide-buffer
  6348. (goto-char (point-min))
  6349. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6350. (if (not (org-at-property-p)) (outline-next-heading)
  6351. (let ((state (match-string 3)))
  6352. (save-excursion
  6353. (org-back-to-heading t)
  6354. (outline-hide-subtree)
  6355. (org-reveal)
  6356. (cond
  6357. ((equal state "folded")
  6358. (outline-hide-subtree))
  6359. ((equal state "children")
  6360. (org-show-hidden-entry)
  6361. (org-show-children))
  6362. ((equal state "content")
  6363. (save-excursion
  6364. (save-restriction
  6365. (org-narrow-to-subtree)
  6366. (org-content))))
  6367. ((member state '("all" "showall"))
  6368. (outline-show-subtree)))))))))
  6369. (defun org-overview ()
  6370. "Switch to overview mode, showing only top-level headlines.
  6371. This shows all headlines with a level equal or greater than the level
  6372. of the first headline in the buffer. This is important, because if the
  6373. first headline is not level one, then (hide-sublevels 1) gives confusing
  6374. results."
  6375. (interactive)
  6376. (save-excursion
  6377. (let ((level
  6378. (save-excursion
  6379. (goto-char (point-min))
  6380. (when (re-search-forward org-outline-regexp-bol nil t)
  6381. (goto-char (match-beginning 0))
  6382. (funcall outline-level)))))
  6383. (and level (outline-hide-sublevels level)))))
  6384. (defun org-content (&optional arg)
  6385. "Show all headlines in the buffer, like a table of contents.
  6386. With numerical argument N, show content up to level N."
  6387. (interactive "P")
  6388. (org-overview)
  6389. (save-excursion
  6390. ;; Visit all headings and show their offspring
  6391. (and (integerp arg) (org-overview))
  6392. (goto-char (point-max))
  6393. (catch 'exit
  6394. (while (and (progn (condition-case nil
  6395. (outline-previous-visible-heading 1)
  6396. (error (goto-char (point-min))))
  6397. t)
  6398. (looking-at org-outline-regexp))
  6399. (if (integerp arg)
  6400. (org-show-children (1- arg))
  6401. (outline-show-branches))
  6402. (when (bobp) (throw 'exit nil))))))
  6403. (defun org-optimize-window-after-visibility-change (state)
  6404. "Adjust the window after a change in outline visibility.
  6405. This function is the default value of the hook `org-cycle-hook'."
  6406. (when (get-buffer-window (current-buffer))
  6407. (cond
  6408. ((eq state 'content) nil)
  6409. ((eq state 'all) nil)
  6410. ((eq state 'folded) nil)
  6411. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6412. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6413. (defun org-clean-visibility-after-subtree-move ()
  6414. "Fix visibility issues after moving a subtree."
  6415. ;; First, find a reasonable region to look at:
  6416. ;; Start two siblings above, end three below
  6417. (let* ((beg (save-excursion
  6418. (and (org-get-last-sibling)
  6419. (org-get-last-sibling))
  6420. (point)))
  6421. (end (save-excursion
  6422. (and (org-get-next-sibling)
  6423. (org-get-next-sibling)
  6424. (org-get-next-sibling))
  6425. (if (org-at-heading-p)
  6426. (point-at-eol)
  6427. (point))))
  6428. (level (looking-at "\\*+"))
  6429. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6430. (save-excursion
  6431. (save-restriction
  6432. (narrow-to-region beg end)
  6433. (when re
  6434. ;; Properly fold already folded siblings
  6435. (goto-char (point-min))
  6436. (while (re-search-forward re nil t)
  6437. (when (and (not (org-invisible-p))
  6438. (org-invisible-p (line-end-position)))
  6439. (outline-hide-entry))))
  6440. (org-cycle-hide-drawers 'all)
  6441. (org-cycle-show-empty-lines 'overview)))))
  6442. (defun org-cycle-show-empty-lines (state)
  6443. "Show empty lines above all visible headlines.
  6444. The region to be covered depends on STATE when called through
  6445. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6446. entire buffer covered. Note that an empty line is only shown if there
  6447. are at least `org-cycle-separator-lines' empty lines before the headline."
  6448. (when (/= org-cycle-separator-lines 0)
  6449. (save-excursion
  6450. (let* ((n (abs org-cycle-separator-lines))
  6451. (re (cond
  6452. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6453. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6454. (t (let ((ns (number-to-string (- n 2))))
  6455. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6456. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6457. beg end)
  6458. (cond
  6459. ((memq state '(overview contents t))
  6460. (setq beg (point-min) end (point-max)))
  6461. ((memq state '(children folded))
  6462. (setq beg (point)
  6463. end (progn (org-end-of-subtree t t)
  6464. (line-beginning-position 2)))))
  6465. (when beg
  6466. (goto-char beg)
  6467. (while (re-search-forward re end t)
  6468. (unless (get-char-property (match-end 1) 'invisible)
  6469. (let ((e (match-end 1))
  6470. (b (if (>= org-cycle-separator-lines 0)
  6471. (match-beginning 1)
  6472. (save-excursion
  6473. (goto-char (match-beginning 0))
  6474. (skip-chars-backward " \t\n")
  6475. (line-end-position)))))
  6476. (org-flag-region b e nil 'outline))))))))
  6477. ;; Never hide empty lines at the end of the file.
  6478. (save-excursion
  6479. (goto-char (point-max))
  6480. (outline-previous-heading)
  6481. (outline-end-of-heading)
  6482. (when (and (looking-at "[ \t\n]+")
  6483. (= (match-end 0) (point-max)))
  6484. (org-flag-region (point) (match-end 0) nil 'outline))))
  6485. ;;;; Reveal point location
  6486. (defun org-show-context (&optional key)
  6487. "Make sure point and context are visible.
  6488. Optional argument KEY, when non-nil, is a symbol. See
  6489. `org-show-context-detail' for allowed values and how much is to
  6490. be shown."
  6491. (org-show-set-visibility
  6492. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  6493. ((cdr (assq key org-show-context-detail)))
  6494. (t (cdr (assq 'default org-show-context-detail))))))
  6495. (defun org-show-set-visibility (detail)
  6496. "Set visibility around point according to DETAIL.
  6497. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  6498. `tree', `canonical' or t. See `org-show-context-detail' for more
  6499. information."
  6500. ;; Show current heading and possibly its entry, following headline
  6501. ;; or all children.
  6502. (if (and (org-at-heading-p) (not (eq detail 'local)))
  6503. (org-flag-heading nil)
  6504. (org-show-entry)
  6505. ;; If point is hidden within a drawer or a block, make sure to
  6506. ;; expose it.
  6507. (dolist (o (overlays-at (point)))
  6508. (when (memq (overlay-get o 'invisible)
  6509. '(org-hide-block org-hide-drawer outline))
  6510. (delete-overlay o)))
  6511. (unless (org-before-first-heading-p)
  6512. (org-with-limited-levels
  6513. (cl-case detail
  6514. ((tree canonical t) (org-show-children))
  6515. ((nil minimal ancestors))
  6516. (t (save-excursion
  6517. (outline-next-heading)
  6518. (org-flag-heading nil)))))))
  6519. ;; Show all siblings.
  6520. (when (eq detail 'lineage) (org-show-siblings))
  6521. ;; Show ancestors, possibly with their children.
  6522. (when (memq detail '(ancestors lineage tree canonical t))
  6523. (save-excursion
  6524. (while (org-up-heading-safe)
  6525. (org-flag-heading nil)
  6526. (when (memq detail '(canonical t)) (org-show-entry))
  6527. (when (memq detail '(tree canonical t)) (org-show-children))))))
  6528. (defvar org-reveal-start-hook nil
  6529. "Hook run before revealing a location.")
  6530. (defun org-reveal (&optional siblings)
  6531. "Show current entry, hierarchy above it, and the following headline.
  6532. This can be used to show a consistent set of context around
  6533. locations exposed with `org-show-context'.
  6534. With optional argument SIBLINGS, on each level of the hierarchy all
  6535. siblings are shown. This repairs the tree structure to what it would
  6536. look like when opened with hierarchical calls to `org-cycle'.
  6537. With a \\[universal-argument] \\[universal-argument] prefix, \
  6538. go to the parent and show the entire tree."
  6539. (interactive "P")
  6540. (run-hooks 'org-reveal-start-hook)
  6541. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6542. ((equal siblings '(16))
  6543. (save-excursion
  6544. (when (org-up-heading-safe)
  6545. (org-show-subtree)
  6546. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6547. (t (org-show-set-visibility 'lineage))))
  6548. ;;; Indirect buffer display of subtrees
  6549. (defvar org-indirect-dedicated-frame nil
  6550. "This is the frame being used for indirect tree display.")
  6551. (defvar org-last-indirect-buffer nil)
  6552. (defun org-tree-to-indirect-buffer (&optional arg)
  6553. "Create indirect buffer and narrow it to current subtree.
  6554. With a numerical prefix ARG, go up to this level and then take that tree.
  6555. If ARG is negative, go up that many levels.
  6556. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6557. indirect buffer previously made with this command, to avoid proliferation of
  6558. indirect buffers. However, when you call the command with a \
  6559. `\\[universal-argument]' prefix, or
  6560. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6561. so that you can work with several indirect buffers at the same time. If
  6562. `org-indirect-buffer-display' is `dedicated-frame', the \
  6563. `\\[universal-argument]' prefix also
  6564. requests that a new frame be made for the new buffer, so that the dedicated
  6565. frame is not changed."
  6566. (interactive "P")
  6567. (let ((cbuf (current-buffer))
  6568. (cwin (selected-window))
  6569. (pos (point))
  6570. beg end level heading ibuf)
  6571. (save-excursion
  6572. (org-back-to-heading t)
  6573. (when (numberp arg)
  6574. (setq level (org-outline-level))
  6575. (when (< arg 0) (setq arg (+ level arg)))
  6576. (while (> (setq level (org-outline-level)) arg)
  6577. (org-up-heading-safe)))
  6578. (setq beg (point)
  6579. heading (org-get-heading 'no-tags))
  6580. (org-end-of-subtree t t)
  6581. (when (org-at-heading-p) (backward-char 1))
  6582. (setq end (point)))
  6583. (when (and (buffer-live-p org-last-indirect-buffer)
  6584. (not (eq org-indirect-buffer-display 'new-frame))
  6585. (not arg))
  6586. (kill-buffer org-last-indirect-buffer))
  6587. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6588. org-last-indirect-buffer ibuf)
  6589. (cond
  6590. ((or (eq org-indirect-buffer-display 'new-frame)
  6591. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6592. (select-frame (make-frame))
  6593. (delete-other-windows)
  6594. (pop-to-buffer-same-window ibuf)
  6595. (org-set-frame-title heading))
  6596. ((eq org-indirect-buffer-display 'dedicated-frame)
  6597. (raise-frame
  6598. (select-frame (or (and org-indirect-dedicated-frame
  6599. (frame-live-p org-indirect-dedicated-frame)
  6600. org-indirect-dedicated-frame)
  6601. (setq org-indirect-dedicated-frame (make-frame)))))
  6602. (delete-other-windows)
  6603. (pop-to-buffer-same-window ibuf)
  6604. (org-set-frame-title (concat "Indirect: " heading)))
  6605. ((eq org-indirect-buffer-display 'current-window)
  6606. (pop-to-buffer-same-window ibuf))
  6607. ((eq org-indirect-buffer-display 'other-window)
  6608. (pop-to-buffer ibuf))
  6609. (t (error "Invalid value")))
  6610. (narrow-to-region beg end)
  6611. (org-show-all '(headings blocks))
  6612. (goto-char pos)
  6613. (run-hook-with-args 'org-cycle-hook 'all)
  6614. (and (window-live-p cwin) (select-window cwin))))
  6615. (defun org-get-indirect-buffer (&optional buffer heading)
  6616. (setq buffer (or buffer (current-buffer)))
  6617. (let ((n 1) (base (buffer-name buffer)) bname)
  6618. (while (buffer-live-p
  6619. (get-buffer
  6620. (setq bname
  6621. (concat base "-"
  6622. (if heading (concat heading "-" (number-to-string n))
  6623. (number-to-string n))))))
  6624. (setq n (1+ n)))
  6625. (condition-case nil
  6626. (make-indirect-buffer buffer bname 'clone)
  6627. (error (make-indirect-buffer buffer bname)))))
  6628. (defun org-set-frame-title (title)
  6629. "Set the title of the current frame to the string TITLE."
  6630. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6631. ;;;; Structure editing
  6632. ;;; Inserting headlines
  6633. (defun org--line-empty-p (n)
  6634. "Is the Nth next line empty?
  6635. Counts the current line as N = 1 and the previous line as N = 0;
  6636. see `beginning-of-line'."
  6637. (save-excursion
  6638. (and (not (bobp))
  6639. (or (beginning-of-line n) t)
  6640. (save-match-data
  6641. (looking-at "[ \t]*$")))))
  6642. (defun org-previous-line-empty-p ()
  6643. "Is the previous line a blank line?
  6644. When NEXT is non-nil, check the next line instead."
  6645. (org--line-empty-p 0))
  6646. (defun org-next-line-empty-p ()
  6647. "Is the previous line a blank line?
  6648. When NEXT is non-nil, check the next line instead."
  6649. (org--line-empty-p 2))
  6650. (defun org--blank-before-heading-p (&optional parent)
  6651. "Non-nil when an empty line should precede a new heading here.
  6652. When optional argument PARENT is non-nil, consider parent
  6653. headline instead of current one."
  6654. (pcase (assq 'heading org-blank-before-new-entry)
  6655. (`(heading . auto)
  6656. (save-excursion
  6657. (org-with-limited-levels
  6658. (unless (and (org-before-first-heading-p)
  6659. (not (outline-next-heading)))
  6660. (org-back-to-heading t)
  6661. (when parent (org-up-heading-safe))
  6662. (cond ((not (bobp))
  6663. (org-previous-line-empty-p))
  6664. ((outline-next-heading)
  6665. (org-previous-line-empty-p))
  6666. ;; Ignore trailing spaces on last buffer line.
  6667. ((progn (skip-chars-backward " \t") (bolp))
  6668. (org-previous-line-empty-p))
  6669. (t nil))))))
  6670. (`(heading . ,value) value)
  6671. (_ nil)))
  6672. (defun org-insert-heading (&optional arg invisible-ok top)
  6673. "Insert a new heading or an item with the same depth at point.
  6674. If point is at the beginning of a heading, insert a new heading
  6675. or a new headline above the current one. When at the beginning
  6676. of a regular line of text, turn it into a heading.
  6677. If point is in the middle of a line, split it and create a new
  6678. headline with the text in the current line after point (see
  6679. `org-M-RET-may-split-line' on how to modify this behavior). As
  6680. a special case, on a headline, splitting can only happen on the
  6681. title itself. E.g., this excludes breaking stars or tags.
  6682. With a `\\[universal-argument]' prefix, set \
  6683. `org-insert-heading-respect-content' to
  6684. a non-nil value for the duration of the command. This forces the
  6685. insertion of a heading after the current subtree, independently
  6686. on the location of point.
  6687. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6688. insert the heading at the end of the tree
  6689. above the current heading. For example, if point is within a
  6690. 2nd-level heading, then it will insert a 2nd-level heading at
  6691. the end of the 1st-level parent subtree.
  6692. When INVISIBLE-OK is set, stop at invisible headlines when going
  6693. back. This is important for non-interactive uses of the
  6694. command.
  6695. When optional argument TOP is non-nil, insert a level 1 heading,
  6696. unconditionally."
  6697. (interactive "P")
  6698. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6699. (level (org-current-level))
  6700. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6701. (cond
  6702. ((or org-insert-heading-respect-content
  6703. (member arg '((4) (16)))
  6704. (and (not invisible-ok)
  6705. (invisible-p (max (1- (point)) (point-min)))))
  6706. ;; Position point at the location of insertion.
  6707. (if (not level) ;before first headline
  6708. (org-with-limited-levels (outline-next-heading))
  6709. ;; Make sure we end up on a visible headline if INVISIBLE-OK
  6710. ;; is nil.
  6711. (org-with-limited-levels (org-back-to-heading invisible-ok))
  6712. (cond ((equal arg '(16))
  6713. (org-up-heading-safe)
  6714. (org-end-of-subtree t t))
  6715. (t
  6716. (org-end-of-subtree t t))))
  6717. (unless (bolp) (insert "\n")) ;ensure final newline
  6718. (unless (and blank? (org-previous-line-empty-p))
  6719. (org-N-empty-lines-before-current (if blank? 1 0)))
  6720. (insert stars " \n")
  6721. (forward-char -1))
  6722. ;; At a headline...
  6723. ((org-at-heading-p)
  6724. (cond ((bolp)
  6725. (when blank? (save-excursion (insert "\n")))
  6726. (save-excursion (insert stars " \n"))
  6727. (unless (and blank? (org-previous-line-empty-p))
  6728. (org-N-empty-lines-before-current (if blank? 1 0)))
  6729. (end-of-line))
  6730. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6731. (org-match-line org-complex-heading-regexp)
  6732. (org-pos-in-match-range (point) 4))
  6733. ;; Grab the text that should moved to the new headline.
  6734. ;; Preserve tags.
  6735. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6736. (if (looking-at "[ \t]*$") (replace-match "")
  6737. (org-align-tags))
  6738. (end-of-line)
  6739. (when blank? (insert "\n"))
  6740. (insert "\n" stars " ")
  6741. (when (org-string-nw-p split) (insert split))
  6742. (when (eobp) (save-excursion (insert "\n")))))
  6743. (t
  6744. (end-of-line)
  6745. (when blank? (insert "\n"))
  6746. (insert "\n" stars " ")
  6747. (when (eobp) (save-excursion (insert "\n"))))))
  6748. ;; On regular text, turn line into a headline or split, if
  6749. ;; appropriate.
  6750. ((bolp)
  6751. (insert stars " ")
  6752. (unless (and blank? (org-previous-line-empty-p))
  6753. (org-N-empty-lines-before-current (if blank? 1 0))))
  6754. (t
  6755. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6756. (end-of-line))
  6757. (insert "\n" stars " ")
  6758. (unless (and blank? (org-previous-line-empty-p))
  6759. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6760. (run-hooks 'org-insert-heading-hook))
  6761. (defun org-N-empty-lines-before-current (n)
  6762. "Make the number of empty lines before current exactly N.
  6763. So this will delete or add empty lines."
  6764. (let ((column (current-column)))
  6765. (beginning-of-line)
  6766. (unless (bobp)
  6767. (let ((start (save-excursion
  6768. (skip-chars-backward " \r\t\n")
  6769. (line-end-position))))
  6770. (delete-region start (line-end-position 0))))
  6771. (insert (make-string n ?\n))
  6772. (move-to-column column)))
  6773. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6774. "Return the heading of the current entry, without the stars.
  6775. When NO-TAGS is non-nil, don't include tags.
  6776. When NO-TODO is non-nil, don't include TODO keywords.
  6777. When NO-PRIORITY is non-nil, don't include priority cookie.
  6778. When NO-COMMENT is non-nil, don't include COMMENT string."
  6779. (save-excursion
  6780. (org-back-to-heading t)
  6781. (let ((case-fold-search nil))
  6782. (looking-at org-complex-heading-regexp)
  6783. (let ((todo (and (not no-todo) (match-string 2)))
  6784. (priority (and (not no-priority) (match-string 3)))
  6785. (headline (pcase (match-string 4)
  6786. (`nil "")
  6787. ((and (guard no-comment) h)
  6788. (replace-regexp-in-string
  6789. (eval-when-compile
  6790. (format "\\`%s[ \t]+" org-comment-string))
  6791. "" h))
  6792. (h h)))
  6793. (tags (and (not no-tags) (match-string 5))))
  6794. (mapconcat #'identity
  6795. (delq nil (list todo priority headline tags))
  6796. " ")))))
  6797. (defun org-heading-components ()
  6798. "Return the components of the current heading.
  6799. This is a list with the following elements:
  6800. - the level as an integer
  6801. - the reduced level, different if `org-odd-levels-only' is set.
  6802. - the TODO keyword, or nil
  6803. - the priority character, like ?A, or nil if no priority is given
  6804. - the headline text itself, or the tags string if no headline text
  6805. - the tags string, or nil."
  6806. (save-excursion
  6807. (org-back-to-heading t)
  6808. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6809. (list (length (match-string 1))
  6810. (org-reduced-level (length (match-string 1)))
  6811. (match-string-no-properties 2)
  6812. (and (match-end 3) (aref (match-string 3) 2))
  6813. (match-string-no-properties 4)
  6814. (match-string-no-properties 5)))))
  6815. (defun org-get-entry ()
  6816. "Get the entry text, after heading, entire subtree."
  6817. (save-excursion
  6818. (org-back-to-heading t)
  6819. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6820. (defun org-edit-headline (&optional heading)
  6821. "Edit the current headline.
  6822. Set it to HEADING when provided."
  6823. (interactive)
  6824. (org-with-wide-buffer
  6825. (org-back-to-heading t)
  6826. (let ((case-fold-search nil))
  6827. (when (looking-at org-complex-heading-regexp)
  6828. (let* ((old (match-string-no-properties 4))
  6829. (new (save-match-data
  6830. (org-trim (or heading (read-string "Edit: " old))))))
  6831. (unless (equal old new)
  6832. (if old (replace-match new t t nil 4)
  6833. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6834. (insert " " new))
  6835. (org-align-tags)
  6836. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6837. (defun org-insert-heading-after-current ()
  6838. "Insert a new heading with same level as current, after current subtree."
  6839. (interactive)
  6840. (org-back-to-heading)
  6841. (org-insert-heading)
  6842. (org-move-subtree-down)
  6843. (end-of-line 1))
  6844. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6845. "Insert heading with `org-insert-heading-respect-content' set to t."
  6846. (interactive)
  6847. (org-insert-heading '(4) invisible-ok))
  6848. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6849. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6850. (interactive)
  6851. (org-insert-todo-heading force-state '(4)))
  6852. (defun org-insert-todo-heading (arg &optional force-heading)
  6853. "Insert a new heading with the same level and TODO state as current heading.
  6854. If the heading has no TODO state, or if the state is DONE, use
  6855. the first state (TODO by default). Also with one prefix arg,
  6856. force first state. With two prefix args, force inserting at the
  6857. end of the parent subtree.
  6858. When called at a plain list item, insert a new item with an
  6859. unchecked check box."
  6860. (interactive "P")
  6861. (when (or force-heading (not (org-insert-item 'checkbox)))
  6862. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6863. force-heading))
  6864. (save-excursion
  6865. (org-forward-heading-same-level -1)
  6866. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6867. (let* ((new-mark-x
  6868. (if (or (equal arg '(4))
  6869. (not (match-beginning 2))
  6870. (member (match-string 2) org-done-keywords))
  6871. (car org-todo-keywords-1)
  6872. (match-string 2)))
  6873. (new-mark
  6874. (or
  6875. (run-hook-with-args-until-success
  6876. 'org-todo-get-default-hook new-mark-x nil)
  6877. new-mark-x)))
  6878. (beginning-of-line 1)
  6879. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6880. (if org-treat-insert-todo-heading-as-state-change
  6881. (org-todo new-mark)
  6882. (insert new-mark " "))))
  6883. (when org-provide-todo-statistics
  6884. (org-update-parent-todo-statistics))))
  6885. (defun org-insert-subheading (arg)
  6886. "Insert a new subheading and demote it.
  6887. Works for outline headings and for plain lists alike."
  6888. (interactive "P")
  6889. (org-insert-heading arg)
  6890. (cond
  6891. ((org-at-heading-p) (org-do-demote))
  6892. ((org-at-item-p) (org-indent-item))))
  6893. (defun org-insert-todo-subheading (arg)
  6894. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6895. Works for outline headings and for plain lists alike."
  6896. (interactive "P")
  6897. (org-insert-todo-heading arg)
  6898. (cond
  6899. ((org-at-heading-p) (org-do-demote))
  6900. ((org-at-item-p) (org-indent-item))))
  6901. ;;; Promotion and Demotion
  6902. (defvar org-after-demote-entry-hook nil
  6903. "Hook run after an entry has been demoted.
  6904. The cursor will be at the beginning of the entry.
  6905. When a subtree is being demoted, the hook will be called for each node.")
  6906. (defvar org-after-promote-entry-hook nil
  6907. "Hook run after an entry has been promoted.
  6908. The cursor will be at the beginning of the entry.
  6909. When a subtree is being promoted, the hook will be called for each node.")
  6910. (defun org-promote-subtree ()
  6911. "Promote the entire subtree.
  6912. See also `org-promote'."
  6913. (interactive)
  6914. (save-excursion
  6915. (org-with-limited-levels (org-map-tree 'org-promote)))
  6916. (org-fix-position-after-promote))
  6917. (defun org-demote-subtree ()
  6918. "Demote the entire subtree.
  6919. See `org-demote' and `org-promote'."
  6920. (interactive)
  6921. (save-excursion
  6922. (org-with-limited-levels (org-map-tree 'org-demote)))
  6923. (org-fix-position-after-promote))
  6924. (defun org-do-promote ()
  6925. "Promote the current heading higher up the tree.
  6926. If the region is active in `transient-mark-mode', promote all
  6927. headings in the region."
  6928. (interactive)
  6929. (save-excursion
  6930. (if (org-region-active-p)
  6931. (org-map-region 'org-promote (region-beginning) (region-end))
  6932. (org-promote)))
  6933. (org-fix-position-after-promote))
  6934. (defun org-do-demote ()
  6935. "Demote the current heading lower down the tree.
  6936. If the region is active in `transient-mark-mode', demote all
  6937. headings in the region."
  6938. (interactive)
  6939. (save-excursion
  6940. (if (org-region-active-p)
  6941. (org-map-region 'org-demote (region-beginning) (region-end))
  6942. (org-demote)))
  6943. (org-fix-position-after-promote))
  6944. (defun org-fix-position-after-promote ()
  6945. "Fix cursor position and indentation after demoting/promoting."
  6946. (let ((pos (point)))
  6947. (when (save-excursion
  6948. (beginning-of-line)
  6949. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6950. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6951. (cond ((eobp) (insert " "))
  6952. ((eolp) (insert " "))
  6953. ((equal (char-after) ?\s) (forward-char 1))))))
  6954. (defun org-current-level ()
  6955. "Return the level of the current entry, or nil if before the first headline.
  6956. The level is the number of stars at the beginning of the
  6957. headline. Use `org-reduced-level' to remove the effect of
  6958. `org-odd-levels'. Unlike to `org-outline-level', this function
  6959. ignores inlinetasks."
  6960. (let ((level (org-with-limited-levels (org-outline-level))))
  6961. (and (> level 0) level)))
  6962. (defun org-get-previous-line-level ()
  6963. "Return the outline depth of the last headline before the current line.
  6964. Returns 0 for the first headline in the buffer, and nil if before the
  6965. first headline."
  6966. (and (org-current-level)
  6967. (or (and (/= (line-beginning-position) (point-min))
  6968. (save-excursion (beginning-of-line 0) (org-current-level)))
  6969. 0)))
  6970. (defun org-reduced-level (l)
  6971. "Compute the effective level of a heading.
  6972. This takes into account the setting of `org-odd-levels-only'."
  6973. (cond
  6974. ((zerop l) 0)
  6975. (org-odd-levels-only (1+ (floor (/ l 2))))
  6976. (t l)))
  6977. (defun org-level-increment ()
  6978. "Return the number of stars that will be added or removed at a
  6979. time to headlines when structure editing, based on the value of
  6980. `org-odd-levels-only'."
  6981. (if org-odd-levels-only 2 1))
  6982. (defun org-get-valid-level (level &optional change)
  6983. "Rectify a level change under the influence of `org-odd-levels-only'.
  6984. LEVEL is a current level, CHANGE is by how much the level should
  6985. be modified. Even if CHANGE is nil, LEVEL may be returned
  6986. modified because even level numbers will become the next higher
  6987. odd number. Returns values greater than 0."
  6988. (if org-odd-levels-only
  6989. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6990. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6991. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6992. (max 1 (+ level (or change 0)))))
  6993. (defun org-promote ()
  6994. "Promote the current heading higher up the tree."
  6995. (org-with-wide-buffer
  6996. (org-back-to-heading t)
  6997. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6998. after-change-functions))
  6999. (level (save-match-data (funcall outline-level)))
  7000. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7001. (diff (abs (- level (length up-head) -1))))
  7002. (cond
  7003. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7004. (replace-match "# " nil t))
  7005. ((= level 1)
  7006. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7007. (t (replace-match up-head nil t)))
  7008. (unless (= level 1)
  7009. (when org-auto-align-tags (org-align-tags))
  7010. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7011. (run-hooks 'org-after-promote-entry-hook))))
  7012. (defun org-demote ()
  7013. "Demote the current heading lower down the tree."
  7014. (org-with-wide-buffer
  7015. (org-back-to-heading t)
  7016. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7017. after-change-functions))
  7018. (level (save-match-data (funcall outline-level)))
  7019. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7020. (diff (abs (- level (length down-head) -1))))
  7021. (replace-match down-head nil t)
  7022. (when org-auto-align-tags (org-align-tags))
  7023. (when org-adapt-indentation (org-fixup-indentation diff))
  7024. (run-hooks 'org-after-demote-entry-hook))))
  7025. (defun org-cycle-level ()
  7026. "Cycle the level of an empty headline through possible states.
  7027. This goes first to child, then to parent, level, then up the hierarchy.
  7028. After top level, it switches back to sibling level."
  7029. (interactive)
  7030. (let ((org-adapt-indentation nil))
  7031. (when (org-point-at-end-of-empty-headline)
  7032. (setq this-command 'org-cycle-level) ; Only needed for caching
  7033. (let ((cur-level (org-current-level))
  7034. (prev-level (org-get-previous-line-level)))
  7035. (cond
  7036. ;; If first headline in file, promote to top-level.
  7037. ((= prev-level 0)
  7038. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7039. do (org-do-promote)))
  7040. ;; If same level as prev, demote one.
  7041. ((= prev-level cur-level)
  7042. (org-do-demote))
  7043. ;; If parent is top-level, promote to top level if not already.
  7044. ((= prev-level 1)
  7045. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7046. do (org-do-promote)))
  7047. ;; If top-level, return to prev-level.
  7048. ((= cur-level 1)
  7049. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7050. do (org-do-demote)))
  7051. ;; If less than prev-level, promote one.
  7052. ((< cur-level prev-level)
  7053. (org-do-promote))
  7054. ;; If deeper than prev-level, promote until higher than
  7055. ;; prev-level.
  7056. ((> cur-level prev-level)
  7057. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7058. do (org-do-promote))))
  7059. t))))
  7060. (defun org-map-tree (fun)
  7061. "Call FUN for every heading underneath the current one."
  7062. (org-back-to-heading t)
  7063. (let ((level (funcall outline-level)))
  7064. (save-excursion
  7065. (funcall fun)
  7066. (while (and (progn
  7067. (outline-next-heading)
  7068. (> (funcall outline-level) level))
  7069. (not (eobp)))
  7070. (funcall fun)))))
  7071. (defun org-map-region (fun beg end)
  7072. "Call FUN for every heading between BEG and END."
  7073. (let ((org-ignore-region t))
  7074. (save-excursion
  7075. (setq end (copy-marker end))
  7076. (goto-char beg)
  7077. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7078. (< (point) end))
  7079. (funcall fun))
  7080. (while (and (progn
  7081. (outline-next-heading)
  7082. (< (point) end))
  7083. (not (eobp)))
  7084. (funcall fun)))))
  7085. (defun org-fixup-indentation (diff)
  7086. "Change the indentation in the current entry by DIFF.
  7087. DIFF is an integer. Indentation is done according to the
  7088. following rules:
  7089. - Planning information and property drawers are always indented
  7090. according to the new level of the headline;
  7091. - Footnote definitions and their contents are ignored;
  7092. - Inlinetasks' boundaries are not shifted;
  7093. - Empty lines are ignored;
  7094. - Other lines' indentation are shifted by DIFF columns, unless
  7095. it would introduce a structural change in the document, in
  7096. which case no shifting is done at all.
  7097. Assume point is at a heading or an inlinetask beginning."
  7098. (org-with-wide-buffer
  7099. (narrow-to-region (line-beginning-position)
  7100. (save-excursion
  7101. (if (org-with-limited-levels (org-at-heading-p))
  7102. (org-with-limited-levels (outline-next-heading))
  7103. (org-inlinetask-goto-end))
  7104. (point)))
  7105. (forward-line)
  7106. ;; Indent properly planning info and property drawer.
  7107. (when (looking-at-p org-planning-line-re)
  7108. (org-indent-line)
  7109. (forward-line))
  7110. (when (looking-at org-property-drawer-re)
  7111. (goto-char (match-end 0))
  7112. (forward-line)
  7113. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7114. (catch 'no-shift
  7115. (when (zerop diff) (throw 'no-shift nil))
  7116. ;; If DIFF is negative, first check if a shift is possible at all
  7117. ;; (e.g., it doesn't break structure). This can only happen if
  7118. ;; some contents are not properly indented.
  7119. (let ((case-fold-search t))
  7120. (when (< diff 0)
  7121. (let ((diff (- diff))
  7122. (forbidden-re (concat org-outline-regexp
  7123. "\\|"
  7124. (substring org-footnote-definition-re 1))))
  7125. (save-excursion
  7126. (while (not (eobp))
  7127. (cond
  7128. ((looking-at-p "[ \t]*$") (forward-line))
  7129. ((and (looking-at-p org-footnote-definition-re)
  7130. (let ((e (org-element-at-point)))
  7131. (and (eq (org-element-type e) 'footnote-definition)
  7132. (goto-char (org-element-property :end e))))))
  7133. ((looking-at-p org-outline-regexp) (forward-line))
  7134. ;; Give up if shifting would move before column 0 or
  7135. ;; if it would introduce a headline or a footnote
  7136. ;; definition.
  7137. (t
  7138. (skip-chars-forward " \t")
  7139. (let ((ind (current-column)))
  7140. (when (or (< ind diff)
  7141. (and (= ind diff) (looking-at-p forbidden-re)))
  7142. (throw 'no-shift nil)))
  7143. ;; Ignore contents of example blocks and source
  7144. ;; blocks if their indentation is meant to be
  7145. ;; preserved. Jump to block's closing line.
  7146. (beginning-of-line)
  7147. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7148. (let ((e (org-element-at-point)))
  7149. (and (memq (org-element-type e)
  7150. '(example-block src-block))
  7151. (or org-src-preserve-indentation
  7152. (org-element-property :preserve-indent e))
  7153. (goto-char (org-element-property :end e))
  7154. (progn (skip-chars-backward " \r\t\n")
  7155. (beginning-of-line)
  7156. t))))
  7157. (forward-line))))))))
  7158. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7159. ;; by DIFF. Also skip contents of source or example blocks
  7160. ;; when indentation is meant to be preserved.
  7161. (while (not (eobp))
  7162. (cond
  7163. ((and (looking-at-p org-footnote-definition-re)
  7164. (let ((e (org-element-at-point)))
  7165. (and (eq (org-element-type e) 'footnote-definition)
  7166. (goto-char (org-element-property :end e))))))
  7167. ((looking-at-p org-outline-regexp) (forward-line))
  7168. ((looking-at-p "[ \t]*$") (forward-line))
  7169. (t
  7170. (indent-line-to (+ (org-get-indentation) diff))
  7171. (beginning-of-line)
  7172. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7173. (let ((e (org-element-at-point)))
  7174. (and (memq (org-element-type e)
  7175. '(example-block src-block))
  7176. (or org-src-preserve-indentation
  7177. (org-element-property :preserve-indent e))
  7178. (goto-char (org-element-property :end e))
  7179. (progn (skip-chars-backward " \r\t\n")
  7180. (beginning-of-line)
  7181. t))))
  7182. (forward-line)))))))))
  7183. (defun org-convert-to-odd-levels ()
  7184. "Convert an Org file with all levels allowed to one with odd levels.
  7185. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7186. level 5 etc."
  7187. (interactive)
  7188. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7189. (let ((outline-level 'org-outline-level)
  7190. (org-odd-levels-only nil) n)
  7191. (save-excursion
  7192. (goto-char (point-min))
  7193. (while (re-search-forward "^\\*\\*+ " nil t)
  7194. (setq n (- (length (match-string 0)) 2))
  7195. (while (>= (setq n (1- n)) 0)
  7196. (org-demote))
  7197. (end-of-line 1))))))
  7198. (defun org-convert-to-oddeven-levels ()
  7199. "Convert an Org file with only odd levels to one with odd/even levels.
  7200. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7201. file contains a section with an even level, conversion would
  7202. destroy the structure of the file. An error is signaled in this
  7203. case."
  7204. (interactive)
  7205. (goto-char (point-min))
  7206. ;; First check if there are no even levels
  7207. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7208. (org-show-set-visibility 'canonical)
  7209. (error "Not all levels are odd in this file. Conversion not possible"))
  7210. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7211. (let ((outline-regexp org-outline-regexp)
  7212. (outline-level 'org-outline-level)
  7213. (org-odd-levels-only nil) n)
  7214. (save-excursion
  7215. (goto-char (point-min))
  7216. (while (re-search-forward "^\\*\\*+ " nil t)
  7217. (setq n (/ (1- (length (match-string 0))) 2))
  7218. (while (>= (setq n (1- n)) 0)
  7219. (org-promote))
  7220. (end-of-line 1))))))
  7221. (defun org-tr-level (n)
  7222. "Make N odd if required."
  7223. (if org-odd-levels-only (1+ (/ n 2)) n))
  7224. ;;; Vertical tree motion, cutting and pasting of subtrees
  7225. (defun org-move-subtree-up (&optional arg)
  7226. "Move the current subtree up past ARG headlines of the same level."
  7227. (interactive "p")
  7228. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7229. (defun org-move-subtree-down (&optional arg)
  7230. "Move the current subtree down past ARG headlines of the same level."
  7231. (interactive "p")
  7232. (setq arg (prefix-numeric-value arg))
  7233. (org-preserve-local-variables
  7234. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7235. 'org-get-last-sibling))
  7236. (ins-point (make-marker))
  7237. (cnt (abs arg))
  7238. (col (current-column))
  7239. beg end txt folded)
  7240. ;; Select the tree
  7241. (org-back-to-heading)
  7242. (setq beg (point))
  7243. (save-match-data
  7244. (save-excursion (outline-end-of-heading)
  7245. (setq folded (org-invisible-p)))
  7246. (progn (org-end-of-subtree nil t)
  7247. (unless (eobp) (backward-char))))
  7248. (outline-next-heading)
  7249. (setq end (point))
  7250. (goto-char beg)
  7251. ;; Find insertion point, with error handling
  7252. (while (> cnt 0)
  7253. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  7254. (goto-char beg)
  7255. (user-error "Cannot move past superior level or buffer limit"))
  7256. (setq cnt (1- cnt)))
  7257. (when (> arg 0)
  7258. ;; Moving forward - still need to move over subtree
  7259. (org-end-of-subtree t t)
  7260. (save-excursion
  7261. (org-back-over-empty-lines)
  7262. (or (bolp) (newline))))
  7263. (move-marker ins-point (point))
  7264. (setq txt (buffer-substring beg end))
  7265. (org-save-markers-in-region beg end)
  7266. (delete-region beg end)
  7267. (org-remove-empty-overlays-at beg)
  7268. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  7269. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  7270. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7271. (let ((bbb (point)))
  7272. (insert-before-markers txt)
  7273. (org-reinstall-markers-in-region bbb)
  7274. (move-marker ins-point bbb))
  7275. (or (bolp) (insert "\n"))
  7276. (goto-char ins-point)
  7277. (org-skip-whitespace)
  7278. (move-marker ins-point nil)
  7279. (if folded
  7280. (outline-hide-subtree)
  7281. (org-show-entry)
  7282. (org-show-children))
  7283. (org-clean-visibility-after-subtree-move)
  7284. ;; move back to the initial column we were at
  7285. (move-to-column col))))
  7286. (defvar org-subtree-clip ""
  7287. "Clipboard for cut and paste of subtrees.
  7288. This is actually only a copy of the kill, because we use the normal kill
  7289. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7290. (defvar org-subtree-clip-folded nil
  7291. "Was the last copied subtree folded?
  7292. This is used to fold the tree back after pasting.")
  7293. (defun org-cut-subtree (&optional n)
  7294. "Cut the current subtree into the clipboard.
  7295. With prefix arg N, cut this many sequential subtrees.
  7296. This is a short-hand for marking the subtree and then cutting it."
  7297. (interactive "p")
  7298. (org-copy-subtree n 'cut))
  7299. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7300. "Copy the current subtree into the clipboard.
  7301. With prefix arg N, copy this many sequential subtrees.
  7302. This is a short-hand for marking the subtree and then copying it.
  7303. If CUT is non-nil, actually cut the subtree.
  7304. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7305. of some markers in the region, even if CUT is non-nil. This is
  7306. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7307. (interactive "p")
  7308. (org-preserve-local-variables
  7309. (let (beg end folded (beg0 (point)))
  7310. (if (called-interactively-p 'any)
  7311. (org-back-to-heading nil) ; take what looks like a subtree
  7312. (org-back-to-heading t)) ; take what is really there
  7313. (setq beg (point))
  7314. (skip-chars-forward " \t\r\n")
  7315. (save-match-data
  7316. (if nosubtrees
  7317. (outline-next-heading)
  7318. (save-excursion (outline-end-of-heading)
  7319. (setq folded (org-invisible-p)))
  7320. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7321. (org-end-of-subtree t t)))
  7322. ;; Include the end of an inlinetask
  7323. (when (and (featurep 'org-inlinetask)
  7324. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7325. "END[ \t]*$")))
  7326. (end-of-line))
  7327. (setq end (point))
  7328. (goto-char beg0)
  7329. (when (> end beg)
  7330. (setq org-subtree-clip-folded folded)
  7331. (when (or cut force-store-markers)
  7332. (org-save-markers-in-region beg end))
  7333. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7334. (setq org-subtree-clip (current-kill 0))
  7335. (message "%s: Subtree(s) with %d characters"
  7336. (if cut "Cut" "Copied")
  7337. (length org-subtree-clip))))))
  7338. (defun org-paste-subtree (&optional level tree for-yank remove)
  7339. "Paste the clipboard as a subtree, with modification of headline level.
  7340. The entire subtree is promoted or demoted in order to match a new headline
  7341. level.
  7342. If the cursor is at the beginning of a headline, the same level as
  7343. that headline is used to paste the tree.
  7344. If not, the new level is derived from the *visible* headings
  7345. before and after the insertion point, and taken to be the inferior headline
  7346. level of the two. So if the previous visible heading is level 3 and the
  7347. next is level 4 (or vice versa), level 4 will be used for insertion.
  7348. This makes sure that the subtree remains an independent subtree and does
  7349. not swallow low level entries.
  7350. You can also force a different level, either by using a numeric prefix
  7351. argument, or by inserting the heading marker by hand. For example, if the
  7352. cursor is after \"*****\", then the tree will be shifted to level 5.
  7353. If optional TREE is given, use this text instead of the kill ring.
  7354. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7355. move back over whitespace before inserting, and move point to the end of
  7356. the inserted text when done.
  7357. When REMOVE is non-nil, remove the subtree from the clipboard."
  7358. (interactive "P")
  7359. (setq tree (or tree (and kill-ring (current-kill 0))))
  7360. (unless (org-kill-is-subtree-p tree)
  7361. (user-error
  7362. (substitute-command-keys
  7363. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  7364. (org-with-limited-levels
  7365. (let* ((visp (not (org-invisible-p)))
  7366. (txt tree)
  7367. (old-level (if (string-match org-outline-regexp-bol txt)
  7368. (- (match-end 0) (match-beginning 0) 1)
  7369. -1))
  7370. (force-level
  7371. (cond
  7372. (level (prefix-numeric-value level))
  7373. ;; When point is right after the stars in an otherwise
  7374. ;; empty headline, use stars as the forced level.
  7375. ((and (looking-at-p "[ \t]*$")
  7376. (string-match-p "^\\*+ *"
  7377. (buffer-substring (line-beginning-position)
  7378. (point))))
  7379. (org-outline-level))
  7380. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  7381. (previous-level
  7382. (save-excursion
  7383. (org-previous-visible-heading 1)
  7384. (if (org-at-heading-p) (org-outline-level) 1)))
  7385. (next-level
  7386. (save-excursion
  7387. (if (org-at-heading-p) (org-outline-level)
  7388. (org-next-visible-heading 1)
  7389. (if (org-at-heading-p) (org-outline-level) 1))))
  7390. (new-level (or force-level (max previous-level next-level)))
  7391. (shift (if (or (= old-level -1)
  7392. (= new-level -1)
  7393. (= old-level new-level))
  7394. 0
  7395. (- new-level old-level)))
  7396. (delta (if (> shift 0) -1 1))
  7397. (func (if (> shift 0) #'org-demote #'org-promote))
  7398. (org-odd-levels-only nil)
  7399. beg end newend)
  7400. ;; Remove the forced level indicator.
  7401. (when (and force-level (not level))
  7402. (delete-region (line-beginning-position) (point)))
  7403. ;; Paste before the next visible heading or at end of buffer,
  7404. ;; unless point is at the beginning of a headline.
  7405. (unless (and (bolp) (org-at-heading-p))
  7406. (org-next-visible-heading 1)
  7407. (unless (bolp) (insert "\n")))
  7408. (setq beg (point))
  7409. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7410. (insert-before-markers txt)
  7411. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7412. (setq newend (point))
  7413. (org-reinstall-markers-in-region beg)
  7414. (setq end (point))
  7415. (goto-char beg)
  7416. (skip-chars-forward " \t\n\r")
  7417. (setq beg (point))
  7418. (when (and (org-invisible-p) visp)
  7419. (save-excursion (outline-show-heading)))
  7420. ;; Shift if necessary.
  7421. (unless (= shift 0)
  7422. (save-restriction
  7423. (narrow-to-region beg end)
  7424. (while (not (= shift 0))
  7425. (org-map-region func (point-min) (point-max))
  7426. (setq shift (+ delta shift)))
  7427. (goto-char (point-min))
  7428. (setq newend (point-max))))
  7429. (when (or for-yank (called-interactively-p 'interactive))
  7430. (message "Clipboard pasted as level %d subtree" new-level))
  7431. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7432. kill-ring
  7433. (equal org-subtree-clip (current-kill 0))
  7434. org-subtree-clip-folded)
  7435. ;; The tree was folded before it was killed/copied
  7436. (outline-hide-subtree))
  7437. (when for-yank (goto-char newend))
  7438. (when remove (pop kill-ring)))))
  7439. (defun org-kill-is-subtree-p (&optional txt)
  7440. "Check if the current kill is an outline subtree, or a set of trees.
  7441. Returns nil if kill does not start with a headline, or if the first
  7442. headline level is not the largest headline level in the tree.
  7443. So this will actually accept several entries of equal levels as well,
  7444. which is OK for `org-paste-subtree'.
  7445. If optional TXT is given, check this string instead of the current kill."
  7446. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7447. (re (org-get-limited-outline-regexp))
  7448. (^re (concat "^" re))
  7449. (start-level (and kill
  7450. (string-match
  7451. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7452. kill)
  7453. (- (match-end 2) (match-beginning 2) 1)))
  7454. (start (1+ (or (match-beginning 2) -1))))
  7455. (if (not start-level)
  7456. (progn
  7457. nil) ;; does not even start with a heading
  7458. (catch 'exit
  7459. (while (setq start (string-match ^re kill (1+ start)))
  7460. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7461. (throw 'exit nil)))
  7462. t))))
  7463. (defvar org-markers-to-move nil
  7464. "Markers that should be moved with a cut-and-paste operation.
  7465. Those markers are stored together with their positions relative to
  7466. the start of the region.")
  7467. (defun org-save-markers-in-region (beg end)
  7468. "Check markers in region.
  7469. If these markers are between BEG and END, record their position relative
  7470. to BEG, so that after moving the block of text, we can put the markers back
  7471. into place.
  7472. This function gets called just before an entry or tree gets cut from the
  7473. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7474. called immediately, to move the markers with the entries."
  7475. (setq org-markers-to-move nil)
  7476. (when (featurep 'org-clock)
  7477. (org-clock-save-markers-for-cut-and-paste beg end))
  7478. (when (featurep 'org-agenda)
  7479. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7480. (defun org-check-and-save-marker (marker beg end)
  7481. "Check if MARKER is between BEG and END.
  7482. If yes, remember the marker and the distance to BEG."
  7483. (when (and (marker-buffer marker)
  7484. (equal (marker-buffer marker) (current-buffer))
  7485. (>= marker beg) (< marker end))
  7486. (push (cons marker (- marker beg)) org-markers-to-move)))
  7487. (defun org-reinstall-markers-in-region (beg)
  7488. "Move all remembered markers to their position relative to BEG."
  7489. (dolist (x org-markers-to-move)
  7490. (move-marker (car x) (+ beg (cdr x))))
  7491. (setq org-markers-to-move nil))
  7492. (defun org-narrow-to-subtree ()
  7493. "Narrow buffer to the current subtree."
  7494. (interactive)
  7495. (save-excursion
  7496. (save-match-data
  7497. (org-with-limited-levels
  7498. (narrow-to-region
  7499. (progn (org-back-to-heading t) (point))
  7500. (progn (org-end-of-subtree t t)
  7501. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7502. (point)))))))
  7503. (defun org-narrow-to-block ()
  7504. "Narrow buffer to the current block."
  7505. (interactive)
  7506. (let* ((case-fold-search t)
  7507. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7508. "^[ \t]*#\\+end_.*")))
  7509. (if blockp
  7510. (narrow-to-region (car blockp) (cdr blockp))
  7511. (user-error "Not in a block"))))
  7512. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7513. "Clone the task (subtree) at point N times.
  7514. The clones will be inserted as siblings.
  7515. In interactive use, the user will be prompted for the number of
  7516. clones to be produced. If the entry has a timestamp, the user
  7517. will also be prompted for a time shift, which may be a repeater
  7518. as used in time stamps, for example `+3d'. To disable this,
  7519. you can call the function with a universal prefix argument.
  7520. When a valid repeater is given and the entry contains any time
  7521. stamps, the clones will become a sequence in time, with time
  7522. stamps in the subtree shifted for each clone produced. If SHIFT
  7523. is nil or the empty string, time stamps will be left alone. The
  7524. ID property of the original subtree is removed.
  7525. In each clone, all the CLOCK entries will be removed. This
  7526. prevents Org from considering that the clocked times overlap.
  7527. If the original subtree did contain time stamps with a repeater,
  7528. the following will happen:
  7529. - the repeater will be removed in each clone
  7530. - an additional clone will be produced, with the current, unshifted
  7531. date(s) in the entry.
  7532. - the original entry will be placed *after* all the clones, with
  7533. repeater intact.
  7534. - the start days in the repeater in the original entry will be shifted
  7535. to past the last clone.
  7536. In this way you can spell out a number of instances of a repeating task,
  7537. and still retain the repeater to cover future instances of the task.
  7538. As described above, N+1 clones are produced when the original
  7539. subtree has a repeater. Setting N to 0, then, can be used to
  7540. remove the repeater from a subtree and create a shifted clone
  7541. with the original repeater."
  7542. (interactive "nNumber of clones to produce: ")
  7543. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7544. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7545. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7546. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7547. (shift
  7548. (or shift
  7549. (if (and (not (equal current-prefix-arg '(4)))
  7550. (save-excursion
  7551. (goto-char beg)
  7552. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7553. (read-from-minibuffer
  7554. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7555. ""))) ;No time shift
  7556. (doshift
  7557. (and (org-string-nw-p shift)
  7558. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7559. shift)
  7560. (user-error "Invalid shift specification %s" shift)))))
  7561. (goto-char end-of-tree)
  7562. (unless (bolp) (insert "\n"))
  7563. (let* ((end (point))
  7564. (template (buffer-substring beg end))
  7565. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7566. (shift-what (pcase (and doshift (match-string 2 shift))
  7567. (`nil nil)
  7568. ("d" 'day)
  7569. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7570. ("m" 'month)
  7571. ("y" 'year)
  7572. (_ (error "Unsupported time unit"))))
  7573. (nmin 1)
  7574. (nmax n)
  7575. (n-no-remove -1)
  7576. (idprop (org-entry-get nil "ID")))
  7577. (when (and doshift
  7578. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7579. template))
  7580. (delete-region beg end)
  7581. (setq end beg)
  7582. (setq nmin 0)
  7583. (setq nmax (1+ nmax))
  7584. (setq n-no-remove nmax))
  7585. (goto-char end)
  7586. (cl-loop for n from nmin to nmax do
  7587. (insert
  7588. ;; Prepare clone.
  7589. (with-temp-buffer
  7590. (insert template)
  7591. (org-mode)
  7592. (goto-char (point-min))
  7593. (org-show-subtree)
  7594. (and idprop (if org-clone-delete-id
  7595. (org-entry-delete nil "ID")
  7596. (org-id-get-create t)))
  7597. (unless (= n 0)
  7598. (while (re-search-forward org-clock-line-re nil t)
  7599. (delete-region (line-beginning-position)
  7600. (line-beginning-position 2)))
  7601. (goto-char (point-min))
  7602. (while (re-search-forward org-drawer-regexp nil t)
  7603. (org-remove-empty-drawer-at (point))))
  7604. (goto-char (point-min))
  7605. (when doshift
  7606. (while (re-search-forward org-ts-regexp-both nil t)
  7607. (org-timestamp-change (* n shift-n) shift-what))
  7608. (unless (= n n-no-remove)
  7609. (goto-char (point-min))
  7610. (while (re-search-forward org-ts-regexp nil t)
  7611. (save-excursion
  7612. (goto-char (match-beginning 0))
  7613. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7614. (delete-region (match-beginning 1) (match-end 1)))))))
  7615. (buffer-string)))))
  7616. (goto-char beg)))
  7617. ;;; Outline Sorting
  7618. (defun org-sort (&optional with-case)
  7619. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7620. Optional argument WITH-CASE means sort case-sensitively."
  7621. (interactive "P")
  7622. (org-call-with-arg
  7623. (cond ((org-at-table-p) #'org-table-sort-lines)
  7624. ((org-at-item-p) #'org-sort-list)
  7625. (t #'org-sort-entries))
  7626. with-case))
  7627. (defun org-sort-remove-invisible (s)
  7628. "Remove invisible part of links and emphasis markers from string S."
  7629. (remove-text-properties 0 (length s) org-rm-props s)
  7630. (replace-regexp-in-string
  7631. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7632. (replace-regexp-in-string
  7633. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7634. (org-link-display-format s)
  7635. t t) t t))
  7636. (defvar org-priority-regexp) ; defined later in the file
  7637. (defvar org-after-sorting-entries-or-items-hook nil
  7638. "Hook that is run after a bunch of entries or items have been sorted.
  7639. When children are sorted, the cursor is in the parent line when this
  7640. hook gets called. When a region or a plain list is sorted, the cursor
  7641. will be in the first entry of the sorted region/list.")
  7642. (defun org-sort-entries
  7643. (&optional with-case sorting-type getkey-func compare-func property
  7644. interactive?)
  7645. "Sort entries on a certain level of an outline tree.
  7646. If there is an active region, the entries in the region are sorted.
  7647. Else, if the cursor is before the first entry, sort the top-level items.
  7648. Else, the children of the entry at point are sorted.
  7649. Sorting can be alphabetically, numerically, by date/time as given by
  7650. a time stamp, by a property, by priority order, or by a custom function.
  7651. The command prompts for the sorting type unless it has been given to the
  7652. function through the SORTING-TYPE argument, which needs to be a character,
  7653. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7654. the precise meaning of each character:
  7655. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7656. c By creation time, which is assumed to be the first inactive time stamp
  7657. at the beginning of a line.
  7658. d By deadline date/time.
  7659. k By clocking time.
  7660. n Numerically, by converting the beginning of the entry/item to a number.
  7661. o By order of TODO keywords.
  7662. p By priority according to the cookie.
  7663. r By the value of a property.
  7664. s By scheduled date/time.
  7665. t By date/time, either the first active time stamp in the entry, or, if
  7666. none exist, by the first inactive one.
  7667. Capital letters will reverse the sort order.
  7668. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7669. called with point at the beginning of the record. It must return a
  7670. value that is compatible with COMPARE-FUNC, the function used to
  7671. compare entries.
  7672. Comparing entries ignores case by default. However, with an optional argument
  7673. WITH-CASE, the sorting considers case as well.
  7674. Sorting is done against the visible part of the headlines, it ignores hidden
  7675. links.
  7676. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7677. A non-nil value for INTERACTIVE? is used to signal that this
  7678. function is being called interactively."
  7679. (interactive (list current-prefix-arg nil nil nil nil t))
  7680. (let ((case-func (if with-case 'identity 'downcase))
  7681. start beg end stars re re2
  7682. txt what tmp)
  7683. ;; Find beginning and end of region to sort
  7684. (cond
  7685. ((org-region-active-p)
  7686. ;; we will sort the region
  7687. (setq end (region-end)
  7688. what "region")
  7689. (goto-char (region-beginning))
  7690. (unless (org-at-heading-p) (outline-next-heading))
  7691. (setq start (point)))
  7692. ((or (org-at-heading-p)
  7693. (ignore-errors (progn (org-back-to-heading) t)))
  7694. ;; we will sort the children of the current headline
  7695. (org-back-to-heading)
  7696. (setq start (point)
  7697. end (progn (org-end-of-subtree t t)
  7698. (or (bolp) (insert "\n"))
  7699. (when (>= (org-back-over-empty-lines) 1)
  7700. (forward-line 1))
  7701. (point))
  7702. what "children")
  7703. (goto-char start)
  7704. (outline-show-subtree)
  7705. (outline-next-heading))
  7706. (t
  7707. ;; we will sort the top-level entries in this file
  7708. (goto-char (point-min))
  7709. (or (org-at-heading-p) (outline-next-heading))
  7710. (setq start (point))
  7711. (goto-char (point-max))
  7712. (beginning-of-line 1)
  7713. (when (looking-at ".*?\\S-")
  7714. ;; File ends in a non-white line
  7715. (end-of-line 1)
  7716. (insert "\n"))
  7717. (setq end (point-max))
  7718. (setq what "top-level")
  7719. (goto-char start)
  7720. (org-show-all '(headings blocks))))
  7721. (setq beg (point))
  7722. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7723. (looking-at "\\(\\*+\\)")
  7724. (setq stars (match-string 1)
  7725. re (concat "^" (regexp-quote stars) " +")
  7726. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7727. txt (buffer-substring beg end))
  7728. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7729. (when (and (not (equal stars "*")) (string-match re2 txt))
  7730. (user-error "Region to sort contains a level above the first entry"))
  7731. (unless sorting-type
  7732. (message
  7733. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7734. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7735. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7736. what)
  7737. (setq sorting-type (read-char-exclusive)))
  7738. (unless getkey-func
  7739. (and (= (downcase sorting-type) ?f)
  7740. (setq getkey-func
  7741. (or (and interactive?
  7742. (org-read-function
  7743. "Function for extracting keys: "))
  7744. (error "Missing key extractor")))))
  7745. (and (= (downcase sorting-type) ?r)
  7746. (not property)
  7747. (setq property
  7748. (completing-read "Property: "
  7749. (mapcar #'list (org-buffer-property-keys t))
  7750. nil t)))
  7751. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7752. (message "Sorting entries...")
  7753. (save-restriction
  7754. (narrow-to-region start end)
  7755. (let ((restore-clock?
  7756. ;; The clock marker is lost when using `sort-subr'; mark
  7757. ;; the clock with temporary `:org-clock-marker-backup'
  7758. ;; text property.
  7759. (when (and (eq (org-clock-is-active) (current-buffer))
  7760. (<= start (marker-position org-clock-marker))
  7761. (>= end (marker-position org-clock-marker)))
  7762. (org-with-silent-modifications
  7763. (put-text-property (1- org-clock-marker) org-clock-marker
  7764. :org-clock-marker-backup t))
  7765. t))
  7766. (dcst (downcase sorting-type))
  7767. (case-fold-search nil)
  7768. (now (current-time)))
  7769. (org-preserve-local-variables
  7770. (sort-subr
  7771. (/= dcst sorting-type)
  7772. ;; This function moves to the beginning character of the
  7773. ;; "record" to be sorted.
  7774. (lambda nil
  7775. (if (re-search-forward re nil t)
  7776. (goto-char (match-beginning 0))
  7777. (goto-char (point-max))))
  7778. ;; This function moves to the last character of the "record" being
  7779. ;; sorted.
  7780. (lambda nil
  7781. (save-match-data
  7782. (condition-case nil
  7783. (outline-forward-same-level 1)
  7784. (error
  7785. (goto-char (point-max))))))
  7786. ;; This function returns the value that gets sorted against.
  7787. (lambda ()
  7788. (cond
  7789. ((= dcst ?n)
  7790. (string-to-number
  7791. (org-sort-remove-invisible (org-get-heading t t t t))))
  7792. ((= dcst ?a)
  7793. (funcall case-func
  7794. (org-sort-remove-invisible (org-get-heading t t t t))))
  7795. ((= dcst ?k)
  7796. (or (get-text-property (point) :org-clock-minutes) 0))
  7797. ((= dcst ?t)
  7798. (let ((end (save-excursion (outline-next-heading) (point))))
  7799. (if (or (re-search-forward org-ts-regexp end t)
  7800. (re-search-forward org-ts-regexp-both end t))
  7801. (org-time-string-to-seconds (match-string 0))
  7802. (float-time now))))
  7803. ((= dcst ?c)
  7804. (let ((end (save-excursion (outline-next-heading) (point))))
  7805. (if (re-search-forward
  7806. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7807. end t)
  7808. (org-time-string-to-seconds (match-string 0))
  7809. (float-time now))))
  7810. ((= dcst ?s)
  7811. (let ((end (save-excursion (outline-next-heading) (point))))
  7812. (if (re-search-forward org-scheduled-time-regexp end t)
  7813. (org-time-string-to-seconds (match-string 1))
  7814. (float-time now))))
  7815. ((= dcst ?d)
  7816. (let ((end (save-excursion (outline-next-heading) (point))))
  7817. (if (re-search-forward org-deadline-time-regexp end t)
  7818. (org-time-string-to-seconds (match-string 1))
  7819. (float-time now))))
  7820. ((= dcst ?p)
  7821. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7822. (string-to-char (match-string 2))
  7823. org-default-priority))
  7824. ((= dcst ?r)
  7825. (or (org-entry-get nil property) ""))
  7826. ((= dcst ?o)
  7827. (when (looking-at org-complex-heading-regexp)
  7828. (let* ((m (match-string 2))
  7829. (s (if (member m org-done-keywords) '- '+)))
  7830. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7831. ((= dcst ?f)
  7832. (if getkey-func
  7833. (progn
  7834. (setq tmp (funcall getkey-func))
  7835. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7836. tmp)
  7837. (error "Invalid key function `%s'" getkey-func)))
  7838. (t (error "Invalid sorting type `%c'" sorting-type))))
  7839. nil
  7840. (cond
  7841. ((= dcst ?a) 'org-string-collate-lessp)
  7842. ((= dcst ?f)
  7843. (or compare-func
  7844. (and interactive?
  7845. (org-read-function
  7846. (concat "Function for comparing keys "
  7847. "(empty for default `sort-subr' predicate): ")
  7848. 'allow-empty))))
  7849. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7850. (when restore-clock?
  7851. (move-marker org-clock-marker
  7852. (1+ (next-single-property-change
  7853. start :org-clock-marker-backup)))
  7854. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7855. '(:org-clock-marker-backup t)))))
  7856. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7857. (message "Sorting entries...done")))
  7858. (defun org-contextualize-keys (alist contexts)
  7859. "Return valid elements in ALIST depending on CONTEXTS.
  7860. `org-agenda-custom-commands' or `org-capture-templates' are the
  7861. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7862. or `org-capture-templates-contexts' are the associated contexts
  7863. definitions."
  7864. (let ((contexts
  7865. ;; normalize contexts
  7866. (mapcar
  7867. (lambda(c) (cond ((listp (cadr c))
  7868. (list (car c) (car c) (nth 1 c)))
  7869. ((string= "" (cadr c))
  7870. (list (car c) (car c) (nth 2 c)))
  7871. (t c)))
  7872. contexts))
  7873. (a alist) r s)
  7874. ;; loop over all commands or templates
  7875. (dolist (c a)
  7876. (let (vrules repl)
  7877. (cond
  7878. ((not (assoc (car c) contexts))
  7879. (push c r))
  7880. ((and (assoc (car c) contexts)
  7881. (setq vrules (org-contextualize-validate-key
  7882. (car c) contexts)))
  7883. (mapc (lambda (vr)
  7884. (unless (equal (car vr) (cadr vr))
  7885. (setq repl vr)))
  7886. vrules)
  7887. (if (not repl) (push c r)
  7888. (push (cadr repl) s)
  7889. (push
  7890. (cons (car c)
  7891. (cdr (or (assoc (cadr repl) alist)
  7892. (error "Undefined key `%s' as contextual replacement for `%s'"
  7893. (cadr repl) (car c)))))
  7894. r))))))
  7895. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7896. (delq
  7897. nil
  7898. (delete-dups
  7899. (mapcar (lambda (x)
  7900. (let ((tpl (car x)))
  7901. (unless (delq
  7902. nil
  7903. (mapcar (lambda (y)
  7904. (equal y tpl))
  7905. s))
  7906. x)))
  7907. (reverse r))))))
  7908. (defun org-contextualize-validate-key (key contexts)
  7909. "Check CONTEXTS for agenda or capture KEY."
  7910. (let (res)
  7911. (dolist (r contexts)
  7912. (dolist (rr (car (last r)))
  7913. (when
  7914. (and (equal key (car r))
  7915. (if (functionp rr) (funcall rr)
  7916. (or (and (eq (car rr) 'in-file)
  7917. (buffer-file-name)
  7918. (string-match (cdr rr) (buffer-file-name)))
  7919. (and (eq (car rr) 'in-mode)
  7920. (string-match (cdr rr) (symbol-name major-mode)))
  7921. (and (eq (car rr) 'in-buffer)
  7922. (string-match (cdr rr) (buffer-name)))
  7923. (when (and (eq (car rr) 'not-in-file)
  7924. (buffer-file-name))
  7925. (not (string-match (cdr rr) (buffer-file-name))))
  7926. (when (eq (car rr) 'not-in-mode)
  7927. (not (string-match (cdr rr) (symbol-name major-mode))))
  7928. (when (eq (car rr) 'not-in-buffer)
  7929. (not (string-match (cdr rr) (buffer-name)))))))
  7930. (push r res))))
  7931. (delete-dups (delq nil res))))
  7932. ;; Defined to provide a value for defcustom, since there is no
  7933. ;; string-collate-greaterp in Emacs.
  7934. (defun org-string-collate-greaterp (s1 s2)
  7935. "Return non-nil if S1 is greater than S2 in collation order."
  7936. (not (org-string-collate-lessp s1 s2)))
  7937. ;;;###autoload
  7938. (defun org-run-like-in-org-mode (cmd)
  7939. "Run a command, pretending that the current buffer is in Org mode.
  7940. This will temporarily bind local variables that are typically bound in
  7941. Org mode to the values they have in Org mode, and then interactively
  7942. call CMD."
  7943. (org-load-modules-maybe)
  7944. (let (binds)
  7945. (dolist (var (org-get-local-variables))
  7946. (when (or (not (boundp (car var)))
  7947. (eq (symbol-value (car var))
  7948. (default-value (car var))))
  7949. (push (list (car var) `(quote ,(cadr var))) binds)))
  7950. (eval `(let ,binds
  7951. (call-interactively (quote ,cmd))))))
  7952. (defun org-get-category (&optional pos force-refresh)
  7953. "Get the category applying to position POS."
  7954. (save-match-data
  7955. (when force-refresh (org-refresh-category-properties))
  7956. (let ((pos (or pos (point))))
  7957. (or (get-text-property pos 'org-category)
  7958. (progn (org-refresh-category-properties)
  7959. (get-text-property pos 'org-category))))))
  7960. ;;; Refresh properties
  7961. (defun org-refresh-properties (dprop tprop)
  7962. "Refresh buffer text properties.
  7963. DPROP is the drawer property and TPROP is either the
  7964. corresponding text property to set, or an alist with each element
  7965. being a text property (as a symbol) and a function to apply to
  7966. the value of the drawer property."
  7967. (let* ((case-fold-search t)
  7968. (inhibit-read-only t)
  7969. (inherit? (org-property-inherit-p dprop))
  7970. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7971. (global (and inherit? (org--property-global-value dprop nil))))
  7972. (org-with-silent-modifications
  7973. (org-with-point-at 1
  7974. ;; Set global values (e.g., values defined through
  7975. ;; "#+PROPERTY:" keywords) to the whole buffer.
  7976. (when global (put-text-property (point-min) (point-max) tprop global))
  7977. ;; Set local values.
  7978. (while (re-search-forward property-re nil t)
  7979. (when (org-at-property-p)
  7980. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7981. (outline-next-heading))))))
  7982. (defun org-refresh-property (tprop p &optional inherit)
  7983. "Refresh the buffer text property TPROP from the drawer property P.
  7984. The refresh happens only for the current headline, or the whole
  7985. sub-tree if optional argument INHERIT is non-nil."
  7986. (unless (org-before-first-heading-p)
  7987. (save-excursion
  7988. (org-back-to-heading t)
  7989. (let ((start (point))
  7990. (end (save-excursion
  7991. (if inherit (org-end-of-subtree t t)
  7992. (or (outline-next-heading) (point-max))))))
  7993. (if (symbolp tprop)
  7994. ;; TPROP is a text property symbol.
  7995. (put-text-property start end tprop p)
  7996. ;; TPROP is an alist with (property . function) elements.
  7997. (pcase-dolist (`(,prop . ,f) tprop)
  7998. (put-text-property start end prop (funcall f p))))))))
  7999. (defun org-refresh-category-properties ()
  8000. "Refresh category text properties in the buffer."
  8001. (let ((case-fold-search t)
  8002. (inhibit-read-only t)
  8003. (default-category
  8004. (cond ((null org-category)
  8005. (if buffer-file-name
  8006. (file-name-sans-extension
  8007. (file-name-nondirectory buffer-file-name))
  8008. "???"))
  8009. ((symbolp org-category) (symbol-name org-category))
  8010. (t org-category))))
  8011. (org-with-silent-modifications
  8012. (org-with-wide-buffer
  8013. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8014. ;; This is the default category for the buffer. If none is
  8015. ;; found, fall-back to `org-category' or buffer file name.
  8016. (put-text-property
  8017. (point-min) (point-max)
  8018. 'org-category
  8019. (catch 'buffer-category
  8020. (goto-char (point-max))
  8021. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8022. (let ((element (org-element-at-point)))
  8023. (when (eq (org-element-type element) 'keyword)
  8024. (throw 'buffer-category
  8025. (org-element-property :value element)))))
  8026. default-category))
  8027. ;; Set sub-tree specific categories.
  8028. (goto-char (point-min))
  8029. (let ((regexp (org-re-property "CATEGORY")))
  8030. (while (re-search-forward regexp nil t)
  8031. (let ((value (match-string-no-properties 3)))
  8032. (when (org-at-property-p)
  8033. (put-text-property
  8034. (save-excursion (org-back-to-heading t) (point))
  8035. (save-excursion (org-end-of-subtree t t) (point))
  8036. 'org-category
  8037. value)))))))))
  8038. (defun org-refresh-stats-properties ()
  8039. "Refresh stats text properties in the buffer."
  8040. (org-with-silent-modifications
  8041. (org-with-point-at 1
  8042. (let ((regexp (concat org-outline-regexp-bol
  8043. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8044. (while (re-search-forward regexp nil t)
  8045. (let* ((numerator (string-to-number (match-string 1)))
  8046. (denominator (and (match-end 2)
  8047. (string-to-number (match-string 2))))
  8048. (stats (cond ((not denominator) numerator) ;percent
  8049. ((= denominator 0) 0)
  8050. (t (/ (* numerator 100) denominator)))))
  8051. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8052. 'org-stats stats)))))))
  8053. (defun org-refresh-effort-properties ()
  8054. "Refresh effort properties"
  8055. (org-refresh-properties
  8056. org-effort-property
  8057. '((effort . identity)
  8058. (effort-minutes . org-duration-to-minutes))))
  8059. ;;;; Link Stuff
  8060. ;;; Link abbreviations
  8061. (defun org-link-expand-abbrev (link)
  8062. "Apply replacements as defined in `org-link-abbrev-alist'."
  8063. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8064. (let* ((key (match-string 1 link))
  8065. (as (or (assoc key org-link-abbrev-alist-local)
  8066. (assoc key org-link-abbrev-alist)))
  8067. (tag (and (match-end 2) (match-string 3 link)))
  8068. rpl)
  8069. (if (not as)
  8070. link
  8071. (setq rpl (cdr as))
  8072. (cond
  8073. ((symbolp rpl) (funcall rpl tag))
  8074. ((string-match "%(\\([^)]+\\))" rpl)
  8075. (replace-match
  8076. (save-match-data
  8077. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8078. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8079. ((string-match "%h" rpl)
  8080. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8081. (t (concat rpl tag)))))
  8082. link))
  8083. ;;; Storing and inserting links
  8084. (defvar org-insert-link-history nil
  8085. "Minibuffer history for links inserted with `org-insert-link'.")
  8086. (defvar org-stored-links nil
  8087. "Contains the links stored with `org-store-link'.")
  8088. (defvar org-store-link-plist nil
  8089. "Plist with info about the most recently link created with `org-store-link'.")
  8090. (defun org-store-link-functions ()
  8091. "Return a list of functions that are called to create and store a link.
  8092. The functions defined in the :store property of
  8093. `org-link-parameters'.
  8094. Each function will be called in turn until one returns a non-nil
  8095. value. Each function should check if it is responsible for
  8096. creating this link (for example by looking at the major mode).
  8097. If not, it must exit and return nil. If yes, it should return
  8098. a non-nil value after calling `org-store-link-props' with a list
  8099. of properties and values. Special properties are:
  8100. :type The link prefix, like \"http\". This must be given.
  8101. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8102. This is obligatory as well.
  8103. :description Optional default description for the second pair
  8104. of brackets in an Org mode link. The user can still change
  8105. this when inserting this link into an Org mode buffer.
  8106. In addition to these, any additional properties can be specified
  8107. and then used in capture templates."
  8108. (cl-loop for link in org-link-parameters
  8109. with store-func
  8110. do (setq store-func (org-link-get-parameter (car link) :store))
  8111. if store-func
  8112. collect store-func))
  8113. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8114. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8115. ;;;###autoload
  8116. (defun org-store-link (arg &optional interactive?)
  8117. "Store an org-link to the current location.
  8118. \\<org-mode-map>
  8119. This link is added to `org-stored-links' and can later be inserted
  8120. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8121. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8122. A single
  8123. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8124. `org-gnus-prefer-web-links' for links to Usenet articles.
  8125. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8126. skipping storing functions that are not
  8127. part of Org core.
  8128. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8129. prefix ARG forces storing a link for each line in the
  8130. active region.
  8131. Assume the function is called interactively if INTERACTIVE? is
  8132. non-nil."
  8133. (interactive "P\np")
  8134. (org-load-modules-maybe)
  8135. (if (and (equal arg '(64)) (org-region-active-p))
  8136. (save-excursion
  8137. (let ((end (region-end)))
  8138. (goto-char (region-beginning))
  8139. (set-mark (point))
  8140. (while (< (point-at-eol) end)
  8141. (move-end-of-line 1) (activate-mark)
  8142. (let (current-prefix-arg)
  8143. (call-interactively 'org-store-link))
  8144. (move-beginning-of-line 2)
  8145. (set-mark (point)))))
  8146. (setq org-store-link-plist nil)
  8147. (let (link cpltxt desc description search txt custom-id agenda-link)
  8148. (cond
  8149. ;; Store a link using an external link type, if any function is
  8150. ;; available. If more than one can generate a link from current
  8151. ;; location, ask which one to use.
  8152. ((and (not (equal arg '(16)))
  8153. (let ((results-alist nil))
  8154. (dolist (f (org-store-link-functions))
  8155. (when (funcall f)
  8156. ;; XXX: return value is not link's plist, so we
  8157. ;; store the new value before it is modified. It
  8158. ;; would be cleaner to ask store link functions to
  8159. ;; return the plist instead.
  8160. (push (cons f (copy-sequence org-store-link-plist))
  8161. results-alist)))
  8162. (pcase results-alist
  8163. (`nil nil)
  8164. (`((,_ . ,_)) t) ;single choice: nothing to do
  8165. (`((,name . ,_) . ,_)
  8166. ;; Reinstate link plist associated to the chosen
  8167. ;; function.
  8168. (apply #'org-store-link-props
  8169. (cdr (assoc-string
  8170. (completing-read
  8171. "Which function for creating the link? "
  8172. (mapcar #'car results-alist)
  8173. nil t (symbol-name name))
  8174. results-alist)))
  8175. t))))
  8176. (setq link (plist-get org-store-link-plist :link))
  8177. (setq desc (or (plist-get org-store-link-plist :description)
  8178. link)))
  8179. ;; Store a link from a source code buffer.
  8180. ((org-src-edit-buffer-p)
  8181. (let ((coderef-format (org-src-coderef-format)))
  8182. (cond ((org-match-line (org-src-coderef-regexp coderef-format))
  8183. (setq link (format "(%s)" (match-string-no-properties 3))))
  8184. (interactive?
  8185. (let ((label (read-string "Code line label: ")))
  8186. (end-of-line)
  8187. (setq link (format coderef-format label))
  8188. (let ((gc (- 79 (length link))))
  8189. (if (< (current-column) gc)
  8190. (org-move-to-column gc t)
  8191. (insert " ")))
  8192. (insert link)
  8193. (setq link (concat "(" label ")"))
  8194. (setq desc nil)))
  8195. (t (setq link nil)))))
  8196. ;; We are in the agenda, link to referenced location
  8197. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8198. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8199. (get-text-property (point) 'org-marker))))
  8200. (when m
  8201. (org-with-point-at m
  8202. (setq agenda-link (org-store-link nil interactive?))))))
  8203. ((eq major-mode 'calendar-mode)
  8204. (let ((cd (calendar-cursor-to-date)))
  8205. (setq link
  8206. (format-time-string
  8207. (car org-time-stamp-formats)
  8208. (apply 'encode-time
  8209. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8210. nil nil nil))))
  8211. (org-store-link-props :type "calendar" :date cd)))
  8212. ((eq major-mode 'help-mode)
  8213. (setq link (concat "help:" (save-excursion
  8214. (goto-char (point-min))
  8215. (looking-at "^[^ ]+")
  8216. (match-string 0))))
  8217. (org-store-link-props :type "help"))
  8218. ((eq major-mode 'w3-mode)
  8219. (setq cpltxt (if (and (buffer-name)
  8220. (not (string-match "Untitled" (buffer-name))))
  8221. (buffer-name)
  8222. (url-view-url t))
  8223. link (url-view-url t))
  8224. (org-store-link-props :type "w3" :url (url-view-url t)))
  8225. ((eq major-mode 'image-mode)
  8226. (setq cpltxt (concat "file:"
  8227. (abbreviate-file-name buffer-file-name))
  8228. link cpltxt)
  8229. (org-store-link-props :type "image" :file buffer-file-name))
  8230. ;; In dired, store a link to the file of the current line
  8231. ((derived-mode-p 'dired-mode)
  8232. (let ((file (dired-get-filename nil t)))
  8233. (setq file (if file
  8234. (abbreviate-file-name
  8235. (expand-file-name (dired-get-filename nil t)))
  8236. ;; otherwise, no file so use current directory.
  8237. default-directory))
  8238. (setq cpltxt (concat "file:" file)
  8239. link cpltxt)))
  8240. ((setq search (run-hook-with-args-until-success
  8241. 'org-create-file-search-functions))
  8242. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8243. "::" search))
  8244. (setq cpltxt (or description link)))
  8245. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8246. (org-with-limited-levels
  8247. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8248. (cond
  8249. ;; Store a link using the target at point
  8250. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8251. (setq cpltxt
  8252. (concat "file:"
  8253. (abbreviate-file-name
  8254. (buffer-file-name (buffer-base-buffer)))
  8255. "::" (match-string 1))
  8256. link cpltxt))
  8257. ((and (featurep 'org-id)
  8258. (or (eq org-id-link-to-org-use-id t)
  8259. (and interactive?
  8260. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8261. (and (eq org-id-link-to-org-use-id
  8262. 'create-if-interactive-and-no-custom-id)
  8263. (not custom-id))))
  8264. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8265. ;; Store a link using the ID at point
  8266. (setq link (condition-case nil
  8267. (prog1 (org-id-store-link)
  8268. (setq desc (or (plist-get org-store-link-plist
  8269. :description)
  8270. "")))
  8271. (error
  8272. ;; Probably before first headline, link only to file
  8273. (concat "file:"
  8274. (abbreviate-file-name
  8275. (buffer-file-name (buffer-base-buffer))))))))
  8276. (t
  8277. ;; Just link to current headline
  8278. (setq cpltxt (concat "file:"
  8279. (abbreviate-file-name
  8280. (buffer-file-name (buffer-base-buffer)))))
  8281. ;; Add a context search string
  8282. (when (org-xor org-context-in-file-links
  8283. (equal arg '(4)))
  8284. (let* ((element (org-element-at-point))
  8285. (name (org-element-property :name element)))
  8286. (setq txt (cond
  8287. ((org-at-heading-p) nil)
  8288. (name)
  8289. ((org-region-active-p)
  8290. (buffer-substring (region-beginning) (region-end)))))
  8291. (when (or (null txt) (string-match "\\S-" txt))
  8292. (setq cpltxt
  8293. (concat cpltxt "::"
  8294. (condition-case nil
  8295. (org-make-org-heading-search-string txt)
  8296. (error "")))
  8297. desc (or name
  8298. (nth 4 (ignore-errors (org-heading-components)))
  8299. "NONE")))))
  8300. (when (string-match "::\\'" cpltxt)
  8301. (setq cpltxt (substring cpltxt 0 -2)))
  8302. (setq link cpltxt)))))
  8303. ((buffer-file-name (buffer-base-buffer))
  8304. ;; Just link to this file here.
  8305. (setq cpltxt (concat "file:"
  8306. (abbreviate-file-name
  8307. (buffer-file-name (buffer-base-buffer)))))
  8308. ;; Add a context string.
  8309. (when (org-xor org-context-in-file-links
  8310. (equal arg '(4)))
  8311. (setq txt (if (org-region-active-p)
  8312. (buffer-substring (region-beginning) (region-end))
  8313. (buffer-substring (point-at-bol) (point-at-eol))))
  8314. ;; Only use search option if there is some text.
  8315. (when (string-match "\\S-" txt)
  8316. (setq cpltxt
  8317. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8318. desc "NONE")))
  8319. (setq link cpltxt))
  8320. (interactive?
  8321. (user-error "No method for storing a link from this buffer"))
  8322. (t (setq link nil)))
  8323. ;; We're done setting link and desc, clean up
  8324. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8325. (setq link (or link cpltxt)
  8326. desc (or desc cpltxt))
  8327. (cond ((not desc))
  8328. ((equal desc "NONE") (setq desc nil))
  8329. (t (setq desc
  8330. (replace-regexp-in-string
  8331. org-bracket-link-analytic-regexp
  8332. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8333. desc))))
  8334. ;; Return the link
  8335. (if (not (and interactive? link))
  8336. (or agenda-link (and link (org-make-link-string link desc)))
  8337. (push (list link desc) org-stored-links)
  8338. (message "Stored: %s" (or desc link))
  8339. (when custom-id
  8340. (setq link (concat "file:" (abbreviate-file-name
  8341. (buffer-file-name)) "::#" custom-id))
  8342. (push (list link desc) org-stored-links))
  8343. (car org-stored-links)))))
  8344. (defun org-store-link-props (&rest plist)
  8345. "Store link properties.
  8346. The properties are pre-processed by extracting names, addresses
  8347. and dates."
  8348. (let ((x (plist-get plist :from)))
  8349. (when x
  8350. (let ((adr (mail-extract-address-components x)))
  8351. (setq plist (plist-put plist :fromname (car adr)))
  8352. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8353. (let ((x (plist-get plist :to)))
  8354. (when x
  8355. (let ((adr (mail-extract-address-components x)))
  8356. (setq plist (plist-put plist :toname (car adr)))
  8357. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8358. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8359. (when x
  8360. (setq plist (plist-put plist :date-timestamp
  8361. (format-time-string
  8362. (org-time-stamp-format t) x)))
  8363. (setq plist (plist-put plist :date-timestamp-inactive
  8364. (format-time-string
  8365. (org-time-stamp-format t t) x)))))
  8366. (let ((from (plist-get plist :from))
  8367. (to (plist-get plist :to)))
  8368. (when (and from to org-from-is-user-regexp)
  8369. (setq plist
  8370. (plist-put plist :fromto
  8371. (if (string-match org-from-is-user-regexp from)
  8372. (concat "to %t")
  8373. (concat "from %f"))))))
  8374. (setq org-store-link-plist plist))
  8375. (defun org-add-link-props (&rest plist)
  8376. "Add these properties to the link property list."
  8377. (let (key value)
  8378. (while plist
  8379. (setq key (pop plist) value (pop plist))
  8380. (setq org-store-link-plist
  8381. (plist-put org-store-link-plist key value)))))
  8382. (defun org-email-link-description (&optional fmt)
  8383. "Return the description part of an email link.
  8384. This takes information from `org-store-link-plist' and formats it
  8385. according to FMT (default from `org-email-link-description-format')."
  8386. (setq fmt (or fmt org-email-link-description-format))
  8387. (let* ((p org-store-link-plist)
  8388. (to (plist-get p :toaddress))
  8389. (from (plist-get p :fromaddress))
  8390. (table
  8391. (list
  8392. (cons "%c" (plist-get p :fromto))
  8393. (cons "%F" (plist-get p :from))
  8394. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8395. (cons "%T" (plist-get p :to))
  8396. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8397. (cons "%s" (plist-get p :subject))
  8398. (cons "%d" (plist-get p :date))
  8399. (cons "%m" (plist-get p :message-id)))))
  8400. (when (string-match "%c" fmt)
  8401. ;; Check if the user wrote this message
  8402. (if (and org-from-is-user-regexp from to
  8403. (save-match-data (string-match org-from-is-user-regexp from)))
  8404. (setq fmt (replace-match "to %t" t t fmt))
  8405. (setq fmt (replace-match "from %f" t t fmt))))
  8406. (org-replace-escapes fmt table)))
  8407. (defun org-make-org-heading-search-string (&optional string)
  8408. "Make search string for the current headline or STRING."
  8409. (let ((s (or string
  8410. (and (derived-mode-p 'org-mode)
  8411. (save-excursion
  8412. (org-back-to-heading t)
  8413. (org-element-property :raw-value (org-element-at-point))))))
  8414. (lines org-context-in-file-links))
  8415. (unless string (setq s (concat "*" s))) ;Add * for headlines
  8416. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8417. (when (and string (integerp lines) (> lines 0))
  8418. (let ((slines (org-split-string s "\n")))
  8419. (when (< lines (length slines))
  8420. (setq s (mapconcat
  8421. 'identity
  8422. (reverse (nthcdr (- (length slines) lines)
  8423. (reverse slines))) "\n")))))
  8424. (mapconcat #'identity (split-string s) " ")))
  8425. (defconst org-link-escape-chars
  8426. ;;%20 %5B %5D %25
  8427. '(?\s ?\[ ?\] ?%)
  8428. "List of characters that should be escaped in a link when stored to Org.
  8429. This is the list that is used for internal purposes.")
  8430. (defun org-make-link-string (link &optional description)
  8431. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8432. (unless (org-string-nw-p link) (error "Empty link"))
  8433. (let ((uri (cond ((string-match org-link-types-re link)
  8434. (concat (match-string 1 link)
  8435. (org-link-escape (substring link (match-end 1)))))
  8436. ((or (file-name-absolute-p link)
  8437. (string-match-p "\\`\\.\\.?/" link))
  8438. (org-link-escape link))
  8439. ;; For readability, do not encode space characters
  8440. ;; in fuzzy links.
  8441. (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
  8442. (description
  8443. (and (org-string-nw-p description)
  8444. ;; Remove brackets from description, as they are fatal.
  8445. (replace-regexp-in-string
  8446. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8447. (org-trim description)))))
  8448. (format "[[%s]%s]"
  8449. uri
  8450. (if description (format "[%s]" description) ""))))
  8451. (defun org-link-escape (text &optional table merge)
  8452. "Return percent escaped representation of TEXT.
  8453. TEXT is a string with the text to escape.
  8454. Optional argument TABLE is a list with characters that should be
  8455. escaped. When nil, `org-link-escape-chars' is used.
  8456. If optional argument MERGE is set, merge TABLE into
  8457. `org-link-escape-chars'."
  8458. (let ((characters-to-encode
  8459. (cond ((null table) org-link-escape-chars)
  8460. (merge (append org-link-escape-chars table))
  8461. (t table))))
  8462. (mapconcat
  8463. (lambda (c)
  8464. (if (or (memq c characters-to-encode)
  8465. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8466. (mapconcat (lambda (e) (format "%%%.2X" e))
  8467. (or (encode-coding-char c 'utf-8)
  8468. (error "Unable to percent escape character: %c" c))
  8469. "")
  8470. (char-to-string c)))
  8471. text "")))
  8472. (defun org-link-unescape (str)
  8473. "Unhex hexified Unicode parts in string STR.
  8474. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  8475. reciprocal of `org-link-escape', which see."
  8476. (if (org-string-nw-p str)
  8477. (replace-regexp-in-string
  8478. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  8479. str))
  8480. (defun org-link-unescape-compound (hex)
  8481. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  8482. Note: this function also decodes single byte encodings like
  8483. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  8484. (save-match-data
  8485. (let* ((bytes (cdr (split-string hex "%")))
  8486. (ret "")
  8487. (eat 0)
  8488. (sum 0))
  8489. (while bytes
  8490. (let* ((val (string-to-number (pop bytes) 16))
  8491. (shift-xor
  8492. (if (= 0 eat)
  8493. (cond
  8494. ((>= val 252) (cons 6 252))
  8495. ((>= val 248) (cons 5 248))
  8496. ((>= val 240) (cons 4 240))
  8497. ((>= val 224) (cons 3 224))
  8498. ((>= val 192) (cons 2 192))
  8499. (t (cons 0 0)))
  8500. (cons 6 128))))
  8501. (when (>= val 192) (setq eat (car shift-xor)))
  8502. (setq val (logxor val (cdr shift-xor)))
  8503. (setq sum (+ (lsh sum (car shift-xor)) val))
  8504. (when (> eat 0) (setq eat (- eat 1)))
  8505. (cond
  8506. ((= 0 eat) ;multi byte
  8507. (setq ret (concat ret (char-to-string sum)))
  8508. (setq sum 0))
  8509. ((not bytes) ; single byte(s)
  8510. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  8511. ret)))
  8512. (defun org-link-unescape-single-byte-sequence (hex)
  8513. "Unhexify hex-encoded single byte character sequences."
  8514. (mapconcat (lambda (byte)
  8515. (char-to-string (string-to-number byte 16)))
  8516. (cdr (split-string hex "%")) ""))
  8517. (defun org-fixup-message-id-for-http (s)
  8518. "Replace special characters in a message id, so it can be used in an http query."
  8519. (when (string-match "%" s)
  8520. (setq s (mapconcat (lambda (c)
  8521. (if (eq c ?%)
  8522. "%25"
  8523. (char-to-string c)))
  8524. s "")))
  8525. (while (string-match "<" s)
  8526. (setq s (replace-match "%3C" t t s)))
  8527. (while (string-match ">" s)
  8528. (setq s (replace-match "%3E" t t s)))
  8529. (while (string-match "@" s)
  8530. (setq s (replace-match "%40" t t s)))
  8531. s)
  8532. (defun org-link-prettify (link)
  8533. "Return a human-readable representation of LINK.
  8534. The car of LINK must be a raw link.
  8535. The cdr of LINK must be either a link description or nil."
  8536. (let ((desc (or (cadr link) "<no description>")))
  8537. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  8538. "<" (car link) ">")))
  8539. ;;;###autoload
  8540. (defun org-insert-link-global ()
  8541. "Insert a link like Org mode does.
  8542. This command can be called in any mode to insert a link in Org syntax."
  8543. (interactive)
  8544. (org-load-modules-maybe)
  8545. (org-run-like-in-org-mode 'org-insert-link))
  8546. (defun org-insert-all-links (arg &optional pre post)
  8547. "Insert all links in `org-stored-links'.
  8548. When a universal prefix, do not delete the links from `org-stored-links'.
  8549. When `ARG' is a number, insert the last N link(s).
  8550. `PRE' and `POST' are optional arguments to define a string to
  8551. prepend or to append."
  8552. (interactive "P")
  8553. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  8554. (links (copy-sequence org-stored-links))
  8555. (pr (or pre "- "))
  8556. (po (or post "\n"))
  8557. (cnt 1) l)
  8558. (if (null org-stored-links)
  8559. (message "No link to insert")
  8560. (while (and (or (listp arg) (>= arg cnt))
  8561. (setq l (if (listp arg)
  8562. (pop links)
  8563. (pop org-stored-links))))
  8564. (setq cnt (1+ cnt))
  8565. (insert pr)
  8566. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  8567. (insert po)))))
  8568. (defun org-insert-last-stored-link (arg)
  8569. "Insert the last link stored in `org-stored-links'."
  8570. (interactive "p")
  8571. (org-insert-all-links arg "" "\n"))
  8572. (defun org-link-fontify-links-to-this-file ()
  8573. "Fontify links to the current file in `org-stored-links'."
  8574. (let ((f (buffer-file-name)) a b)
  8575. (setq a (mapcar (lambda(l)
  8576. (let ((ll (car l)))
  8577. (when (and (string-match "^file:\\(.+\\)::" ll)
  8578. (equal f (expand-file-name (match-string 1 ll))))
  8579. ll)))
  8580. org-stored-links))
  8581. (when (featurep 'org-id)
  8582. (setq b (mapcar (lambda(l)
  8583. (let ((ll (car l)))
  8584. (when (and (string-match "^id:\\(.+\\)$" ll)
  8585. (equal f (expand-file-name
  8586. (or (org-id-find-id-file
  8587. (match-string 1 ll)) ""))))
  8588. ll)))
  8589. org-stored-links)))
  8590. (mapcar (lambda(l)
  8591. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  8592. (delq nil (append a b)))))
  8593. (defvar org--links-history nil)
  8594. (defun org-insert-link (&optional complete-file link-location default-description)
  8595. "Insert a link. At the prompt, enter the link.
  8596. Completion can be used to insert any of the link protocol prefixes in use.
  8597. The history can be used to select a link previously stored with
  8598. `org-store-link'. When the empty string is entered (i.e. if you just
  8599. press `RET' at the prompt), the link defaults to the most recently
  8600. stored link. As `SPC' triggers completion in the minibuffer, you need to
  8601. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  8602. You will also be prompted for a description, and if one is given, it will
  8603. be displayed in the buffer instead of the link.
  8604. If there is already a link at point, this command will allow you to edit
  8605. link and description parts.
  8606. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  8607. file name can be
  8608. selected using completion. The path to the file will be relative to the
  8609. current directory if the file is in the current directory or a subdirectory.
  8610. Otherwise, the link will be the absolute path as completed in the minibuffer
  8611. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  8612. option `org-link-file-path-type'.
  8613. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  8614. absolute path even if the file is in
  8615. the current directory or below.
  8616. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8617. prefix negates `org-keep-stored-link-after-insertion'.
  8618. If the LINK-LOCATION parameter is non-nil, this value will be used as
  8619. the link location instead of reading one interactively.
  8620. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  8621. be used as the default description. Otherwise, if
  8622. `org-make-link-description-function' is non-nil, this function
  8623. will be called with the link target, and the result will be the
  8624. default link description. When called non-interactivily, don't
  8625. allow to edit the default description."
  8626. (interactive "P")
  8627. (let* ((wcf (current-window-configuration))
  8628. (origbuf (current-buffer))
  8629. (region (when (org-region-active-p)
  8630. (buffer-substring (region-beginning) (region-end))))
  8631. (remove (and region (list (region-beginning) (region-end))))
  8632. (desc region)
  8633. (link link-location)
  8634. (abbrevs org-link-abbrev-alist-local)
  8635. entry all-prefixes auto-desc)
  8636. (cond
  8637. (link-location) ; specified by arg, just use it.
  8638. ((org-in-regexp org-bracket-link-regexp 1)
  8639. ;; We do have a link at point, and we are going to edit it.
  8640. (setq remove (list (match-beginning 0) (match-end 0)))
  8641. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  8642. (setq link (read-string "Link: "
  8643. (org-link-unescape
  8644. (match-string-no-properties 1)))))
  8645. ((or (org-in-regexp org-angle-link-re)
  8646. (org-in-regexp org-plain-link-re))
  8647. ;; Convert to bracket link
  8648. (setq remove (list (match-beginning 0) (match-end 0))
  8649. link (read-string "Link: "
  8650. (org-unbracket-string "<" ">" (match-string 0)))))
  8651. ((member complete-file '((4) (16)))
  8652. ;; Completing read for file names.
  8653. (setq link (org-file-complete-link complete-file)))
  8654. (t
  8655. ;; Read link, with completion for stored links.
  8656. (org-link-fontify-links-to-this-file)
  8657. (org-switch-to-buffer-other-window "*Org Links*")
  8658. (with-current-buffer "*Org Links*"
  8659. (erase-buffer)
  8660. (insert "Insert a link.
  8661. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  8662. (when org-stored-links
  8663. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  8664. (insert (mapconcat 'org-link-prettify
  8665. (reverse org-stored-links) "\n")))
  8666. (goto-char (point-min)))
  8667. (let ((cw (selected-window)))
  8668. (select-window (get-buffer-window "*Org Links*" 'visible))
  8669. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  8670. (unless (pos-visible-in-window-p (point-max))
  8671. (org-fit-window-to-buffer))
  8672. (and (window-live-p cw) (select-window cw)))
  8673. (setq all-prefixes (append (mapcar 'car abbrevs)
  8674. (mapcar 'car org-link-abbrev-alist)
  8675. (org-link-types)))
  8676. (unwind-protect
  8677. ;; Fake a link history, containing the stored links.
  8678. (let ((org--links-history
  8679. (append (mapcar #'car org-stored-links)
  8680. org-insert-link-history)))
  8681. (setq link
  8682. (org-completing-read
  8683. "Link: "
  8684. (append
  8685. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  8686. (mapcar #'car org-stored-links))
  8687. nil nil nil
  8688. 'org--links-history
  8689. (caar org-stored-links)))
  8690. (unless (org-string-nw-p link) (user-error "No link selected"))
  8691. (dolist (l org-stored-links)
  8692. (when (equal link (cadr l))
  8693. (setq link (car l))
  8694. (setq auto-desc t)))
  8695. (when (or (member link all-prefixes)
  8696. (and (equal ":" (substring link -1))
  8697. (member (substring link 0 -1) all-prefixes)
  8698. (setq link (substring link 0 -1))))
  8699. (setq link (with-current-buffer origbuf
  8700. (org-link-try-special-completion link)))))
  8701. (set-window-configuration wcf)
  8702. (kill-buffer "*Org Links*"))
  8703. (setq entry (assoc link org-stored-links))
  8704. (or entry (push link org-insert-link-history))
  8705. (setq desc (or desc (nth 1 entry)))))
  8706. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  8707. (not org-keep-stored-link-after-insertion))
  8708. (setq org-stored-links (delq (assoc link org-stored-links)
  8709. org-stored-links)))
  8710. (when (and (string-match org-plain-link-re link)
  8711. (not (string-match org-ts-regexp link)))
  8712. ;; URL-like link, normalize the use of angular brackets.
  8713. (setq link (org-unbracket-string "<" ">" link)))
  8714. ;; Check if we are linking to the current file with a search
  8715. ;; option If yes, simplify the link by using only the search
  8716. ;; option.
  8717. (when (and buffer-file-name
  8718. (let ((case-fold-search nil))
  8719. (string-match "\\`file:\\(.+?\\)::" link)))
  8720. (let ((path (match-string-no-properties 1 link))
  8721. (search (substring-no-properties link (match-end 0))))
  8722. (save-match-data
  8723. (when (equal (file-truename buffer-file-name) (file-truename path))
  8724. ;; We are linking to this same file, with a search option
  8725. (setq link search)))))
  8726. ;; Check if we can/should use a relative path. If yes, simplify
  8727. ;; the link.
  8728. (let ((case-fold-search nil))
  8729. (when (string-match "\\`\\(file\\|docview\\):" link)
  8730. (let* ((type (match-string-no-properties 0 link))
  8731. (path-start (match-end 0))
  8732. (search (and (string-match "::\\(.*\\)\\'" link)
  8733. (match-string 1 link)))
  8734. (path
  8735. (if search
  8736. (substring-no-properties
  8737. link path-start (match-beginning 0))
  8738. (substring-no-properties link (match-end 0))))
  8739. (origpath path))
  8740. (cond
  8741. ((or (eq org-link-file-path-type 'absolute)
  8742. (equal complete-file '(16)))
  8743. (setq path (abbreviate-file-name (expand-file-name path))))
  8744. ((eq org-link-file-path-type 'noabbrev)
  8745. (setq path (expand-file-name path)))
  8746. ((eq org-link-file-path-type 'relative)
  8747. (setq path (file-relative-name path)))
  8748. (t
  8749. (save-match-data
  8750. (if (string-match (concat "^" (regexp-quote
  8751. (expand-file-name
  8752. (file-name-as-directory
  8753. default-directory))))
  8754. (expand-file-name path))
  8755. ;; We are linking a file with relative path name.
  8756. (setq path (substring (expand-file-name path)
  8757. (match-end 0)))
  8758. (setq path (abbreviate-file-name (expand-file-name path)))))))
  8759. (setq link (concat type path (and search (concat "::" search))))
  8760. (when (equal desc origpath)
  8761. (setq desc path)))))
  8762. (unless auto-desc
  8763. (let ((initial-input
  8764. (cond
  8765. (default-description)
  8766. ((not org-make-link-description-function) desc)
  8767. (t (condition-case nil
  8768. (funcall org-make-link-description-function link desc)
  8769. (error
  8770. (message "Can't get link description from `%s'"
  8771. (symbol-name org-make-link-description-function))
  8772. (sit-for 2)
  8773. nil))))))
  8774. (setq desc (if (called-interactively-p 'any)
  8775. (read-string "Description: " initial-input)
  8776. initial-input))))
  8777. (unless (string-match "\\S-" desc) (setq desc nil))
  8778. (when remove (apply 'delete-region remove))
  8779. (insert (org-make-link-string link desc))
  8780. ;; Redisplay so as the new link has proper invisible characters.
  8781. (sit-for 0)))
  8782. (defun org-link-try-special-completion (type)
  8783. "If there is completion support for link type TYPE, offer it."
  8784. (let ((fun (org-link-get-parameter type :complete)))
  8785. (if (functionp fun)
  8786. (funcall fun)
  8787. (read-string "Link (no completion support): " (concat type ":")))))
  8788. (defun org-file-complete-link (&optional arg)
  8789. "Create a file link using completion."
  8790. (let ((file (read-file-name "File: "))
  8791. (pwd (file-name-as-directory (expand-file-name ".")))
  8792. (pwd1 (file-name-as-directory (abbreviate-file-name
  8793. (expand-file-name ".")))))
  8794. (cond ((equal arg '(16))
  8795. (concat "file:"
  8796. (abbreviate-file-name (expand-file-name file))))
  8797. ((string-match
  8798. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  8799. (concat "file:" (match-string 1 file)))
  8800. ((string-match
  8801. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  8802. (expand-file-name file))
  8803. (concat "file:"
  8804. (match-string 1 (expand-file-name file))))
  8805. (t (concat "file:" file)))))
  8806. ;;; Opening/following a link
  8807. (defvar org-link-search-failed nil)
  8808. (defvar org-open-link-functions nil
  8809. "Hook for functions finding a plain text link.
  8810. These functions must take a single argument, the link content.
  8811. They will be called for links that look like [[link text][description]]
  8812. when LINK TEXT does not have a protocol like \"http:\" and does not look
  8813. like a filename (e.g. \"./blue.png\").
  8814. These functions will be called *before* Org attempts to resolve the
  8815. link by doing text searches in the current buffer - so if you want a
  8816. link \"[[target]]\" to still find \"<<target>>\", your function should
  8817. handle this as a special case.
  8818. When the function does handle the link, it must return a non-nil value.
  8819. If it decides that it is not responsible for this link, it must return
  8820. nil to indicate that that Org can continue with other options like
  8821. exact and fuzzy text search.")
  8822. (defun org-next-link (&optional search-backward)
  8823. "Move forward to the next link.
  8824. If the link is in hidden text, expose it."
  8825. (interactive "P")
  8826. (when (and org-link-search-failed (eq this-command last-command))
  8827. (goto-char (point-min))
  8828. (message "Link search wrapped back to beginning of buffer"))
  8829. (setq org-link-search-failed nil)
  8830. (let* ((pos (point))
  8831. (ct (org-context))
  8832. (a (assq :link ct))
  8833. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  8834. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  8835. ((looking-at org-any-link-re)
  8836. ;; Don't stay stuck at link without an org-link face
  8837. (forward-char (if search-backward -1 1))))
  8838. (if (funcall srch-fun org-any-link-re nil t)
  8839. (progn
  8840. (goto-char (match-beginning 0))
  8841. (when (org-invisible-p) (org-show-context)))
  8842. (goto-char pos)
  8843. (setq org-link-search-failed t)
  8844. (message "No further link found"))))
  8845. (defun org-previous-link ()
  8846. "Move backward to the previous link.
  8847. If the link is in hidden text, expose it."
  8848. (interactive)
  8849. (funcall 'org-next-link t))
  8850. (defun org-translate-link (s)
  8851. "Translate a link string if a translation function has been defined."
  8852. (with-temp-buffer
  8853. (insert (org-trim s))
  8854. (org-trim (org-element-interpret-data (org-element-context)))))
  8855. (defun org-translate-link-from-planner (type path)
  8856. "Translate a link from Emacs Planner syntax so that Org can follow it.
  8857. This is still an experimental function, your mileage may vary."
  8858. (cond
  8859. ((member type '("http" "https" "news" "ftp"))
  8860. ;; standard Internet links are the same.
  8861. nil)
  8862. ((and (equal type "irc") (string-match "^//" path))
  8863. ;; Planner has two / at the beginning of an irc link, we have 1.
  8864. ;; We should have zero, actually....
  8865. (setq path (substring path 1)))
  8866. ((and (equal type "lisp") (string-match "^/" path))
  8867. ;; Planner has a slash, we do not.
  8868. (setq type "elisp" path (substring path 1)))
  8869. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  8870. ;; A typical message link. Planner has the id after the final slash,
  8871. ;; we separate it with a hash mark
  8872. (setq path (concat (match-string 1 path) "#"
  8873. (org-unbracket-string "<" ">" (match-string 2 path))))))
  8874. (cons type path))
  8875. (defun org-find-file-at-mouse (ev)
  8876. "Open file link or URL at mouse."
  8877. (interactive "e")
  8878. (mouse-set-point ev)
  8879. (org-open-at-point 'in-emacs))
  8880. (defun org-open-at-mouse (ev)
  8881. "Open file link or URL at mouse.
  8882. See the docstring of `org-open-file' for details."
  8883. (interactive "e")
  8884. (mouse-set-point ev)
  8885. (when (eq major-mode 'org-agenda-mode)
  8886. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  8887. (org-open-at-point))
  8888. (defvar org-window-config-before-follow-link nil
  8889. "The window configuration before following a link.
  8890. This is saved in case the need arises to restore it.")
  8891. ;;;###autoload
  8892. (defun org-open-at-point-global ()
  8893. "Follow a link or a time-stamp like Org mode does.
  8894. Also follow links and emails as seen by `thing-at-point'.
  8895. This command can be called in any mode to follow an external
  8896. link or a time-stamp that has Org mode syntax. Its behavior
  8897. is undefined when called on internal links like fuzzy links.
  8898. Raise a user error when there is nothing to follow."
  8899. (interactive)
  8900. (let ((tap-url (thing-at-point 'url))
  8901. (tap-email (thing-at-point 'email)))
  8902. (cond ((org-in-regexp org-any-link-re)
  8903. (org-open-link-from-string (match-string-no-properties 0)))
  8904. ((or (org-in-regexp org-ts-regexp-both nil t)
  8905. (org-in-regexp org-tsr-regexp-both nil t))
  8906. (org-follow-timestamp-link))
  8907. (tap-url (org-open-link-from-string tap-url))
  8908. (tap-email (org-open-link-from-string
  8909. (concat "mailto:" tap-email)))
  8910. (t (user-error "No link found")))))
  8911. ;;;###autoload
  8912. (defun org-open-link-from-string (s &optional arg reference-buffer)
  8913. "Open a link in the string S, as if it was in Org mode."
  8914. (interactive "sLink: \nP")
  8915. (let ((reference-buffer (or reference-buffer (current-buffer))))
  8916. (with-temp-buffer
  8917. (let ((org-inhibit-startup (not reference-buffer)))
  8918. (org-mode)
  8919. (insert s)
  8920. (goto-char (point-min))
  8921. (when reference-buffer
  8922. (setq org-link-abbrev-alist-local
  8923. (with-current-buffer reference-buffer
  8924. org-link-abbrev-alist-local)))
  8925. (org-open-at-point arg reference-buffer)))))
  8926. (defvar org-open-at-point-functions nil
  8927. "Hook that is run when following a link at point.
  8928. Functions in this hook must return t if they identify and follow
  8929. a link at point. If they don't find anything interesting at point,
  8930. they must return nil.")
  8931. (defvar org-link-search-inhibit-query nil)
  8932. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  8933. (defun org--open-doi-link (path)
  8934. "Open a \"doi\" type link.
  8935. PATH is a the path to search for, as a string."
  8936. (browse-url (url-encode-url (concat org-doi-server-url path))))
  8937. (defun org--open-elisp-link (path)
  8938. "Open a \"elisp\" type link.
  8939. PATH is the sexp to evaluate, as a string."
  8940. (let ((cmd path))
  8941. (if (or (and (org-string-nw-p
  8942. org-confirm-elisp-link-not-regexp)
  8943. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  8944. (not org-confirm-elisp-link-function)
  8945. (funcall org-confirm-elisp-link-function
  8946. (format "Execute \"%s\" as elisp? "
  8947. (org-add-props cmd nil 'face 'org-warning))))
  8948. (message "%s => %s" cmd
  8949. (if (eq (string-to-char cmd) ?\()
  8950. (eval (read cmd))
  8951. (call-interactively (read cmd))))
  8952. (user-error "Abort"))))
  8953. (defun org--open-help-link (path)
  8954. "Open a \"help\" type link.
  8955. PATH is a symbol name, as a string."
  8956. (pcase (intern path)
  8957. ((and (pred fboundp) variable) (describe-function variable))
  8958. ((and (pred boundp) function) (describe-variable function))
  8959. (name (user-error "Unknown function or variable: %s" name))))
  8960. (defun org--open-shell-link (path)
  8961. "Open a \"shell\" type link.
  8962. PATH is the command to execute, as a string."
  8963. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  8964. (cmd path))
  8965. (if (or (and (org-string-nw-p
  8966. org-confirm-shell-link-not-regexp)
  8967. (string-match
  8968. org-confirm-shell-link-not-regexp cmd))
  8969. (not org-confirm-shell-link-function)
  8970. (funcall org-confirm-shell-link-function
  8971. (format "Execute \"%s\" in shell? "
  8972. (org-add-props cmd nil
  8973. 'face 'org-warning))))
  8974. (progn
  8975. (message "Executing %s" cmd)
  8976. (shell-command cmd buf)
  8977. (when (featurep 'midnight)
  8978. (setq clean-buffer-list-kill-buffer-names
  8979. (cons (buffer-name buf)
  8980. clean-buffer-list-kill-buffer-names))))
  8981. (user-error "Abort"))))
  8982. (defun org-open-at-point (&optional arg reference-buffer)
  8983. "Open link, timestamp, footnote or tags at point.
  8984. When point is on a link, follow it. Normally, files will be
  8985. opened by an appropriate application. If the optional prefix
  8986. argument ARG is non-nil, Emacs will visit the file. With
  8987. a double prefix argument, try to open outside of Emacs, in the
  8988. application the system uses for this file type.
  8989. When point is on a timestamp, open the agenda at the day
  8990. specified.
  8991. When point is a footnote definition, move to the first reference
  8992. found. If it is on a reference, move to the associated
  8993. definition.
  8994. When point is on a headline, display a list of every link in the
  8995. entry, so it is possible to pick one, or all, of them. If point
  8996. is on a tag, call `org-tags-view' instead.
  8997. When optional argument REFERENCE-BUFFER is non-nil, it should
  8998. specify a buffer from where the link search should happen. This
  8999. is used internally by `org-open-link-from-string'.
  9000. On top of syntactically correct links, this function will also
  9001. try to open links and time-stamps in comments, example
  9002. blocks... i.e., whenever point is on something looking like
  9003. a timestamp or a link."
  9004. (interactive "P")
  9005. ;; On a code block, open block's results.
  9006. (unless (call-interactively 'org-babel-open-src-block-result)
  9007. (org-load-modules-maybe)
  9008. (setq org-window-config-before-follow-link (current-window-configuration))
  9009. (org-remove-occur-highlights nil nil t)
  9010. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9011. (let* ((context
  9012. ;; Only consider supported types, even if they are not
  9013. ;; the closest one.
  9014. (org-element-lineage
  9015. (org-element-context)
  9016. '(clock footnote-definition footnote-reference headline
  9017. inlinetask link timestamp)
  9018. t))
  9019. (type (org-element-type context))
  9020. (value (org-element-property :value context)))
  9021. (cond
  9022. ;; On a headline or an inlinetask, but not on a timestamp,
  9023. ;; a link, a footnote reference.
  9024. ((memq type '(headline inlinetask))
  9025. (org-match-line org-complex-heading-regexp)
  9026. (if (and (match-beginning 5)
  9027. (>= (point) (match-beginning 5))
  9028. (< (point) (match-end 5)))
  9029. ;; On tags.
  9030. (org-tags-view arg (substring (match-string 5) 0 -1))
  9031. ;; Not on tags.
  9032. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  9033. (`(nil . ,_)
  9034. (require 'org-attach)
  9035. (org-attach-reveal 'if-exists))
  9036. (`(,links . ,links-end)
  9037. (dolist (link (if (stringp links) (list links) links))
  9038. (search-forward link nil links-end)
  9039. (goto-char (match-beginning 0))
  9040. (org-open-at-point))))))
  9041. ;; On a footnote reference or at definition's label.
  9042. ((or (eq type 'footnote-reference)
  9043. (and (eq type 'footnote-definition)
  9044. (save-excursion
  9045. ;; Do not validate action when point is on the
  9046. ;; spaces right after the footnote label, in
  9047. ;; order to be on par with behavior on links.
  9048. (skip-chars-forward " \t")
  9049. (let ((begin
  9050. (org-element-property :contents-begin context)))
  9051. (if begin (< (point) begin)
  9052. (= (org-element-property :post-affiliated context)
  9053. (line-beginning-position)))))))
  9054. (org-footnote-action))
  9055. ;; No valid context. Ignore catch-all types like `headline'.
  9056. ;; If point is on something looking like a link or
  9057. ;; a time-stamp, try opening it. It may be useful in
  9058. ;; comments, example blocks...
  9059. ((memq type '(footnote-definition headline inlinetask nil))
  9060. (call-interactively #'org-open-at-point-global))
  9061. ;; On a clock line, make sure point is on the timestamp
  9062. ;; before opening it.
  9063. ((and (eq type 'clock)
  9064. value
  9065. (>= (point) (org-element-property :begin value))
  9066. (<= (point) (org-element-property :end value)))
  9067. (org-follow-timestamp-link))
  9068. ;; Do nothing on white spaces after an object.
  9069. ((>= (point)
  9070. (save-excursion
  9071. (goto-char (org-element-property :end context))
  9072. (skip-chars-backward " \t")
  9073. (point)))
  9074. (user-error "No link found"))
  9075. ((eq type 'timestamp) (org-follow-timestamp-link))
  9076. ((eq type 'link)
  9077. (let ((type (org-element-property :type context))
  9078. (path (org-link-unescape (org-element-property :path context))))
  9079. ;; Switch back to REFERENCE-BUFFER needed when called in
  9080. ;; a temporary buffer through `org-open-link-from-string'.
  9081. (with-current-buffer (or reference-buffer (current-buffer))
  9082. (cond
  9083. ((equal type "file")
  9084. (if (string-match "[*?{]" (file-name-nondirectory path))
  9085. (dired path)
  9086. ;; Look into `org-link-parameters' in order to find
  9087. ;; a DEDICATED-FUNCTION to open file. The function
  9088. ;; will be applied on raw link instead of parsed
  9089. ;; link due to the limitation in `org-add-link-type'
  9090. ;; ("open" function called with a single argument).
  9091. ;; If no such function is found, fallback to
  9092. ;; `org-open-file'.
  9093. (let* ((option (org-element-property :search-option context))
  9094. (app (org-element-property :application context))
  9095. (dedicated-function
  9096. (org-link-get-parameter
  9097. (if app (concat type "+" app) type)
  9098. :follow)))
  9099. (if dedicated-function
  9100. (funcall dedicated-function
  9101. (concat path
  9102. (and option (concat "::" option))))
  9103. (apply #'org-open-file
  9104. path
  9105. (cond (arg)
  9106. ((equal app "emacs") 'emacs)
  9107. ((equal app "sys") 'system))
  9108. (cond ((not option) nil)
  9109. ((string-match-p "\\`[0-9]+\\'" option)
  9110. (list (string-to-number option)))
  9111. (t (list nil
  9112. (org-link-unescape option)))))))))
  9113. ((functionp (org-link-get-parameter type :follow))
  9114. (funcall (org-link-get-parameter type :follow) path))
  9115. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9116. (unless (run-hook-with-args-until-success
  9117. 'org-open-link-functions path)
  9118. (if (not arg) (org-mark-ring-push)
  9119. (switch-to-buffer-other-window
  9120. (org-get-buffer-for-internal-link (current-buffer))))
  9121. (let ((destination
  9122. (org-with-wide-buffer
  9123. (if (equal type "radio")
  9124. (org-search-radio-target
  9125. (org-element-property :path context))
  9126. (org-link-search
  9127. (if (member type '("custom-id" "coderef"))
  9128. (org-element-property :raw-link context)
  9129. path)
  9130. ;; Prevent fuzzy links from matching
  9131. ;; themselves.
  9132. (and (equal type "fuzzy")
  9133. (+ 2 (org-element-property :begin context)))))
  9134. (point))))
  9135. (unless (and (<= (point-min) destination)
  9136. (>= (point-max) destination))
  9137. (widen))
  9138. (goto-char destination))))
  9139. (t (browse-url-at-point))))))
  9140. (t (user-error "No link found")))))
  9141. (run-hook-with-args 'org-follow-link-hook)))
  9142. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9143. "Offer links in the current entry and return the selected link.
  9144. If there is only one link, return it.
  9145. If NTH is an integer, return the NTH link found.
  9146. If ZERO is a string, check also this string for a link, and if
  9147. there is one, return it."
  9148. (with-current-buffer buffer
  9149. (org-with-wide-buffer
  9150. (goto-char marker)
  9151. (let ((cnt ?0)
  9152. have-zero end links link c)
  9153. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9154. (push (match-string 0 zero) links)
  9155. (setq cnt (1- cnt) have-zero t))
  9156. (save-excursion
  9157. (org-back-to-heading t)
  9158. (setq end (save-excursion (outline-next-heading) (point)))
  9159. (while (re-search-forward org-any-link-re end t)
  9160. (push (match-string 0) links))
  9161. (setq links (org-uniquify (reverse links))))
  9162. (cond
  9163. ((null links)
  9164. (message "No links"))
  9165. ((equal (length links) 1)
  9166. (setq link (car links)))
  9167. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9168. (setq link (nth (if have-zero nth (1- nth)) links)))
  9169. (t ; we have to select a link
  9170. (save-excursion
  9171. (save-window-excursion
  9172. (delete-other-windows)
  9173. (with-output-to-temp-buffer "*Select Link*"
  9174. (dolist (l links)
  9175. (cond
  9176. ((not (string-match org-bracket-link-regexp l))
  9177. (princ (format "[%c] %s\n" (cl-incf cnt)
  9178. (org-unbracket-string "<" ">" l))))
  9179. ((match-end 3)
  9180. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9181. (match-string 3 l) (match-string 1 l))))
  9182. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9183. (match-string 1 l)))))))
  9184. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9185. (message "Select link to open, RET to open all:")
  9186. (setq c (read-char-exclusive))
  9187. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9188. (when (equal c ?q) (user-error "Abort"))
  9189. (if (equal c ?\C-m)
  9190. (setq link links)
  9191. (setq nth (- c ?0))
  9192. (when have-zero (setq nth (1+ nth)))
  9193. (unless (and (integerp nth) (>= (length links) nth))
  9194. (user-error "Invalid link selection"))
  9195. (setq link (nth (1- nth) links)))))
  9196. (cons link end)))))
  9197. ;; TODO: These functions are deprecated since `org-open-at-point'
  9198. ;; hard-codes behavior for "file+emacs" and "file+sys" types.
  9199. (defun org-open-file-with-system (path)
  9200. "Open file at PATH using the system way of opening it."
  9201. (org-open-file path 'system))
  9202. (defun org-open-file-with-emacs (path)
  9203. "Open file at PATH in Emacs."
  9204. (org-open-file path 'emacs))
  9205. ;;; File search
  9206. (defvar org-create-file-search-functions nil
  9207. "List of functions to construct the right search string for a file link.
  9208. These functions are called in turn with point at the location to
  9209. which the link should point.
  9210. A function in the hook should first test if it would like to
  9211. handle this file type, for example by checking the `major-mode'
  9212. or the file extension. If it decides not to handle this file, it
  9213. should just return nil to give other functions a chance. If it
  9214. does handle the file, it must return the search string to be used
  9215. when following the link. The search string will be part of the
  9216. file link, given after a double colon, and `org-open-at-point'
  9217. will automatically search for it. If special measures must be
  9218. taken to make the search successful, another function should be
  9219. added to the companion hook `org-execute-file-search-functions',
  9220. which see.
  9221. A function in this hook may also use `setq' to set the variable
  9222. `description' to provide a suggestion for the descriptive text to
  9223. be used for this link when it gets inserted into an Org buffer
  9224. with \\[org-insert-link].")
  9225. (defvar org-execute-file-search-functions nil
  9226. "List of functions to execute a file search triggered by a link.
  9227. Functions added to this hook must accept a single argument, the
  9228. search string that was part of the file link, the part after the
  9229. double colon. The function must first check if it would like to
  9230. handle this search, for example by checking the `major-mode' or
  9231. the file extension. If it decides not to handle this search, it
  9232. should just return nil to give other functions a chance. If it
  9233. does handle the search, it must return a non-nil value to keep
  9234. other functions from trying.
  9235. Each function can access the current prefix argument through the
  9236. variable `current-prefix-arg'. Note that a single prefix is used
  9237. to force opening a link in Emacs, so it may be good to only use a
  9238. numeric or double prefix to guide the search function.
  9239. In case this is needed, a function in this hook can also restore
  9240. the window configuration before `org-open-at-point' was called using:
  9241. (set-window-configuration org-window-config-before-follow-link)")
  9242. (defun org-search-radio-target (target)
  9243. "Search a radio target matching TARGET in current buffer.
  9244. White spaces are not significant."
  9245. (let ((re (format "<<<%s>>>"
  9246. (mapconcat #'regexp-quote
  9247. (split-string target)
  9248. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9249. (origin (point)))
  9250. (goto-char (point-min))
  9251. (catch :radio-match
  9252. (while (re-search-forward re nil t)
  9253. (backward-char)
  9254. (let ((object (org-element-context)))
  9255. (when (eq (org-element-type object) 'radio-target)
  9256. (goto-char (org-element-property :begin object))
  9257. (org-show-context 'link-search)
  9258. (throw :radio-match nil))))
  9259. (goto-char origin)
  9260. (user-error "No match for radio target: %s" target))))
  9261. (defun org-link-search (s &optional avoid-pos stealth)
  9262. "Search for a search string S.
  9263. If S starts with \"#\", it triggers a custom ID search.
  9264. If S is enclosed within parenthesis, it initiates a coderef
  9265. search.
  9266. If S is surrounded by forward slashes, it is interpreted as
  9267. a regular expression. In Org mode files, this will create an
  9268. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9269. to list matches. If the current buffer is in `dired-mode', grep
  9270. will be used to search in all files.
  9271. When AVOID-POS is given, ignore matches near that position.
  9272. When optional argument STEALTH is non-nil, do not modify
  9273. visibility around point, thus ignoring `org-show-context-detail'
  9274. variable.
  9275. Search is case-insensitive and ignores white spaces. Return type
  9276. of matched result, which is either `dedicated' or `fuzzy'."
  9277. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9278. (let* ((case-fold-search t)
  9279. (origin (point))
  9280. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9281. (starred (eq (string-to-char normalized) ?*))
  9282. (words (split-string (if starred (substring s 1) s)))
  9283. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9284. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9285. type)
  9286. (cond
  9287. ;; Check if there are any special search functions.
  9288. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9289. ((eq (string-to-char s) ?#)
  9290. ;; Look for a custom ID S if S starts with "#".
  9291. (let* ((id (substring normalized 1))
  9292. (match (org-find-property "CUSTOM_ID" id)))
  9293. (if match (progn (goto-char match) (setf type 'dedicated))
  9294. (error "No match for custom ID: %s" id))))
  9295. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9296. ;; Look for coderef targets if S is enclosed within parenthesis.
  9297. (let ((coderef (match-string-no-properties 1 normalized))
  9298. (re (substring s-single-re 1 -1)))
  9299. (goto-char (point-min))
  9300. (catch :coderef-match
  9301. (while (re-search-forward re nil t)
  9302. (let ((element (org-element-at-point)))
  9303. (when (and (memq (org-element-type element)
  9304. '(example-block src-block))
  9305. ;; Build proper regexp according to current
  9306. ;; block's label format.
  9307. (let ((label-fmt
  9308. (regexp-quote
  9309. (or (org-element-property :label-fmt element)
  9310. org-coderef-label-format))))
  9311. (save-excursion
  9312. (beginning-of-line)
  9313. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9314. (format label-fmt coderef))))))
  9315. (setq type 'dedicated)
  9316. (goto-char (match-beginning 1))
  9317. (throw :coderef-match nil))))
  9318. (goto-char origin)
  9319. (error "No match for coderef: %s" coderef))))
  9320. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9321. ;; Look for a regular expression.
  9322. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9323. (match-string 1 s)))
  9324. ;; From here, we handle fuzzy links.
  9325. ;;
  9326. ;; Look for targets, only if not in a headline search.
  9327. ((and (not starred)
  9328. (let ((target (format "<<%s>>" s-multi-re)))
  9329. (catch :target-match
  9330. (goto-char (point-min))
  9331. (while (re-search-forward target nil t)
  9332. (backward-char)
  9333. (let ((context (org-element-context)))
  9334. (when (eq (org-element-type context) 'target)
  9335. (setq type 'dedicated)
  9336. (goto-char (org-element-property :begin context))
  9337. (throw :target-match t))))
  9338. nil))))
  9339. ;; Look for elements named after S, only if not in a headline
  9340. ;; search.
  9341. ((and (not starred)
  9342. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9343. (catch :name-match
  9344. (goto-char (point-min))
  9345. (while (re-search-forward name nil t)
  9346. (let ((element (org-element-at-point)))
  9347. (when (equal words
  9348. (split-string
  9349. (org-element-property :name element)))
  9350. (setq type 'dedicated)
  9351. (beginning-of-line)
  9352. (throw :name-match t))))
  9353. nil))))
  9354. ;; Regular text search. Prefer headlines in Org mode buffers.
  9355. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9356. ;; statistics cookies and tags.
  9357. ((and (derived-mode-p 'org-mode)
  9358. (let ((title-re
  9359. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9360. org-outline-regexp-bol
  9361. org-comment-string
  9362. (mapconcat #'regexp-quote words ".+")))
  9363. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9364. (comment-re (eval-when-compile
  9365. (format "\\`%s[ \t]+" org-comment-string))))
  9366. (goto-char (point-min))
  9367. (catch :found
  9368. (while (re-search-forward title-re nil t)
  9369. (when (equal words
  9370. (split-string
  9371. (replace-regexp-in-string
  9372. cookie-re ""
  9373. (replace-regexp-in-string
  9374. comment-re "" (org-get-heading t t t)))))
  9375. (throw :found t)))
  9376. nil)))
  9377. (beginning-of-line)
  9378. (setq type 'dedicated))
  9379. ;; Offer to create non-existent headline depending on
  9380. ;; `org-link-search-must-match-exact-headline'.
  9381. ((and (derived-mode-p 'org-mode)
  9382. (not org-link-search-inhibit-query)
  9383. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9384. (yes-or-no-p "No match - create this as a new heading? "))
  9385. (goto-char (point-max))
  9386. (unless (bolp) (newline))
  9387. (org-insert-heading nil t t)
  9388. (insert s "\n")
  9389. (beginning-of-line 0))
  9390. ;; Only headlines are looked after. No need to process
  9391. ;; further: throw an error.
  9392. ((and (derived-mode-p 'org-mode)
  9393. (or starred org-link-search-must-match-exact-headline))
  9394. (goto-char origin)
  9395. (error "No match for fuzzy expression: %s" normalized))
  9396. ;; Regular text search.
  9397. ((catch :fuzzy-match
  9398. (goto-char (point-min))
  9399. (while (re-search-forward s-multi-re nil t)
  9400. ;; Skip match if it contains AVOID-POS or it is included in
  9401. ;; a link with a description but outside the description.
  9402. (unless (or (and avoid-pos
  9403. (<= (match-beginning 0) avoid-pos)
  9404. (> (match-end 0) avoid-pos))
  9405. (and (save-match-data
  9406. (org-in-regexp org-bracket-link-regexp))
  9407. (match-beginning 3)
  9408. (or (> (match-beginning 3) (point))
  9409. (<= (match-end 3) (point)))
  9410. (org-element-lineage
  9411. (save-match-data (org-element-context))
  9412. '(link) t)))
  9413. (goto-char (match-beginning 0))
  9414. (setq type 'fuzzy)
  9415. (throw :fuzzy-match t)))
  9416. nil))
  9417. ;; All failed. Throw an error.
  9418. (t (goto-char origin)
  9419. (error "No match for fuzzy expression: %s" normalized)))
  9420. ;; Disclose surroundings of match, if appropriate.
  9421. (when (and (derived-mode-p 'org-mode) (not stealth))
  9422. (org-show-context 'link-search))
  9423. type))
  9424. (defun org-get-buffer-for-internal-link (buffer)
  9425. "Return a buffer to be used for displaying the link target of internal links."
  9426. (cond
  9427. ((not org-display-internal-link-with-indirect-buffer)
  9428. buffer)
  9429. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9430. (message "Buffer is already a clone, not making another one")
  9431. ;; we also do not modify visibility in this case
  9432. buffer)
  9433. (t ; make a new indirect buffer for displaying the link
  9434. (let* ((bn (buffer-name buffer))
  9435. (ibn (concat bn "(Clone)"))
  9436. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9437. (with-current-buffer ib (org-overview))
  9438. ib))))
  9439. (defun org-do-occur (regexp &optional cleanup)
  9440. "Call the Emacs command `occur'.
  9441. If CLEANUP is non-nil, remove the printout of the regular expression
  9442. in the *Occur* buffer. This is useful if the regex is long and not useful
  9443. to read."
  9444. (occur regexp)
  9445. (when cleanup
  9446. (let ((cwin (selected-window)) win beg end)
  9447. (when (setq win (get-buffer-window "*Occur*"))
  9448. (select-window win))
  9449. (goto-char (point-min))
  9450. (when (re-search-forward "match[a-z]+" nil t)
  9451. (setq beg (match-end 0))
  9452. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9453. (setq end (1- (match-beginning 0)))))
  9454. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9455. (goto-char (point-min))
  9456. (select-window cwin))))
  9457. ;;; The Mark Ring
  9458. (defvar org-mark-ring nil
  9459. "Mark ring for positions before jumps in Org mode.")
  9460. (defvar org-mark-ring-last-goto nil
  9461. "Last position in the mark ring used to go back.")
  9462. ;; Fill and close the ring
  9463. (setq org-mark-ring nil)
  9464. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  9465. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  9466. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  9467. org-mark-ring)
  9468. (defun org-mark-ring-push (&optional pos buffer)
  9469. "Put the current position into the mark ring and rotate it.
  9470. Also push position into the Emacs mark ring. If optional
  9471. argument POS and BUFFER are not nil, mark this location instead."
  9472. (interactive)
  9473. (let ((pos (or pos (point)))
  9474. (buffer (or buffer (current-buffer))))
  9475. (with-current-buffer buffer
  9476. (org-with-point-at pos (push-mark nil t)))
  9477. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  9478. (move-marker (car org-mark-ring) pos buffer))
  9479. (message
  9480. (substitute-command-keys
  9481. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  9482. (defun org-mark-ring-goto (&optional n)
  9483. "Jump to the previous position in the mark ring.
  9484. With prefix arg N, jump back that many stored positions. When
  9485. called several times in succession, walk through the entire ring.
  9486. Org mode commands jumping to a different position in the current file,
  9487. or to another Org file, automatically push the old position onto the ring."
  9488. (interactive "p")
  9489. (let (p m)
  9490. (if (eq last-command this-command)
  9491. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  9492. (setq p org-mark-ring))
  9493. (setq org-mark-ring-last-goto p)
  9494. (setq m (car p))
  9495. (pop-to-buffer-same-window (marker-buffer m))
  9496. (goto-char m)
  9497. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  9498. (defun org-add-angle-brackets (s)
  9499. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  9500. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  9501. s)
  9502. ;;; Following specific links
  9503. (defvar org-agenda-buffer-tmp-name)
  9504. (defvar org-agenda-start-on-weekday)
  9505. (defun org-follow-timestamp-link ()
  9506. "Open an agenda view for the time-stamp date/range at point."
  9507. (cond
  9508. ((org-at-date-range-p t)
  9509. (let ((org-agenda-start-on-weekday)
  9510. (t1 (match-string 1))
  9511. (t2 (match-string 2)) tt1 tt2)
  9512. (setq tt1 (time-to-days (org-time-string-to-time t1))
  9513. tt2 (time-to-days (org-time-string-to-time t2)))
  9514. (let ((org-agenda-buffer-tmp-name
  9515. (format "*Org Agenda(a:%s)"
  9516. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  9517. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  9518. ((org-at-timestamp-p 'lax)
  9519. (let ((org-agenda-buffer-tmp-name
  9520. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  9521. (org-agenda-list nil (time-to-days (org-time-string-to-time
  9522. (substring (match-string 1) 0 10)))
  9523. 1)))
  9524. (t (error "This should not happen"))))
  9525. ;;; Following file links
  9526. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  9527. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  9528. (declare-function mailcap-mime-info
  9529. "mailcap" (string &optional request no-decode))
  9530. (defvar org-wait nil)
  9531. (defun org-open-file (path &optional in-emacs line search)
  9532. "Open the file at PATH.
  9533. First, this expands any special file name abbreviations. Then the
  9534. configuration variable `org-file-apps' is checked if it contains an
  9535. entry for this file type, and if yes, the corresponding command is launched.
  9536. If no application is found, Emacs simply visits the file.
  9537. With optional prefix argument IN-EMACS, Emacs will visit the file.
  9538. With a double \\[universal-argument] \\[universal-argument] \
  9539. prefix arg, Org tries to avoid opening in Emacs
  9540. and to use an external application to visit the file.
  9541. Optional LINE specifies a line to go to, optional SEARCH a string
  9542. to search for. If LINE or SEARCH is given, the file will be
  9543. opened in Emacs, unless an entry from org-file-apps that makes
  9544. use of groups in a regexp matches.
  9545. If you want to change the way frames are used when following a
  9546. link, please customize `org-link-frame-setup'.
  9547. If the file does not exist, an error is thrown."
  9548. (let* ((file (if (equal path "")
  9549. buffer-file-name
  9550. (substitute-in-file-name (expand-file-name path))))
  9551. (file-apps (append org-file-apps (org-default-apps)))
  9552. (apps (cl-remove-if
  9553. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9554. (apps-dlink (cl-remove-if-not
  9555. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9556. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  9557. (dirp (unless remp (file-directory-p file)))
  9558. (file (if (and dirp org-open-directory-means-index-dot-org)
  9559. (concat (file-name-as-directory file) "index.org")
  9560. file))
  9561. (a-m-a-p (assq 'auto-mode apps))
  9562. (dfile (downcase file))
  9563. ;; Reconstruct the original link from the PATH, LINE and
  9564. ;; SEARCH args.
  9565. (link (cond (line (concat file "::" (number-to-string line)))
  9566. (search (concat file "::" search))
  9567. (t file)))
  9568. (dlink (downcase link))
  9569. (ext
  9570. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  9571. (match-string 1 dfile)))
  9572. (save-position-maybe
  9573. (let ((old-buffer (current-buffer))
  9574. (old-pos (point))
  9575. (old-mode major-mode))
  9576. (lambda ()
  9577. (and (derived-mode-p 'org-mode)
  9578. (eq old-mode 'org-mode)
  9579. (or (not (eq old-buffer (current-buffer)))
  9580. (not (eq old-pos (point))))
  9581. (org-mark-ring-push old-pos old-buffer)))))
  9582. cmd link-match-data)
  9583. (cond
  9584. ((member in-emacs '((16) system))
  9585. (setq cmd (cdr (assq 'system apps))))
  9586. (in-emacs (setq cmd 'emacs))
  9587. (t
  9588. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  9589. (and dirp (cdr (assq 'directory apps)))
  9590. ;; First, try matching against apps-dlink if we
  9591. ;; get a match here, store the match data for
  9592. ;; later.
  9593. (let ((match (assoc-default dlink apps-dlink
  9594. 'string-match)))
  9595. (if match
  9596. (progn (setq link-match-data (match-data))
  9597. match)
  9598. (progn (setq in-emacs (or in-emacs line search))
  9599. nil))) ; if we have no match in apps-dlink,
  9600. ; always open the file in emacs if line or search
  9601. ; is given (for backwards compatibility)
  9602. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  9603. 'string-match)
  9604. (cdr (assoc ext apps))
  9605. (cdr (assq t apps))))))
  9606. (when (eq cmd 'system)
  9607. (setq cmd (cdr (assq 'system apps))))
  9608. (when (eq cmd 'default)
  9609. (setq cmd (cdr (assoc t apps))))
  9610. (when (eq cmd 'mailcap)
  9611. (require 'mailcap)
  9612. (mailcap-parse-mailcaps)
  9613. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  9614. (command (mailcap-mime-info mime-type)))
  9615. (if (stringp command)
  9616. (setq cmd command)
  9617. (setq cmd 'emacs))))
  9618. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  9619. (not (file-exists-p file))
  9620. (not org-open-non-existing-files))
  9621. (user-error "No such file: %s" file))
  9622. (cond
  9623. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  9624. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  9625. (while (string-match "['\"]%s['\"]" cmd)
  9626. (setq cmd (replace-match "%s" t t cmd)))
  9627. (setq cmd (replace-regexp-in-string
  9628. "%s"
  9629. (shell-quote-argument (convert-standard-filename file))
  9630. cmd
  9631. nil t))
  9632. ;; Replace "%1", "%2" etc. in command with group matches from regex
  9633. (save-match-data
  9634. (let ((match-index 1)
  9635. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  9636. (set-match-data link-match-data)
  9637. (while (<= match-index number-of-groups)
  9638. (let ((regex (concat "%" (number-to-string match-index)))
  9639. (replace-with (match-string match-index dlink)))
  9640. (while (string-match regex cmd)
  9641. (setq cmd (replace-match replace-with t t cmd))))
  9642. (setq match-index (+ match-index 1)))))
  9643. (save-window-excursion
  9644. (message "Running %s...done" cmd)
  9645. (start-process-shell-command cmd nil cmd)
  9646. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  9647. ((or (stringp cmd)
  9648. (eq cmd 'emacs))
  9649. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  9650. (widen)
  9651. (cond (line (org-goto-line line)
  9652. (when (derived-mode-p 'org-mode) (org-reveal)))
  9653. (search (condition-case err
  9654. (org-link-search search)
  9655. ;; Save position before error-ing out so user
  9656. ;; can easily move back to the original buffer.
  9657. (error (funcall save-position-maybe)
  9658. (error (nth 1 err)))))))
  9659. ((functionp cmd)
  9660. (save-match-data
  9661. (set-match-data link-match-data)
  9662. (condition-case nil
  9663. (funcall cmd file link)
  9664. ;; FIXME: Remove this check when most default installations
  9665. ;; of Emacs have at least Org 9.0.
  9666. ((debug wrong-number-of-arguments wrong-type-argument
  9667. invalid-function)
  9668. (user-error "Please see Org News for version 9.0 about \
  9669. `org-file-apps'--Lisp error: %S" cmd)))))
  9670. ((consp cmd)
  9671. ;; FIXME: Remove this check when most default installations of
  9672. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  9673. ;; fall back to `org-link-frame-setup' for an old usage of
  9674. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  9675. (user-error "Please see Org News for version 9.0 about \
  9676. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  9677. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  9678. (funcall save-position-maybe)))
  9679. (defun org-file-apps-entry-match-against-dlink-p (entry)
  9680. "This function returns non-nil if `entry' uses a regular
  9681. expression which should be matched against the whole link by
  9682. org-open-file.
  9683. It assumes that is the case when the entry uses a regular
  9684. expression which has at least one grouping construct and the
  9685. action is either a lisp form or a command string containing
  9686. `%1', i.e. using at least one subexpression match as a
  9687. parameter."
  9688. (let ((selector (car entry))
  9689. (action (cdr entry)))
  9690. (if (stringp selector)
  9691. (and (> (regexp-opt-depth selector) 0)
  9692. (or (and (stringp action)
  9693. (string-match "%[0-9]" action))
  9694. (consp action)))
  9695. nil)))
  9696. (defun org-default-apps ()
  9697. "Return the default applications for this operating system."
  9698. (cond
  9699. ((eq system-type 'darwin)
  9700. org-file-apps-defaults-macosx)
  9701. ((eq system-type 'windows-nt)
  9702. org-file-apps-defaults-windowsnt)
  9703. (t org-file-apps-defaults-gnu)))
  9704. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  9705. "Convert extensions to regular expressions in the cars of LIST.
  9706. Also, weed out any non-string entries, because the return value is used
  9707. only for regexp matching.
  9708. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  9709. point to the symbol `emacs', indicating that the file should
  9710. be opened in Emacs."
  9711. (append
  9712. (delq nil
  9713. (mapcar (lambda (x)
  9714. (unless (not (stringp (car x)))
  9715. (if (string-match "\\W" (car x))
  9716. x
  9717. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  9718. list))
  9719. (when add-auto-mode
  9720. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  9721. (defvar ange-ftp-name-format)
  9722. (defun org-file-remote-p (file)
  9723. "Test whether FILE specifies a location on a remote system.
  9724. Return non-nil if the location is indeed remote.
  9725. For example, the filename \"/user@host:/foo\" specifies a location
  9726. on the system \"/user@host:\"."
  9727. (cond ((fboundp 'file-remote-p)
  9728. (file-remote-p file))
  9729. ((fboundp 'tramp-handle-file-remote-p)
  9730. (tramp-handle-file-remote-p file))
  9731. ((and (boundp 'ange-ftp-name-format)
  9732. (string-match (car ange-ftp-name-format) file))
  9733. t)))
  9734. ;;;; Refiling
  9735. (defun org-get-org-file ()
  9736. "Read a filename, with default directory `org-directory'."
  9737. (let ((default (or org-default-notes-file remember-data-file)))
  9738. (read-file-name (format "File name [%s]: " default)
  9739. (file-name-as-directory org-directory)
  9740. default)))
  9741. (defun org-notes-order-reversed-p ()
  9742. "Check if the current file should receive notes in reversed order."
  9743. (cond
  9744. ((not org-reverse-note-order) nil)
  9745. ((eq t org-reverse-note-order) t)
  9746. ((not (listp org-reverse-note-order)) nil)
  9747. (t (catch 'exit
  9748. (dolist (entry org-reverse-note-order)
  9749. (when (string-match (car entry) buffer-file-name)
  9750. (throw 'exit (cdr entry))))))))
  9751. (defvar org-refile-target-table nil
  9752. "The list of refile targets, created by `org-refile'.")
  9753. (defvar org-agenda-new-buffers nil
  9754. "Buffers created to visit agenda files.")
  9755. (defvar org-refile-cache nil
  9756. "Cache for refile targets.")
  9757. (defvar org-refile-markers nil
  9758. "All the markers used for caching refile locations.")
  9759. (defun org-refile-marker (pos)
  9760. "Get a new refile marker, but only if caching is in use."
  9761. (if (not org-refile-use-cache)
  9762. pos
  9763. (let ((m (make-marker)))
  9764. (move-marker m pos)
  9765. (push m org-refile-markers)
  9766. m)))
  9767. (defun org-refile-cache-clear ()
  9768. "Clear the refile cache and disable all the markers."
  9769. (dolist (m org-refile-markers) (move-marker m nil))
  9770. (setq org-refile-markers nil)
  9771. (setq org-refile-cache nil)
  9772. (message "Refile cache has been cleared"))
  9773. (defun org-refile-cache-check-set (set)
  9774. "Check if all the markers in the cache still have live buffers."
  9775. (let (marker)
  9776. (catch 'exit
  9777. (while (and set (setq marker (nth 3 (pop set))))
  9778. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  9779. (when (and marker (null (marker-buffer marker)))
  9780. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  9781. (sit-for 3)
  9782. (throw 'exit nil)))
  9783. t)))
  9784. (defun org-refile-cache-put (set &rest identifiers)
  9785. "Push the refile targets SET into the cache, under IDENTIFIERS."
  9786. (let* ((key (sha1 (prin1-to-string identifiers)))
  9787. (entry (assoc key org-refile-cache)))
  9788. (if entry
  9789. (setcdr entry set)
  9790. (push (cons key set) org-refile-cache))))
  9791. (defun org-refile-cache-get (&rest identifiers)
  9792. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  9793. (cond
  9794. ((not org-refile-cache) nil)
  9795. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  9796. (t
  9797. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  9798. org-refile-cache))))
  9799. (and set (org-refile-cache-check-set set) set)))))
  9800. (defvar org-outline-path-cache nil
  9801. "Alist between buffer positions and outline paths.
  9802. It value is an alist (POSITION . PATH) where POSITION is the
  9803. buffer position at the beginning of an entry and PATH is a list
  9804. of strings describing the outline path for that entry, in reverse
  9805. order.")
  9806. (defun org-refile-get-targets (&optional default-buffer)
  9807. "Produce a table with refile targets."
  9808. (let ((case-fold-search nil)
  9809. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  9810. (entries (or org-refile-targets '((nil . (:level . 1)))))
  9811. targets tgs files desc descre)
  9812. (message "Getting targets...")
  9813. (with-current-buffer (or default-buffer (current-buffer))
  9814. (dolist (entry entries)
  9815. (setq files (car entry) desc (cdr entry))
  9816. (cond
  9817. ((null files) (setq files (list (current-buffer))))
  9818. ((eq files 'org-agenda-files)
  9819. (setq files (org-agenda-files 'unrestricted)))
  9820. ((and (symbolp files) (fboundp files))
  9821. (setq files (funcall files)))
  9822. ((and (symbolp files) (boundp files))
  9823. (setq files (symbol-value files))))
  9824. (when (stringp files) (setq files (list files)))
  9825. (cond
  9826. ((eq (car desc) :tag)
  9827. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  9828. ((eq (car desc) :todo)
  9829. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  9830. ((eq (car desc) :regexp)
  9831. (setq descre (cdr desc)))
  9832. ((eq (car desc) :level)
  9833. (setq descre (concat "^\\*\\{" (number-to-string
  9834. (if org-odd-levels-only
  9835. (1- (* 2 (cdr desc)))
  9836. (cdr desc)))
  9837. "\\}[ \t]")))
  9838. ((eq (car desc) :maxlevel)
  9839. (setq descre (concat "^\\*\\{1," (number-to-string
  9840. (if org-odd-levels-only
  9841. (1- (* 2 (cdr desc)))
  9842. (cdr desc)))
  9843. "\\}[ \t]")))
  9844. (t (error "Bad refiling target description %s" desc)))
  9845. (dolist (f files)
  9846. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  9847. (or
  9848. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  9849. (progn
  9850. (when (bufferp f)
  9851. (setq f (buffer-file-name (buffer-base-buffer f))))
  9852. (setq f (and f (expand-file-name f)))
  9853. (when (eq org-refile-use-outline-path 'file)
  9854. (push (list (file-name-nondirectory f) f nil nil) tgs))
  9855. (when (eq org-refile-use-outline-path 'buffer-name)
  9856. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  9857. (when (eq org-refile-use-outline-path 'full-file-path)
  9858. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  9859. (org-with-wide-buffer
  9860. (goto-char (point-min))
  9861. (setq org-outline-path-cache nil)
  9862. (while (re-search-forward descre nil t)
  9863. (beginning-of-line)
  9864. (let ((case-fold-search nil))
  9865. (looking-at org-complex-heading-regexp))
  9866. (let ((begin (point))
  9867. (heading (match-string-no-properties 4)))
  9868. (unless (or (and
  9869. org-refile-target-verify-function
  9870. (not
  9871. (funcall org-refile-target-verify-function)))
  9872. (not heading))
  9873. (let ((re (format org-complex-heading-regexp-format
  9874. (regexp-quote heading)))
  9875. (target
  9876. (if (not org-refile-use-outline-path) heading
  9877. (mapconcat
  9878. #'identity
  9879. (append
  9880. (pcase org-refile-use-outline-path
  9881. (`file (list (file-name-nondirectory
  9882. (buffer-file-name
  9883. (buffer-base-buffer)))))
  9884. (`full-file-path
  9885. (list (buffer-file-name
  9886. (buffer-base-buffer))))
  9887. (`buffer-name
  9888. (list (buffer-name
  9889. (buffer-base-buffer))))
  9890. (_ nil))
  9891. (mapcar (lambda (s) (replace-regexp-in-string
  9892. "/" "\\/" s nil t))
  9893. (org-get-outline-path t t)))
  9894. "/"))))
  9895. (push (list target f re (org-refile-marker (point)))
  9896. tgs)))
  9897. (when (= (point) begin)
  9898. ;; Verification function has not moved point.
  9899. (end-of-line)))))))
  9900. (when org-refile-use-cache
  9901. (org-refile-cache-put tgs (buffer-file-name) descre))
  9902. (setq targets (append tgs targets))))))
  9903. (message "Getting targets...done")
  9904. (delete-dups (nreverse targets))))
  9905. (defun org--get-outline-path-1 (&optional use-cache)
  9906. "Return outline path to current headline.
  9907. Outline path is a list of strings, in reverse order. When
  9908. optional argument USE-CACHE is non-nil, make use of a cache. See
  9909. `org-get-outline-path' for details.
  9910. Assume buffer is widened and point is on a headline."
  9911. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  9912. (let ((p (point))
  9913. (heading (let ((case-fold-search nil))
  9914. (looking-at org-complex-heading-regexp)
  9915. (if (not (match-end 4)) ""
  9916. ;; Remove statistics cookies.
  9917. (org-trim
  9918. (org-link-display-format
  9919. (replace-regexp-in-string
  9920. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  9921. (match-string-no-properties 4))))))))
  9922. (if (org-up-heading-safe)
  9923. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  9924. (when use-cache
  9925. (push (cons p path) org-outline-path-cache))
  9926. path)
  9927. ;; This is a new root node. Since we assume we are moving
  9928. ;; forward, we can drop previous cache so as to limit number
  9929. ;; of associations there.
  9930. (let ((path (list heading)))
  9931. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  9932. path)))))
  9933. (defun org-get-outline-path (&optional with-self use-cache)
  9934. "Return the outline path to the current entry.
  9935. An outline path is a list of ancestors for current headline, as
  9936. a list of strings. Statistics cookies are removed and links are
  9937. replaced with their description, if any, or their path otherwise.
  9938. When optional argument WITH-SELF is non-nil, the path also
  9939. includes the current headline.
  9940. When optional argument USE-CACHE is non-nil, cache outline paths
  9941. between calls to this function so as to avoid backtracking. This
  9942. argument is useful when planning to find more than one outline
  9943. path in the same document. In that case, there are two
  9944. conditions to satisfy:
  9945. - `org-outline-path-cache' is set to nil before starting the
  9946. process;
  9947. - outline paths are computed by increasing buffer positions."
  9948. (org-with-wide-buffer
  9949. (and (or (and with-self (org-back-to-heading t))
  9950. (org-up-heading-safe))
  9951. (reverse (org--get-outline-path-1 use-cache)))))
  9952. (defun org-format-outline-path (path &optional width prefix separator)
  9953. "Format the outline path PATH for display.
  9954. WIDTH is the maximum number of characters that is available.
  9955. PREFIX is a prefix to be included in the returned string,
  9956. such as the file name.
  9957. SEPARATOR is inserted between the different parts of the path,
  9958. the default is \"/\"."
  9959. (setq width (or width 79))
  9960. (setq path (delq nil path))
  9961. (unless (> width 0)
  9962. (user-error "Argument `width' must be positive"))
  9963. (setq separator (or separator "/"))
  9964. (let* ((org-odd-levels-only nil)
  9965. (fpath (concat
  9966. prefix (and prefix path separator)
  9967. (mapconcat
  9968. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  9969. (cl-loop for head in path
  9970. for n from 0
  9971. collect (org-add-props
  9972. head nil 'face
  9973. (nth (% n org-n-level-faces) org-level-faces)))
  9974. separator))))
  9975. (when (> (length fpath) width)
  9976. (if (< width 7)
  9977. ;; It's unlikely that `width' will be this small, but don't
  9978. ;; waste characters by adding ".." if it is.
  9979. (setq fpath (substring fpath 0 width))
  9980. (setf (substring fpath (- width 2)) "..")))
  9981. fpath))
  9982. (defun org-display-outline-path (&optional file current separator just-return-string)
  9983. "Display the current outline path in the echo area.
  9984. If FILE is non-nil, prepend the output with the file name.
  9985. If CURRENT is non-nil, append the current heading to the output.
  9986. SEPARATOR is passed through to `org-format-outline-path'. It separates
  9987. the different parts of the path and defaults to \"/\".
  9988. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  9989. (interactive "P")
  9990. (let* (case-fold-search
  9991. (bfn (buffer-file-name (buffer-base-buffer)))
  9992. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  9993. res)
  9994. (when current (setq path (append path
  9995. (save-excursion
  9996. (org-back-to-heading t)
  9997. (when (looking-at org-complex-heading-regexp)
  9998. (list (match-string 4)))))))
  9999. (setq res
  10000. (org-format-outline-path
  10001. path
  10002. (1- (frame-width))
  10003. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10004. separator))
  10005. (if just-return-string
  10006. (org-no-properties res)
  10007. (org-unlogged-message "%s" res))))
  10008. (defvar org-refile-history nil
  10009. "History for refiling operations.")
  10010. (defvar org-after-refile-insert-hook nil
  10011. "Hook run after `org-refile' has inserted its stuff at the new location.
  10012. Note that this is still *before* the stuff will be removed from
  10013. the *old* location.")
  10014. (defvar org-capture-last-stored-marker)
  10015. (defvar org-refile-keep nil
  10016. "Non-nil means `org-refile' will copy instead of refile.")
  10017. (defun org-copy ()
  10018. "Like `org-refile', but copy."
  10019. (interactive)
  10020. (let ((org-refile-keep t))
  10021. (funcall 'org-refile nil nil nil "Copy")))
  10022. (defun org-refile (&optional arg default-buffer rfloc msg)
  10023. "Move the entry or entries at point to another heading.
  10024. The list of target headings is compiled using the information in
  10025. `org-refile-targets', which see.
  10026. At the target location, the entry is filed as a subitem of the
  10027. target heading. Depending on `org-reverse-note-order', the new
  10028. subitem will either be the first or the last subitem.
  10029. If there is an active region, all entries in that region will be
  10030. refiled. However, the region must fulfill the requirement that
  10031. the first heading sets the top-level of the moved text.
  10032. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10033. location
  10034. and not actually move anything.
  10035. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10036. location where the last
  10037. refiling operation has put the subtree.
  10038. With a numeric prefix argument of `2', refile to the running clock.
  10039. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10040. being set to t and copy to the target location, don't move it.
  10041. Beware that keeping refiled entries may result in duplicated ID
  10042. properties.
  10043. RFLOC can be a refile location obtained in a different way.
  10044. MSG is a string to replace \"Refile\" in the default prompt with
  10045. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10046. See also `org-refile-use-outline-path'.
  10047. If you are using target caching (see `org-refile-use-cache'), you
  10048. have to clear the target cache in order to find new targets.
  10049. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10050. prefix argument (`C-u C-u C-u C-c C-w')."
  10051. (interactive "P")
  10052. (if (member arg '(0 (64)))
  10053. (org-refile-cache-clear)
  10054. (let* ((actionmsg (cond (msg msg)
  10055. ((equal arg 3) "Refile (and keep)")
  10056. (t "Refile")))
  10057. (regionp (org-region-active-p))
  10058. (region-start (and regionp (region-beginning)))
  10059. (region-end (and regionp (region-end)))
  10060. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10061. pos it nbuf file level reversed)
  10062. (setq last-command nil)
  10063. (when regionp
  10064. (goto-char region-start)
  10065. (or (bolp) (goto-char (point-at-bol)))
  10066. (setq region-start (point))
  10067. (unless (or (org-kill-is-subtree-p
  10068. (buffer-substring region-start region-end))
  10069. (prog1 org-refile-active-region-within-subtree
  10070. (let ((s (point-at-eol)))
  10071. (org-toggle-heading)
  10072. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10073. (user-error "The region is not a (sequence of) subtree(s)")))
  10074. (if (equal arg '(16))
  10075. (org-refile-goto-last-stored)
  10076. (when (or
  10077. (and (equal arg 2)
  10078. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10079. (prog1
  10080. (setq it (list (or org-clock-heading "running clock")
  10081. (buffer-file-name
  10082. (marker-buffer org-clock-hd-marker))
  10083. ""
  10084. (marker-position org-clock-hd-marker)))
  10085. (setq arg nil)))
  10086. (setq it
  10087. (or rfloc
  10088. (let (heading-text)
  10089. (save-excursion
  10090. (unless (and arg (listp arg))
  10091. (org-back-to-heading t)
  10092. (setq heading-text
  10093. (replace-regexp-in-string
  10094. org-bracket-link-regexp
  10095. "\\3"
  10096. (or (nth 4 (org-heading-components))
  10097. ""))))
  10098. (org-refile-get-location
  10099. (cond ((and arg (listp arg)) "Goto")
  10100. (regionp (concat actionmsg " region to"))
  10101. (t (concat actionmsg " subtree \""
  10102. heading-text "\" to")))
  10103. default-buffer
  10104. (and (not (equal '(4) arg))
  10105. org-refile-allow-creating-parent-nodes)))))))
  10106. (setq file (nth 1 it)
  10107. pos (nth 3 it))
  10108. (when (and (not arg)
  10109. pos
  10110. (equal (buffer-file-name) file)
  10111. (if regionp
  10112. (and (>= pos region-start)
  10113. (<= pos region-end))
  10114. (and (>= pos (point))
  10115. (< pos (save-excursion
  10116. (org-end-of-subtree t t))))))
  10117. (error "Cannot refile to position inside the tree or region"))
  10118. (setq nbuf (or (find-buffer-visiting file)
  10119. (find-file-noselect file)))
  10120. (if (and arg (not (equal arg 3)))
  10121. (progn
  10122. (pop-to-buffer-same-window nbuf)
  10123. (goto-char (cond (pos)
  10124. ((org-notes-order-reversed-p) (point-min))
  10125. (t (point-max))))
  10126. (org-show-context 'org-goto))
  10127. (if regionp
  10128. (progn
  10129. (org-kill-new (buffer-substring region-start region-end))
  10130. (org-save-markers-in-region region-start region-end))
  10131. (org-copy-subtree 1 nil t))
  10132. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10133. (find-file-noselect file)))
  10134. (setq reversed (org-notes-order-reversed-p))
  10135. (org-with-wide-buffer
  10136. (if pos
  10137. (progn
  10138. (goto-char pos)
  10139. (setq level (org-get-valid-level (funcall outline-level) 1))
  10140. (goto-char
  10141. (if reversed
  10142. (or (outline-next-heading) (point-max))
  10143. (or (save-excursion (org-get-next-sibling))
  10144. (org-end-of-subtree t t)
  10145. (point-max)))))
  10146. (setq level 1)
  10147. (if (not reversed)
  10148. (goto-char (point-max))
  10149. (goto-char (point-min))
  10150. (or (outline-next-heading) (goto-char (point-max)))))
  10151. (unless (bolp) (newline))
  10152. (org-paste-subtree level nil nil t)
  10153. (when org-log-refile
  10154. (org-add-log-setup 'refile nil nil org-log-refile)
  10155. (unless (eq org-log-refile 'note)
  10156. (save-excursion (org-add-log-note))))
  10157. (and org-auto-align-tags
  10158. (let ((org-loop-over-headlines-in-active-region nil))
  10159. (org-align-tags)))
  10160. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10161. :last-refile)))
  10162. (when bookmark-name
  10163. (with-demoted-errors
  10164. (bookmark-set bookmark-name))))
  10165. ;; If we are refiling for capture, make sure that the
  10166. ;; last-capture pointers point here
  10167. (when (bound-and-true-p org-capture-is-refiling)
  10168. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10169. :last-capture-marker)))
  10170. (when bookmark-name
  10171. (with-demoted-errors
  10172. (bookmark-set bookmark-name))))
  10173. (move-marker org-capture-last-stored-marker (point)))
  10174. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10175. (run-hooks 'org-after-refile-insert-hook)))
  10176. (unless org-refile-keep
  10177. (if regionp
  10178. (delete-region (point) (+ (point) (- region-end region-start)))
  10179. (org-preserve-local-variables
  10180. (delete-region
  10181. (and (org-back-to-heading t) (point))
  10182. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  10183. (when (featurep 'org-inlinetask)
  10184. (org-inlinetask-remove-END-maybe))
  10185. (setq org-markers-to-move nil)
  10186. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10187. (defun org-refile-goto-last-stored ()
  10188. "Go to the location where the last refile was stored."
  10189. (interactive)
  10190. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10191. (message "This is the location of the last refile"))
  10192. (defun org-refile--get-location (refloc tbl)
  10193. "When user refile to REFLOC, find the associated target in TBL.
  10194. Also check `org-refile-target-table'."
  10195. (car (delq
  10196. nil
  10197. (mapcar
  10198. (lambda (r) (or (assoc r tbl)
  10199. (assoc r org-refile-target-table)))
  10200. (list (replace-regexp-in-string "/$" "" refloc)
  10201. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10202. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10203. "Prompt the user for a refile location, using PROMPT.
  10204. PROMPT should not be suffixed with a colon and a space, because
  10205. this function appends the default value from
  10206. `org-refile-history' automatically, if that is not empty."
  10207. (let ((org-refile-targets org-refile-targets)
  10208. (org-refile-use-outline-path org-refile-use-outline-path))
  10209. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10210. (unless org-refile-target-table
  10211. (user-error "No refile targets"))
  10212. (let* ((cbuf (current-buffer))
  10213. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10214. (cfunc (if (and org-refile-use-outline-path
  10215. org-outline-path-complete-in-steps)
  10216. #'org-olpath-completing-read
  10217. #'completing-read))
  10218. (extra (if org-refile-use-outline-path "/" ""))
  10219. (cbnex (concat (buffer-name) extra))
  10220. (filename (and cfn (expand-file-name cfn)))
  10221. (tbl (mapcar
  10222. (lambda (x)
  10223. (if (and (not (member org-refile-use-outline-path
  10224. '(file full-file-path)))
  10225. (not (equal filename (nth 1 x))))
  10226. (cons (concat (car x) extra " ("
  10227. (file-name-nondirectory (nth 1 x)) ")")
  10228. (cdr x))
  10229. (cons (concat (car x) extra) (cdr x))))
  10230. org-refile-target-table))
  10231. (completion-ignore-case t)
  10232. cdef
  10233. (prompt (concat prompt
  10234. (or (and (car org-refile-history)
  10235. (concat " (default " (car org-refile-history) ")"))
  10236. (and (assoc cbnex tbl) (setq cdef cbnex)
  10237. (concat " (default " cbnex ")"))) ": "))
  10238. pa answ parent-target child parent old-hist)
  10239. (setq old-hist org-refile-history)
  10240. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10241. nil 'org-refile-history (or cdef (car org-refile-history))))
  10242. (if (setq pa (org-refile--get-location answ tbl))
  10243. (progn
  10244. (org-refile-check-position pa)
  10245. (when (or (not org-refile-history)
  10246. (not (eq old-hist org-refile-history))
  10247. (not (equal (car pa) (car org-refile-history))))
  10248. (setq org-refile-history
  10249. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10250. org-refile-history
  10251. (cdr org-refile-history))))
  10252. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10253. (pop org-refile-history)))
  10254. pa)
  10255. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10256. (progn
  10257. (setq parent (match-string 1 answ)
  10258. child (match-string 2 answ))
  10259. (setq parent-target (org-refile--get-location parent tbl))
  10260. (when (and parent-target
  10261. (or (eq new-nodes t)
  10262. (and (eq new-nodes 'confirm)
  10263. (y-or-n-p (format "Create new node \"%s\"? "
  10264. child)))))
  10265. (org-refile-new-child parent-target child)))
  10266. (user-error "Invalid target location")))))
  10267. (declare-function org-string-nw-p "org-macs" (s))
  10268. (defun org-refile-check-position (refile-pointer)
  10269. "Check if the refile pointer matches the headline to which it points."
  10270. (let* ((file (nth 1 refile-pointer))
  10271. (re (nth 2 refile-pointer))
  10272. (pos (nth 3 refile-pointer))
  10273. buffer)
  10274. (if (and (not (markerp pos)) (not file))
  10275. (user-error "Please indicate a target file in the refile path")
  10276. (when (org-string-nw-p re)
  10277. (setq buffer (if (markerp pos)
  10278. (marker-buffer pos)
  10279. (or (find-buffer-visiting file)
  10280. (find-file-noselect file))))
  10281. (with-current-buffer buffer
  10282. (org-with-wide-buffer
  10283. (goto-char pos)
  10284. (beginning-of-line 1)
  10285. (unless (looking-at-p re)
  10286. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10287. (defun org-refile-new-child (parent-target child)
  10288. "Use refile target PARENT-TARGET to add new CHILD below it."
  10289. (unless parent-target
  10290. (error "Cannot find parent for new node"))
  10291. (let ((file (nth 1 parent-target))
  10292. (pos (nth 3 parent-target))
  10293. level)
  10294. (with-current-buffer (or (find-buffer-visiting file)
  10295. (find-file-noselect file))
  10296. (org-with-wide-buffer
  10297. (if pos
  10298. (goto-char pos)
  10299. (goto-char (point-max))
  10300. (unless (bolp) (newline)))
  10301. (when (looking-at org-outline-regexp)
  10302. (setq level (funcall outline-level))
  10303. (org-end-of-subtree t t))
  10304. (org-back-over-empty-lines)
  10305. (insert "\n" (make-string
  10306. (if pos (org-get-valid-level level 1) 1) ?*)
  10307. " " child "\n")
  10308. (beginning-of-line 0)
  10309. (list (concat (car parent-target) "/" child) file "" (point))))))
  10310. (defun org-olpath-completing-read (prompt collection &rest args)
  10311. "Read an outline path like a file name."
  10312. (let ((thetable collection))
  10313. (apply #'completing-read
  10314. prompt
  10315. (lambda (string predicate &optional flag)
  10316. (cond
  10317. ((eq flag nil) (try-completion string thetable))
  10318. ((eq flag t)
  10319. (let ((l (length string)))
  10320. (mapcar (lambda (x)
  10321. (let ((r (substring x l))
  10322. (f (if (string-match " ([^)]*)$" x)
  10323. (match-string 0 x)
  10324. "")))
  10325. (if (string-match "/" r)
  10326. (concat string (substring r 0 (match-end 0)) f)
  10327. x)))
  10328. (all-completions string thetable predicate))))
  10329. ;; Exact match?
  10330. ((eq flag 'lambda) (assoc string thetable))))
  10331. args)))
  10332. ;;;; Dynamic blocks
  10333. (defun org-find-dblock (name)
  10334. "Find the first dynamic block with name NAME in the buffer.
  10335. If not found, stay at current position and return nil."
  10336. (let ((case-fold-search t) pos)
  10337. (save-excursion
  10338. (goto-char (point-min))
  10339. (setq pos (and (re-search-forward
  10340. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10341. (match-beginning 0))))
  10342. (when pos (goto-char pos))
  10343. pos))
  10344. (defun org-create-dblock (plist)
  10345. "Create a dynamic block section, with parameters taken from PLIST.
  10346. PLIST must contain a :name entry which is used as the name of the block."
  10347. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10348. (end-of-line 1)
  10349. (newline))
  10350. (let ((col (current-column))
  10351. (name (plist-get plist :name)))
  10352. (insert "#+BEGIN: " name)
  10353. (while plist
  10354. (if (eq (car plist) :name)
  10355. (setq plist (cddr plist))
  10356. (insert " " (prin1-to-string (pop plist)))))
  10357. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10358. (beginning-of-line -2)))
  10359. (defun org-prepare-dblock ()
  10360. "Prepare dynamic block for refresh.
  10361. This empties the block, puts the cursor at the insert position and returns
  10362. the property list including an extra property :name with the block name."
  10363. (unless (looking-at org-dblock-start-re)
  10364. (user-error "Not at a dynamic block"))
  10365. (let* ((begdel (1+ (match-end 0)))
  10366. (name (org-no-properties (match-string 1)))
  10367. (params (append (list :name name)
  10368. (read (concat "(" (match-string 3) ")")))))
  10369. (save-excursion
  10370. (beginning-of-line 1)
  10371. (skip-chars-forward " \t")
  10372. (setq params (plist-put params :indentation-column (current-column))))
  10373. (unless (re-search-forward org-dblock-end-re nil t)
  10374. (error "Dynamic block not terminated"))
  10375. (setq params
  10376. (append params
  10377. (list :content (buffer-substring
  10378. begdel (match-beginning 0)))))
  10379. (delete-region begdel (match-beginning 0))
  10380. (goto-char begdel)
  10381. (open-line 1)
  10382. params))
  10383. (defun org-map-dblocks (&optional command)
  10384. "Apply COMMAND to all dynamic blocks in the current buffer.
  10385. If COMMAND is not given, use `org-update-dblock'."
  10386. (let ((cmd (or command 'org-update-dblock)))
  10387. (save-excursion
  10388. (goto-char (point-min))
  10389. (while (re-search-forward org-dblock-start-re nil t)
  10390. (goto-char (match-beginning 0))
  10391. (save-excursion
  10392. (condition-case nil
  10393. (funcall cmd)
  10394. (error (message "Error during update of dynamic block"))))
  10395. (unless (re-search-forward org-dblock-end-re nil t)
  10396. (error "Dynamic block not terminated"))))))
  10397. (defun org-dblock-update (&optional arg)
  10398. "User command for updating dynamic blocks.
  10399. Update the dynamic block at point. With prefix ARG, update all dynamic
  10400. blocks in the buffer."
  10401. (interactive "P")
  10402. (if arg
  10403. (org-update-all-dblocks)
  10404. (or (looking-at org-dblock-start-re)
  10405. (org-beginning-of-dblock))
  10406. (org-update-dblock)))
  10407. (defun org-update-dblock ()
  10408. "Update the dynamic block at point.
  10409. This means to empty the block, parse for parameters and then call
  10410. the correct writing function."
  10411. (interactive)
  10412. (save-excursion
  10413. (let* ((win (selected-window))
  10414. (pos (point))
  10415. (line (org-current-line))
  10416. (params (org-prepare-dblock))
  10417. (name (plist-get params :name))
  10418. (indent (plist-get params :indentation-column))
  10419. (cmd (intern (concat "org-dblock-write:" name))))
  10420. (message "Updating dynamic block `%s' at line %d..." name line)
  10421. (funcall cmd params)
  10422. (message "Updating dynamic block `%s' at line %d...done" name line)
  10423. (goto-char pos)
  10424. (when (and indent (> indent 0))
  10425. (setq indent (make-string indent ?\ ))
  10426. (save-excursion
  10427. (select-window win)
  10428. (org-beginning-of-dblock)
  10429. (forward-line 1)
  10430. (while (not (looking-at org-dblock-end-re))
  10431. (insert indent)
  10432. (beginning-of-line 2))
  10433. (when (looking-at org-dblock-end-re)
  10434. (and (looking-at "[ \t]+")
  10435. (replace-match ""))
  10436. (insert indent)))))))
  10437. (defun org-beginning-of-dblock ()
  10438. "Find the beginning of the dynamic block at point.
  10439. Error if there is no such block at point."
  10440. (let ((pos (point))
  10441. beg)
  10442. (end-of-line 1)
  10443. (if (and (re-search-backward org-dblock-start-re nil t)
  10444. (setq beg (match-beginning 0))
  10445. (re-search-forward org-dblock-end-re nil t)
  10446. (> (match-end 0) pos))
  10447. (goto-char beg)
  10448. (goto-char pos)
  10449. (error "Not in a dynamic block"))))
  10450. (defun org-update-all-dblocks ()
  10451. "Update all dynamic blocks in the buffer.
  10452. This function can be used in a hook."
  10453. (interactive)
  10454. (when (derived-mode-p 'org-mode)
  10455. (org-map-dblocks 'org-update-dblock)))
  10456. ;;;; Completion
  10457. (declare-function org-export-backend-options "ox" (cl-x) t)
  10458. (defun org-get-export-keywords ()
  10459. "Return a list of all currently understood export keywords.
  10460. Export keywords include options, block names, attributes and
  10461. keywords relative to each registered export back-end."
  10462. (let (keywords)
  10463. (dolist (backend
  10464. (bound-and-true-p org-export-registered-backends)
  10465. (delq nil keywords))
  10466. ;; Back-end name (for keywords, like #+LATEX:)
  10467. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10468. (dolist (option-entry (org-export-backend-options backend))
  10469. ;; Back-end options.
  10470. (push (nth 1 option-entry) keywords)))))
  10471. (defconst org-options-keywords
  10472. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10473. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10474. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10475. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10476. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10477. (defcustom org-structure-template-alist
  10478. '(("a" . "export ascii")
  10479. ("c" . "center")
  10480. ("C" . "comment")
  10481. ("e" . "example")
  10482. ("E" . "export")
  10483. ("h" . "export html")
  10484. ("l" . "export latex")
  10485. ("q" . "quote")
  10486. ("s" . "src")
  10487. ("v" . "verse"))
  10488. "Structure completion elements.
  10489. This is an alist of keys and block types. With
  10490. `org-insert-structure-template' a block can be inserted through a
  10491. menu. The block type is inserted, with \"#+BEGIN_\" and
  10492. \"#+END_\" added automatically. The menukeys are determined
  10493. based on the key elements in the `org-structure-template-alist'.
  10494. If two entries have the keys \"a\" and \"aa\" respectively, the
  10495. former will be inserted by typing \"a TAB/RET/SPC\" and the
  10496. latter will be inserted by typing \"aa\". If an entry with the
  10497. key \"aab\" is later added it would be inserted by typing \"ab\".
  10498. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  10499. block can be inserted by pressing TAB after the string \"<KEY\".
  10500. "
  10501. :group 'org-edit-structure
  10502. :type '(repeat
  10503. (cons (string :tag "Key")
  10504. (string :tag "Template")))
  10505. :package-version '(Org . "9.2"))
  10506. (defun org--insert-structure-template-mks ()
  10507. "Present `org-structure-template-alist' with `org-mks'.
  10508. Menus are added if keys require more than one keystroke.
  10509. Tabs are added to single key entires when needing more than one stroke.
  10510. Keys longer than two characters are reduced to two characters."
  10511. (let* (case-fold-search
  10512. (templates (append org-structure-template-alist
  10513. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  10514. (keys (mapcar #'car templates))
  10515. (start-letters (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  10516. ;; Sort each element of `org-structure-template-alist' into
  10517. ;; sublists according to the first letter.
  10518. (superlist (mapcar (lambda (letter)
  10519. (list letter
  10520. (cl-remove-if-not
  10521. (apply-partially #'string-match-p (concat "^" letter))
  10522. templates :key #'car)))
  10523. start-letters)))
  10524. (org-mks
  10525. (apply #'append
  10526. ;; Make an `org-mks' table. If only one element is
  10527. ;; present in a sublist, make it part of the top-menu,
  10528. ;; otherwise make a submenu according to the starting
  10529. ;; letter and populate it.
  10530. (mapcar (lambda (sublist)
  10531. (if (eq 1 (length (cadr sublist)))
  10532. (mapcar (lambda (elm)
  10533. (list (substring (car elm) 0 1)
  10534. (cdr elm) ""))
  10535. (cadr sublist))
  10536. ;; Create submenu.
  10537. (let* ((topkey (car sublist))
  10538. (elms (cadr sublist))
  10539. (keys (mapcar #'car elms))
  10540. (long (> (length elms) 3)))
  10541. (append
  10542. (list
  10543. ;; Make a description of the submenu.
  10544. (list topkey
  10545. (concat
  10546. (mapconcat #'cdr
  10547. (cl-subseq elms 0 (if long 3 (length elms)))
  10548. ", ")
  10549. (when long ", ..."))))
  10550. ;; List of entries in submenu.
  10551. (cl-mapcar #'list
  10552. (org--insert-structure-template-unique-keys keys)
  10553. (mapcar #'cdr elms)
  10554. (make-list (length elms) ""))))))
  10555. superlist))
  10556. "Select a key\n============"
  10557. "Key: ")))
  10558. (defun org--insert-structure-template-unique-keys (keys)
  10559. "Make list of unique, two character long elements from KEYS.
  10560. Elements of length one have a tab appended. Elements of length
  10561. two are kept as is. Longer elements are truncated to length two.
  10562. If an element cannot be made unique an error is raised."
  10563. (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  10564. menu-keys)
  10565. (dolist (key orderd-keys)
  10566. (let ((potential-key
  10567. (cl-case (length key)
  10568. (1 (concat key "\t"))
  10569. (2 key)
  10570. (otherwise
  10571. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  10572. (mapcar (apply-partially #'concat (substring key 0 1))
  10573. (split-string (substring key 1) "" t)))))))
  10574. (if (or (not potential-key) (assoc potential-key menu-keys))
  10575. (user-error "Could not make unique key for %s." key)
  10576. (push (cons potential-key key) menu-keys))))
  10577. (mapcar #'car
  10578. (cl-sort menu-keys #'<
  10579. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  10580. (defun org-insert-structure-template (type)
  10581. "Insert a block structure of the type #+begin_foo/#+end_foo.
  10582. First choose a block based on `org-structure-template-alist'.
  10583. Alternatively, type RET, TAB or SPC to write the block type.
  10584. With an active region, wrap the region in the block. Otherwise,
  10585. insert an empty block."
  10586. (interactive
  10587. (list (pcase (org--insert-structure-template-mks)
  10588. (`("\t" . ,_) (read-string "Structure type: "))
  10589. (`(,_ ,choice . ,_) choice))))
  10590. (let* ((region? (use-region-p))
  10591. (col (current-indentation))
  10592. (indent (make-string col ?\s))
  10593. (special? (string-match-p "\\(src\\|export\\)\\'" type))
  10594. (region-string (and region?
  10595. (buffer-substring (region-beginning)
  10596. (region-end))))
  10597. (region-end-blank (and region?
  10598. (save-excursion
  10599. (goto-char (region-end))
  10600. (when (looking-at "[ \t]*$")
  10601. (replace-match "")
  10602. t))))
  10603. s)
  10604. (when region? (delete-region (region-beginning) (region-end)))
  10605. (unless (save-excursion (skip-chars-backward "[ \t]") (bolp))
  10606. (insert "\n"))
  10607. (beginning-of-line)
  10608. (save-excursion
  10609. (insert
  10610. (with-temp-buffer
  10611. (when region?
  10612. (insert region-string "\n")
  10613. (when (string-match-p
  10614. (concat "\\`" (regexp-opt '("example" "export" "src")))
  10615. type)
  10616. (org-escape-code-in-region (point-min) (point-max))))
  10617. (goto-char (point-min))
  10618. ;; Delete trailing white-lines.
  10619. (when region?
  10620. (while (looking-at-p "^[ \t]*$")
  10621. (delete-region (line-beginning-position)
  10622. (line-beginning-position 2))))
  10623. (save-excursion
  10624. (while (not (eobp))
  10625. (unless (looking-at-p indent)
  10626. (insert indent))
  10627. (forward-line)))
  10628. (insert
  10629. indent
  10630. (format "#+begin_%s%s\n" type (if special? " " "")))
  10631. (unless region? (indent-to col))
  10632. (setq s (point))
  10633. (goto-char (point-max))
  10634. (skip-chars-backward "[ \t\n]" s)
  10635. (delete-region (line-end-position) (point-max))
  10636. (insert "\n" indent
  10637. (format "#+end_%s" (car (split-string type)))
  10638. (if region-end-blank "" "\n"))
  10639. (buffer-substring (point-min) (point))))
  10640. (when (and (eobp) (not (bolp))) (insert "\n")))
  10641. (cond (special?
  10642. (end-of-line))
  10643. (t
  10644. (forward-line)
  10645. (skip-chars-forward "[ \t]*")))))
  10646. ;;;; TODO, DEADLINE, Comments
  10647. (defun org-toggle-comment ()
  10648. "Change the COMMENT state of an entry."
  10649. (interactive)
  10650. (save-excursion
  10651. (org-back-to-heading)
  10652. (let ((case-fold-search nil))
  10653. (looking-at org-complex-heading-regexp))
  10654. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  10655. (skip-chars-forward " \t")
  10656. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  10657. (if (org-in-commented-heading-p t)
  10658. (delete-region (point)
  10659. (progn (search-forward " " (line-end-position) 'move)
  10660. (skip-chars-forward " \t")
  10661. (point)))
  10662. (insert org-comment-string)
  10663. (unless (eolp) (insert " ")))))
  10664. (defvar org-last-todo-state-is-todo nil
  10665. "This is non-nil when the last TODO state change led to a TODO state.
  10666. If the last change removed the TODO tag or switched to DONE, then
  10667. this is nil.")
  10668. (defvar org-todo-setup-filter-hook nil
  10669. "Hook for functions that pre-filter todo specs.
  10670. Each function takes a todo spec and returns either nil or the spec
  10671. transformed into canonical form." )
  10672. (defvar org-todo-get-default-hook nil
  10673. "Hook for functions that get a default item for todo.
  10674. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  10675. nil or a string to be used for the todo mark." )
  10676. (defvar org-agenda-headline-snapshot-before-repeat)
  10677. (defun org-current-effective-time ()
  10678. "Return current time adjusted for `org-extend-today-until' variable."
  10679. (let* ((ct (org-current-time))
  10680. (dct (decode-time ct))
  10681. (ct1
  10682. (cond
  10683. (org-use-last-clock-out-time-as-effective-time
  10684. (or (org-clock-get-last-clock-out-time) ct))
  10685. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  10686. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  10687. (t ct))))
  10688. ct1))
  10689. (defun org-todo-yesterday (&optional arg)
  10690. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  10691. (interactive "P")
  10692. (if (eq major-mode 'org-agenda-mode)
  10693. (apply 'org-agenda-todo-yesterday arg)
  10694. (let* ((org-use-effective-time t)
  10695. (hour (nth 2 (decode-time (org-current-time))))
  10696. (org-extend-today-until (1+ hour)))
  10697. (org-todo arg))))
  10698. (defvar org-block-entry-blocking ""
  10699. "First entry preventing the TODO state change.")
  10700. (defun org-cancel-repeater ()
  10701. "Cancel a repeater by setting its numeric value to zero."
  10702. (interactive)
  10703. (save-excursion
  10704. (org-back-to-heading t)
  10705. (let ((bound1 (point))
  10706. (bound0 (save-excursion (outline-next-heading) (point))))
  10707. (when (and (re-search-forward
  10708. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  10709. org-deadline-time-regexp "\\)\\|\\("
  10710. org-ts-regexp "\\)")
  10711. bound0 t)
  10712. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  10713. bound1 t))
  10714. (replace-match "0" t nil nil 1)))))
  10715. (defvar org-state)
  10716. (defvar org-blocked-by-checkboxes)
  10717. (defun org-todo (&optional arg)
  10718. "Change the TODO state of an item.
  10719. The state of an item is given by a keyword at the start of the heading,
  10720. like
  10721. *** TODO Write paper
  10722. *** DONE Call mom
  10723. The different keywords are specified in the variable `org-todo-keywords'.
  10724. By default the available states are \"TODO\" and \"DONE\". So, for this
  10725. example: when the item starts with TODO, it is changed to DONE.
  10726. When it starts with DONE, the DONE is removed. And when neither TODO nor
  10727. DONE are present, add TODO at the beginning of the heading.
  10728. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  10729. state.
  10730. With numeric prefix ARG, switch to that state.
  10731. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  10732. next set of TODO \
  10733. keywords (nextset).
  10734. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  10735. prefix, circumvent any state blocking.
  10736. With a numeric prefix arg of 0, inhibit note taking for the change.
  10737. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  10738. When called through ELisp, arg is also interpreted in the following way:
  10739. `none' -> empty state
  10740. \"\" -> switch to empty state
  10741. `done' -> switch to DONE
  10742. `nextset' -> switch to the next set of keywords
  10743. `previousset' -> switch to the previous set of keywords
  10744. \"WAITING\" -> switch to the specified keyword, but only if it
  10745. really is a member of `org-todo-keywords'."
  10746. (interactive "P")
  10747. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10748. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10749. 'region-start-level 'region))
  10750. org-loop-over-headlines-in-active-region)
  10751. (org-map-entries
  10752. `(org-todo ,arg)
  10753. org-loop-over-headlines-in-active-region
  10754. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  10755. (when (equal arg '(16)) (setq arg 'nextset))
  10756. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  10757. (let ((org-blocker-hook org-blocker-hook)
  10758. commentp
  10759. case-fold-search)
  10760. (when (equal arg '(64))
  10761. (setq arg nil org-blocker-hook nil))
  10762. (when (and org-blocker-hook
  10763. (or org-inhibit-blocking
  10764. (org-entry-get nil "NOBLOCKING")))
  10765. (setq org-blocker-hook nil))
  10766. (save-excursion
  10767. (catch 'exit
  10768. (org-back-to-heading t)
  10769. (when (org-in-commented-heading-p t)
  10770. (org-toggle-comment)
  10771. (setq commentp t))
  10772. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  10773. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  10774. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  10775. (let* ((match-data (match-data))
  10776. (startpos (copy-marker (line-beginning-position)))
  10777. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  10778. (org-log-done org-log-done)
  10779. (org-log-repeat org-log-repeat)
  10780. (org-todo-log-states org-todo-log-states)
  10781. (org-inhibit-logging
  10782. (if (equal arg 0)
  10783. (progn (setq arg nil) 'note) org-inhibit-logging))
  10784. (this (match-string 1))
  10785. (hl-pos (match-beginning 0))
  10786. (head (org-get-todo-sequence-head this))
  10787. (ass (assoc head org-todo-kwd-alist))
  10788. (interpret (nth 1 ass))
  10789. (done-word (nth 3 ass))
  10790. (final-done-word (nth 4 ass))
  10791. (org-last-state (or this ""))
  10792. (completion-ignore-case t)
  10793. (member (member this org-todo-keywords-1))
  10794. (tail (cdr member))
  10795. (org-state (cond
  10796. ((and org-todo-key-trigger
  10797. (or (and (equal arg '(4))
  10798. (eq org-use-fast-todo-selection 'prefix))
  10799. (and (not arg) org-use-fast-todo-selection
  10800. (not (eq org-use-fast-todo-selection
  10801. 'prefix)))))
  10802. ;; Use fast selection.
  10803. (org-fast-todo-selection))
  10804. ((and (equal arg '(4))
  10805. (or (not org-use-fast-todo-selection)
  10806. (not org-todo-key-trigger)))
  10807. ;; Read a state with completion.
  10808. (completing-read
  10809. "State: " (mapcar #'list org-todo-keywords-1)
  10810. nil t))
  10811. ((eq arg 'right)
  10812. (if this
  10813. (if tail (car tail) nil)
  10814. (car org-todo-keywords-1)))
  10815. ((eq arg 'left)
  10816. (unless (equal member org-todo-keywords-1)
  10817. (if this
  10818. (nth (- (length org-todo-keywords-1)
  10819. (length tail) 2)
  10820. org-todo-keywords-1)
  10821. (org-last org-todo-keywords-1))))
  10822. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  10823. (setq arg nil))) ;hack to fall back to cycling
  10824. (arg
  10825. ;; User or caller requests a specific state.
  10826. (cond
  10827. ((equal arg "") nil)
  10828. ((eq arg 'none) nil)
  10829. ((eq arg 'done) (or done-word (car org-done-keywords)))
  10830. ((eq arg 'nextset)
  10831. (or (car (cdr (member head org-todo-heads)))
  10832. (car org-todo-heads)))
  10833. ((eq arg 'previousset)
  10834. (let ((org-todo-heads (reverse org-todo-heads)))
  10835. (or (car (cdr (member head org-todo-heads)))
  10836. (car org-todo-heads))))
  10837. ((car (member arg org-todo-keywords-1)))
  10838. ((stringp arg)
  10839. (user-error "State `%s' not valid in this file" arg))
  10840. ((nth (1- (prefix-numeric-value arg))
  10841. org-todo-keywords-1))))
  10842. ((null member) (or head (car org-todo-keywords-1)))
  10843. ((equal this final-done-word) nil) ;-> make empty
  10844. ((null tail) nil) ;-> first entry
  10845. ((memq interpret '(type priority))
  10846. (if (eq this-command last-command)
  10847. (car tail)
  10848. (if (> (length tail) 0)
  10849. (or done-word (car org-done-keywords))
  10850. nil)))
  10851. (t
  10852. (car tail))))
  10853. (org-state (or
  10854. (run-hook-with-args-until-success
  10855. 'org-todo-get-default-hook org-state org-last-state)
  10856. org-state))
  10857. (next (if org-state (concat " " org-state " ") " "))
  10858. (change-plist (list :type 'todo-state-change :from this :to org-state
  10859. :position startpos))
  10860. dolog now-done-p)
  10861. (when org-blocker-hook
  10862. (let (org-blocked-by-checkboxes block-reason)
  10863. (setq org-last-todo-state-is-todo
  10864. (not (member this org-done-keywords)))
  10865. (unless (save-excursion
  10866. (save-match-data
  10867. (org-with-wide-buffer
  10868. (run-hook-with-args-until-failure
  10869. 'org-blocker-hook change-plist))))
  10870. (setq block-reason (if org-blocked-by-checkboxes
  10871. "contained checkboxes"
  10872. (format "\"%s\"" org-block-entry-blocking)))
  10873. (if (called-interactively-p 'interactive)
  10874. (user-error "TODO state change from %s to %s blocked (by %s)"
  10875. this org-state block-reason)
  10876. ;; Fail silently.
  10877. (message "TODO state change from %s to %s blocked (by %s)"
  10878. this org-state block-reason)
  10879. (throw 'exit nil)))))
  10880. (store-match-data match-data)
  10881. (replace-match next t t)
  10882. (cond ((equal this org-state)
  10883. (message "TODO state was already %s" (org-trim next)))
  10884. ((not (pos-visible-in-window-p hl-pos))
  10885. (message "TODO state changed to %s" (org-trim next))))
  10886. (unless head
  10887. (setq head (org-get-todo-sequence-head org-state)
  10888. ass (assoc head org-todo-kwd-alist)
  10889. interpret (nth 1 ass)
  10890. done-word (nth 3 ass)
  10891. final-done-word (nth 4 ass)))
  10892. (when (memq arg '(nextset previousset))
  10893. (message "Keyword-Set %d/%d: %s"
  10894. (- (length org-todo-sets) -1
  10895. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  10896. (length org-todo-sets)
  10897. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  10898. (setq org-last-todo-state-is-todo
  10899. (not (member org-state org-done-keywords)))
  10900. (setq now-done-p (and (member org-state org-done-keywords)
  10901. (not (member this org-done-keywords))))
  10902. (and logging (org-local-logging logging))
  10903. (when (and (or org-todo-log-states org-log-done)
  10904. (not (eq org-inhibit-logging t))
  10905. (not (memq arg '(nextset previousset))))
  10906. ;; We need to look at recording a time and note.
  10907. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  10908. (nth 2 (assoc this org-todo-log-states))))
  10909. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  10910. (setq dolog 'time))
  10911. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  10912. (and org-state
  10913. (member org-state org-not-done-keywords)
  10914. (not (member this org-not-done-keywords))))
  10915. ;; This is now a todo state and was not one before
  10916. ;; If there was a CLOSED time stamp, get rid of it.
  10917. (org-add-planning-info nil nil 'closed))
  10918. (when (and now-done-p org-log-done)
  10919. ;; It is now done, and it was not done before.
  10920. (org-add-planning-info 'closed (org-current-effective-time))
  10921. (when (and (not dolog) (eq 'note org-log-done))
  10922. (org-add-log-setup 'done org-state this 'note)))
  10923. (when (and org-state dolog)
  10924. ;; This is a non-nil state, and we need to log it.
  10925. (org-add-log-setup 'state org-state this dolog)))
  10926. ;; Fixup tag positioning.
  10927. (org-todo-trigger-tag-changes org-state)
  10928. (when org-auto-align-tags (org-align-tags))
  10929. (when org-provide-todo-statistics
  10930. (org-update-parent-todo-statistics))
  10931. (run-hooks 'org-after-todo-state-change-hook)
  10932. (when (and arg (not (member org-state org-done-keywords)))
  10933. (setq head (org-get-todo-sequence-head org-state)))
  10934. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  10935. ;; Do we need to trigger a repeat?
  10936. (when now-done-p
  10937. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  10938. ;; This is for the agenda, take a snapshot of the headline.
  10939. (save-match-data
  10940. (setq org-agenda-headline-snapshot-before-repeat
  10941. (org-get-heading))))
  10942. (org-auto-repeat-maybe org-state))
  10943. ;; Fixup cursor location if close to the keyword.
  10944. (when (and (outline-on-heading-p)
  10945. (not (bolp))
  10946. (save-excursion (beginning-of-line 1)
  10947. (looking-at org-todo-line-regexp))
  10948. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  10949. (goto-char (or (match-end 2) (match-end 1)))
  10950. (and (looking-at " ") (just-one-space)))
  10951. (when org-trigger-hook
  10952. (save-excursion
  10953. (run-hook-with-args 'org-trigger-hook change-plist)))
  10954. (when commentp (org-toggle-comment))))))))
  10955. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  10956. "Block turning an entry into a TODO, using the hierarchy.
  10957. This checks whether the current task should be blocked from state
  10958. changes. Such blocking occurs when:
  10959. 1. The task has children which are not all in a completed state.
  10960. 2. A task has a parent with the property :ORDERED:, and there
  10961. are siblings prior to the current task with incomplete
  10962. status.
  10963. 3. The parent of the task is blocked because it has siblings that should
  10964. be done first, or is child of a block grandparent TODO entry."
  10965. (if (not org-enforce-todo-dependencies)
  10966. t ; if locally turned off don't block
  10967. (catch 'dont-block
  10968. ;; If this is not a todo state change, or if this entry is already DONE,
  10969. ;; do not block
  10970. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  10971. (member (plist-get change-plist :from)
  10972. (cons 'done org-done-keywords))
  10973. (member (plist-get change-plist :to)
  10974. (cons 'todo org-not-done-keywords))
  10975. (not (plist-get change-plist :to)))
  10976. (throw 'dont-block t))
  10977. ;; If this task has children, and any are undone, it's blocked
  10978. (save-excursion
  10979. (org-back-to-heading t)
  10980. (let ((this-level (funcall outline-level)))
  10981. (outline-next-heading)
  10982. (let ((child-level (funcall outline-level)))
  10983. (while (and (not (eobp))
  10984. (> child-level this-level))
  10985. ;; this todo has children, check whether they are all
  10986. ;; completed
  10987. (when (and (not (org-entry-is-done-p))
  10988. (org-entry-is-todo-p))
  10989. (setq org-block-entry-blocking (org-get-heading))
  10990. (throw 'dont-block nil))
  10991. (outline-next-heading)
  10992. (setq child-level (funcall outline-level))))))
  10993. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  10994. ;; any previous siblings are undone, it's blocked
  10995. (save-excursion
  10996. (org-back-to-heading t)
  10997. (let* ((pos (point))
  10998. (parent-pos (and (org-up-heading-safe) (point)))
  10999. (case-fold-search nil))
  11000. (unless parent-pos (throw 'dont-block t)) ; no parent
  11001. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11002. (forward-line 1)
  11003. (re-search-forward org-not-done-heading-regexp pos t))
  11004. (setq org-block-entry-blocking (match-string 0))
  11005. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11006. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11007. (while t
  11008. (goto-char parent-pos)
  11009. (unless (looking-at org-not-done-heading-regexp)
  11010. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11011. (setq pos (point))
  11012. (setq parent-pos (and (org-up-heading-safe) (point)))
  11013. (unless parent-pos (throw 'dont-block t)) ; no parent
  11014. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11015. (forward-line 1)
  11016. (re-search-forward org-not-done-heading-regexp pos t)
  11017. (setq org-block-entry-blocking (org-get-heading)))
  11018. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11019. (defcustom org-track-ordered-property-with-tag nil
  11020. "Should the ORDERED property also be shown as a tag?
  11021. The ORDERED property decides if an entry should require subtasks to be
  11022. completed in sequence. Since a property is not very visible, setting
  11023. this option means that toggling the ORDERED property with the command
  11024. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11025. not relevant for the behavior, but it makes things more visible.
  11026. Note that toggling the tag with tags commands will not change the property
  11027. and therefore not influence behavior!
  11028. This can be t, meaning the tag ORDERED should be used, It can also be a
  11029. string to select a different tag for this task."
  11030. :group 'org-todo
  11031. :type '(choice
  11032. (const :tag "No tracking" nil)
  11033. (const :tag "Track with ORDERED tag" t)
  11034. (string :tag "Use other tag")))
  11035. (defun org-toggle-ordered-property ()
  11036. "Toggle the ORDERED property of the current entry.
  11037. For better visibility, you can track the value of this property with a tag.
  11038. See variable `org-track-ordered-property-with-tag'."
  11039. (interactive)
  11040. (let* ((t1 org-track-ordered-property-with-tag)
  11041. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11042. (save-excursion
  11043. (org-back-to-heading)
  11044. (if (org-entry-get nil "ORDERED")
  11045. (progn
  11046. (org-delete-property "ORDERED")
  11047. (and tag (org-toggle-tag tag 'off))
  11048. (message "Subtasks can be completed in arbitrary order"))
  11049. (org-entry-put nil "ORDERED" "t")
  11050. (and tag (org-toggle-tag tag 'on))
  11051. (message "Subtasks must be completed in sequence")))))
  11052. (defun org-block-todo-from-checkboxes (change-plist)
  11053. "Block turning an entry into a TODO, using checkboxes.
  11054. This checks whether the current task should be blocked from state
  11055. changes because there are unchecked boxes in this entry."
  11056. (if (not org-enforce-todo-checkbox-dependencies)
  11057. t ; if locally turned off don't block
  11058. (catch 'dont-block
  11059. ;; If this is not a todo state change, or if this entry is already DONE,
  11060. ;; do not block
  11061. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11062. (member (plist-get change-plist :from)
  11063. (cons 'done org-done-keywords))
  11064. (member (plist-get change-plist :to)
  11065. (cons 'todo org-not-done-keywords))
  11066. (not (plist-get change-plist :to)))
  11067. (throw 'dont-block t))
  11068. ;; If this task has checkboxes that are not checked, it's blocked
  11069. (save-excursion
  11070. (org-back-to-heading t)
  11071. (let ((beg (point)) end)
  11072. (outline-next-heading)
  11073. (setq end (point))
  11074. (goto-char beg)
  11075. (when (org-list-search-forward
  11076. (concat (org-item-beginning-re)
  11077. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11078. "\\[[- ]\\]")
  11079. end t)
  11080. (when (boundp 'org-blocked-by-checkboxes)
  11081. (setq org-blocked-by-checkboxes t))
  11082. (throw 'dont-block nil))))
  11083. t))) ; do not block
  11084. (defun org-entry-blocked-p ()
  11085. "Non-nil if entry at point is blocked."
  11086. (and (not (org-entry-get nil "NOBLOCKING"))
  11087. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11088. (not (run-hook-with-args-until-failure
  11089. 'org-blocker-hook
  11090. (list :type 'todo-state-change
  11091. :position (point)
  11092. :from 'todo
  11093. :to 'done)))))
  11094. (defun org-update-statistics-cookies (all)
  11095. "Update the statistics cookie, either from TODO or from checkboxes.
  11096. This should be called with the cursor in a line with a statistics
  11097. cookie. When called with a \\[universal-argument] prefix, update
  11098. all statistics cookies in the buffer."
  11099. (interactive "P")
  11100. (if all
  11101. (progn
  11102. (org-update-checkbox-count 'all)
  11103. (org-map-entries 'org-update-parent-todo-statistics))
  11104. (if (not (org-at-heading-p))
  11105. (org-update-checkbox-count)
  11106. (let ((pos (point-marker))
  11107. end l1 l2)
  11108. (ignore-errors (org-back-to-heading t))
  11109. (if (not (org-at-heading-p))
  11110. (org-update-checkbox-count)
  11111. (setq l1 (org-outline-level))
  11112. (setq end (save-excursion
  11113. (outline-next-heading)
  11114. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11115. (point)))
  11116. (if (and (save-excursion
  11117. (re-search-forward
  11118. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11119. (not (save-excursion (re-search-forward
  11120. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11121. (org-update-checkbox-count)
  11122. (if (and l2 (> l2 l1))
  11123. (progn
  11124. (goto-char end)
  11125. (org-update-parent-todo-statistics))
  11126. (goto-char pos)
  11127. (beginning-of-line 1)
  11128. (while (re-search-forward
  11129. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11130. (point-at-eol) t)
  11131. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11132. (goto-char pos)
  11133. (move-marker pos nil)))))
  11134. (defvar org-entry-property-inherited-from) ;; defined below
  11135. (defun org-update-parent-todo-statistics ()
  11136. "Update any statistics cookie in the parent of the current headline.
  11137. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11138. the entire subtree and this will travel up the hierarchy and update
  11139. statistics everywhere."
  11140. (let* ((prop (save-excursion (org-up-heading-safe)
  11141. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11142. (recursive (or (not org-hierarchical-todo-statistics)
  11143. (and prop (string-match "\\<recursive\\>" prop))))
  11144. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11145. 0))
  11146. (first t)
  11147. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11148. level ltoggle l1 new ndel
  11149. (cnt-all 0) (cnt-done 0) is-percent kwd
  11150. checkbox-beg cookie-present)
  11151. (catch 'exit
  11152. (save-excursion
  11153. (beginning-of-line 1)
  11154. (setq ltoggle (funcall outline-level))
  11155. ;; Three situations are to consider:
  11156. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11157. ;; to the top-level ancestor on the headline;
  11158. ;; 2. If parent has "recursive" property, repeat up to the
  11159. ;; headline setting that property, taking inheritance into
  11160. ;; account;
  11161. ;; 3. Else, move up to direct parent and proceed only once.
  11162. (while (and (setq level (org-up-heading-safe))
  11163. (or recursive first)
  11164. (>= (point) lim))
  11165. (setq first nil cookie-present nil)
  11166. (unless (and level
  11167. (not (string-match
  11168. "\\<checkbox\\>"
  11169. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11170. "")))))
  11171. (throw 'exit nil))
  11172. (while (re-search-forward box-re (point-at-eol) t)
  11173. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11174. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11175. (save-match-data
  11176. (unless (outline-next-heading) (throw 'exit nil))
  11177. (while (and (looking-at org-complex-heading-regexp)
  11178. (> (setq l1 (length (match-string 1))) level))
  11179. (setq kwd (and (or recursive (= l1 ltoggle))
  11180. (match-string 2)))
  11181. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11182. (and (eq org-provide-todo-statistics t)
  11183. (or (member kwd org-done-keywords)))
  11184. (and (listp org-provide-todo-statistics)
  11185. (stringp (car org-provide-todo-statistics))
  11186. (or (member kwd org-provide-todo-statistics)
  11187. (member kwd org-done-keywords)))
  11188. (and (listp org-provide-todo-statistics)
  11189. (listp (car org-provide-todo-statistics))
  11190. (or (member kwd (car org-provide-todo-statistics))
  11191. (and (member kwd org-done-keywords)
  11192. (member kwd (cadr org-provide-todo-statistics))))))
  11193. (setq cnt-all (1+ cnt-all))
  11194. (and (eq org-provide-todo-statistics t)
  11195. kwd
  11196. (setq cnt-all (1+ cnt-all))))
  11197. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11198. (member kwd org-done-keywords))
  11199. (and (listp org-provide-todo-statistics)
  11200. (listp (car org-provide-todo-statistics))
  11201. (member kwd org-done-keywords)
  11202. (member kwd (cadr org-provide-todo-statistics)))
  11203. (and (listp org-provide-todo-statistics)
  11204. (stringp (car org-provide-todo-statistics))
  11205. (member kwd org-done-keywords)))
  11206. (setq cnt-done (1+ cnt-done)))
  11207. (outline-next-heading)))
  11208. (setq new
  11209. (if is-percent
  11210. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11211. (max 1 cnt-all)))
  11212. (format "[%d/%d]" cnt-done cnt-all))
  11213. ndel (- (match-end 0) checkbox-beg))
  11214. (goto-char checkbox-beg)
  11215. (insert new)
  11216. (delete-region (point) (+ (point) ndel))
  11217. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11218. (when cookie-present
  11219. (run-hook-with-args 'org-after-todo-statistics-hook
  11220. cnt-done (- cnt-all cnt-done))))))
  11221. (run-hooks 'org-todo-statistics-hook)))
  11222. (defvar org-after-todo-statistics-hook nil
  11223. "Hook that is called after a TODO statistics cookie has been updated.
  11224. Each function is called with two arguments: the number of not-done entries
  11225. and the number of done entries.
  11226. For example, the following function, when added to this hook, will switch
  11227. an entry to DONE when all children are done, and back to TODO when new
  11228. entries are set to a TODO status. Note that this hook is only called
  11229. when there is a statistics cookie in the headline!
  11230. (defun org-summary-todo (n-done n-not-done)
  11231. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11232. (let (org-log-done org-log-states) ; turn off logging
  11233. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11234. ")
  11235. (defvar org-todo-statistics-hook nil
  11236. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11237. This hook runs even if there is no statistics cookie present, in which case
  11238. `org-after-todo-statistics-hook' would not run.")
  11239. (defun org-todo-trigger-tag-changes (state)
  11240. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11241. (let ((l org-todo-state-tags-triggers)
  11242. changes)
  11243. (when (or (not state) (equal state ""))
  11244. (setq changes (append changes (cdr (assoc "" l)))))
  11245. (when (and (stringp state) (> (length state) 0))
  11246. (setq changes (append changes (cdr (assoc state l)))))
  11247. (when (member state org-not-done-keywords)
  11248. (setq changes (append changes (cdr (assq 'todo l)))))
  11249. (when (member state org-done-keywords)
  11250. (setq changes (append changes (cdr (assq 'done l)))))
  11251. (dolist (c changes)
  11252. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11253. (defun org-local-logging (value)
  11254. "Get logging settings from a property VALUE."
  11255. ;; Directly set the variables, they are already local.
  11256. (setq org-log-done nil
  11257. org-log-repeat nil
  11258. org-todo-log-states nil)
  11259. (dolist (w (split-string value))
  11260. (let (a)
  11261. (cond
  11262. ((setq a (assoc w org-startup-options))
  11263. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11264. (set (nth 1 a) (nth 2 a))))
  11265. ((setq a (org-extract-log-state-settings w))
  11266. (and (member (car a) org-todo-keywords-1)
  11267. (push a org-todo-log-states)))))))
  11268. (defun org-get-todo-sequence-head (kwd)
  11269. "Return the head of the TODO sequence to which KWD belongs.
  11270. If KWD is not set, check if there is a text property remembering the
  11271. right sequence."
  11272. (let (p)
  11273. (cond
  11274. ((not kwd)
  11275. (or (get-text-property (point-at-bol) 'org-todo-head)
  11276. (progn
  11277. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11278. nil (point-at-eol)))
  11279. (get-text-property p 'org-todo-head))))
  11280. ((not (member kwd org-todo-keywords-1))
  11281. (car org-todo-keywords-1))
  11282. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11283. (defun org-fast-todo-selection ()
  11284. "Fast TODO keyword selection with single keys.
  11285. Returns the new TODO keyword, or nil if no state change should occur."
  11286. (let* ((fulltable org-todo-key-alist)
  11287. (done-keywords org-done-keywords) ;; needed for the faces.
  11288. (maxlen (apply 'max (mapcar
  11289. (lambda (x)
  11290. (if (stringp (car x)) (string-width (car x)) 0))
  11291. fulltable)))
  11292. (expert nil)
  11293. (fwidth (+ maxlen 3 1 3))
  11294. (ncol (/ (- (window-width) 4) fwidth))
  11295. tg cnt e c tbl
  11296. groups ingroup)
  11297. (save-excursion
  11298. (save-window-excursion
  11299. (if expert
  11300. (set-buffer (get-buffer-create " *Org todo*"))
  11301. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11302. (erase-buffer)
  11303. (setq-local org-done-keywords done-keywords)
  11304. (setq tbl fulltable cnt 0)
  11305. (while (setq e (pop tbl))
  11306. (cond
  11307. ((equal e '(:startgroup))
  11308. (push '() groups) (setq ingroup t)
  11309. (unless (= cnt 0)
  11310. (setq cnt 0)
  11311. (insert "\n"))
  11312. (insert "{ "))
  11313. ((equal e '(:endgroup))
  11314. (setq ingroup nil cnt 0)
  11315. (insert "}\n"))
  11316. ((equal e '(:newline))
  11317. (unless (= cnt 0)
  11318. (setq cnt 0)
  11319. (insert "\n")
  11320. (setq e (car tbl))
  11321. (while (equal (car tbl) '(:newline))
  11322. (insert "\n")
  11323. (setq tbl (cdr tbl)))))
  11324. (t
  11325. (setq tg (car e) c (cdr e))
  11326. (when ingroup (push tg (car groups)))
  11327. (setq tg (org-add-props tg nil 'face
  11328. (org-get-todo-face tg)))
  11329. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11330. (insert "[" c "] " tg (make-string
  11331. (- fwidth 4 (length tg)) ?\ ))
  11332. (when (= (setq cnt (1+ cnt)) ncol)
  11333. (insert "\n")
  11334. (when ingroup (insert " "))
  11335. (setq cnt 0)))))
  11336. (insert "\n")
  11337. (goto-char (point-min))
  11338. (unless expert (org-fit-window-to-buffer))
  11339. (message "[a-z..]:Set [SPC]:clear")
  11340. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11341. (cond
  11342. ((or (= c ?\C-g)
  11343. (and (= c ?q) (not (rassoc c fulltable))))
  11344. (setq quit-flag t))
  11345. ((= c ?\ ) nil)
  11346. ((setq e (rassoc c fulltable) tg (car e))
  11347. tg)
  11348. (t (setq quit-flag t)))))))
  11349. (defun org-entry-is-todo-p ()
  11350. (member (org-get-todo-state) org-not-done-keywords))
  11351. (defun org-entry-is-done-p ()
  11352. (member (org-get-todo-state) org-done-keywords))
  11353. (defun org-get-todo-state ()
  11354. "Return the TODO keyword of the current subtree."
  11355. (save-excursion
  11356. (org-back-to-heading t)
  11357. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11358. (match-end 2)
  11359. (match-string 2))))
  11360. (defun org-at-date-range-p (&optional inactive-ok)
  11361. "Non-nil if point is inside a date range.
  11362. When optional argument INACTIVE-OK is non-nil, also consider
  11363. inactive time ranges.
  11364. When this function returns a non-nil value, match data is set
  11365. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11366. on INACTIVE-OK."
  11367. (interactive)
  11368. (save-excursion
  11369. (catch 'exit
  11370. (let ((pos (point)))
  11371. (skip-chars-backward "^[<\r\n")
  11372. (skip-chars-backward "<[")
  11373. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11374. (>= (match-end 0) pos)
  11375. (throw 'exit t))
  11376. (skip-chars-backward "^<[\r\n")
  11377. (skip-chars-backward "<[")
  11378. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11379. (>= (match-end 0) pos)
  11380. (throw 'exit t)))
  11381. nil)))
  11382. (defun org-get-repeat (&optional timestamp)
  11383. "Check if there is a time-stamp with repeater in this entry.
  11384. Return the repeater, as a string, or nil. Also return nil when
  11385. this function is called before first heading.
  11386. When optional argument TIMESTAMP is a string, extract the
  11387. repeater from there instead."
  11388. (save-match-data
  11389. (cond (timestamp
  11390. (and (string-match org-repeat-re timestamp)
  11391. (match-string-no-properties 1 timestamp)))
  11392. ((org-before-first-heading-p) nil)
  11393. (t
  11394. (save-excursion
  11395. (org-back-to-heading t)
  11396. (let ((end (org-entry-end-position)))
  11397. (catch :repeat
  11398. (while (re-search-forward org-repeat-re end t)
  11399. (when (save-match-data (org-at-timestamp-p 'agenda))
  11400. (throw :repeat (match-string-no-properties 1)))))))))))
  11401. (defvar org-last-changed-timestamp)
  11402. (defvar org-last-inserted-timestamp)
  11403. (defvar org-log-post-message)
  11404. (defvar org-log-note-purpose)
  11405. (defvar org-log-note-how nil)
  11406. (defvar org-log-note-extra)
  11407. (defun org-auto-repeat-maybe (done-word)
  11408. "Check if the current headline contains a repeated time-stamp.
  11409. If yes, set TODO state back to what it was and change the base date
  11410. of repeating deadline/scheduled time stamps to new date.
  11411. This function is run automatically after each state change to a DONE state."
  11412. (let* ((repeat (org-get-repeat))
  11413. (aa (assoc org-last-state org-todo-kwd-alist))
  11414. (interpret (nth 1 aa))
  11415. (head (nth 2 aa))
  11416. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11417. (msg "Entry repeats: ")
  11418. (org-log-done nil)
  11419. (org-todo-log-states nil)
  11420. (end (copy-marker (org-entry-end-position))))
  11421. (unwind-protect
  11422. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11423. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11424. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11425. (and (stringp org-todo-repeat-to-state)
  11426. org-todo-repeat-to-state)
  11427. (and org-todo-repeat-to-state org-last-state))))
  11428. (org-todo (cond
  11429. ((and to-state (member to-state org-todo-keywords-1))
  11430. to-state)
  11431. ((eq interpret 'type) org-last-state)
  11432. (head)
  11433. (t 'none))))
  11434. (org-back-to-heading t)
  11435. (org-add-planning-info nil nil 'closed)
  11436. ;; When `org-log-repeat' is non-nil or entry contains
  11437. ;; a clock, set LAST_REPEAT property.
  11438. (when (or org-log-repeat
  11439. (catch :clock
  11440. (save-excursion
  11441. (while (re-search-forward org-clock-line-re end t)
  11442. (when (org-at-clock-log-p) (throw :clock t))))))
  11443. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11444. (org-time-stamp-format t t)
  11445. (current-time))))
  11446. (when org-log-repeat
  11447. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11448. (memq 'org-add-log-note post-command-hook))
  11449. ;; We are already setup for some record.
  11450. (when (eq org-log-repeat 'note)
  11451. ;; Make sure we take a note, not only a time stamp.
  11452. (setq org-log-note-how 'note))
  11453. ;; Set up for taking a record.
  11454. (org-add-log-setup 'state
  11455. (or done-word (car org-done-keywords))
  11456. org-last-state
  11457. org-log-repeat)))
  11458. (let ((planning-re (regexp-opt
  11459. (list org-scheduled-string org-deadline-string))))
  11460. (while (re-search-forward org-ts-regexp end t)
  11461. (let* ((ts (match-string 0))
  11462. (planning? (org-at-planning-p))
  11463. (type (if (not planning?) "Plain:"
  11464. (save-excursion
  11465. (re-search-backward
  11466. planning-re (line-beginning-position) t)
  11467. (match-string 0)))))
  11468. (cond
  11469. ;; Ignore fake time-stamps (e.g., within comments).
  11470. ((not (org-at-timestamp-p 'agenda)))
  11471. ;; Time-stamps without a repeater are usually
  11472. ;; skipped. However, a SCHEDULED time-stamp without
  11473. ;; one is removed, as they are no longer relevant.
  11474. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11475. ts))
  11476. (when (equal type org-scheduled-string)
  11477. (org-remove-timestamp-with-keyword type)))
  11478. (t
  11479. (let ((n (string-to-number (match-string 2 ts)))
  11480. (what (match-string 3 ts)))
  11481. (when (equal what "w") (setq n (* n 7) what "d"))
  11482. (when (and (equal what "h")
  11483. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11484. ts)))
  11485. (user-error
  11486. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11487. has been set"
  11488. n))
  11489. ;; Preparation, see if we need to modify the start
  11490. ;; date for the change.
  11491. (when (match-end 1)
  11492. (let ((time (save-match-data
  11493. (org-time-string-to-time ts))))
  11494. (cond
  11495. ((equal (match-string 1 ts) ".")
  11496. ;; Shift starting date to today
  11497. (org-timestamp-change
  11498. (- (org-today) (time-to-days time))
  11499. 'day))
  11500. ((equal (match-string 1 ts) "+")
  11501. (let ((nshiftmax 10)
  11502. (nshift 0))
  11503. (while (or (= nshift 0)
  11504. (not (time-less-p (current-time) time)))
  11505. (when (= (cl-incf nshift) nshiftmax)
  11506. (or (y-or-n-p
  11507. (format "%d repeater intervals were not \
  11508. enough to shift date past today. Continue? "
  11509. nshift))
  11510. (user-error "Abort")))
  11511. (org-timestamp-change n (cdr (assoc what whata)))
  11512. (org-in-regexp org-ts-regexp3)
  11513. (setq ts (match-string 1))
  11514. (setq time
  11515. (save-match-data
  11516. (org-time-string-to-time ts)))))
  11517. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11518. ;; Rematch, so that we have everything in place
  11519. ;; for the real shift.
  11520. (org-in-regexp org-ts-regexp3)
  11521. (setq ts (match-string 1))
  11522. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11523. ts)))))
  11524. (save-excursion
  11525. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11526. (setq msg
  11527. (concat
  11528. msg type " " org-last-changed-timestamp " "))))))))
  11529. (setq org-log-post-message msg)
  11530. (message "%s" msg))
  11531. (set-marker end nil))))
  11532. (defun org-show-todo-tree (arg)
  11533. "Make a compact tree which shows all headlines marked with TODO.
  11534. The tree will show the lines where the regexp matches, and all higher
  11535. headlines above the match.
  11536. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11537. With a numeric prefix N, construct a sparse tree for the Nth element
  11538. of `org-todo-keywords-1'."
  11539. (interactive "P")
  11540. (let ((case-fold-search nil)
  11541. (kwd-re
  11542. (cond ((null arg) org-not-done-regexp)
  11543. ((equal arg '(4))
  11544. (let ((kwd
  11545. (completing-read "Keyword (or KWD1|KWD2|...): "
  11546. (mapcar #'list org-todo-keywords-1))))
  11547. (concat "\\("
  11548. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11549. "\\)\\>")))
  11550. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11551. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11552. org-todo-keywords-1)))
  11553. (t (user-error "Invalid prefix argument: %s" arg)))))
  11554. (message "%d TODO entries found"
  11555. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11556. (defun org--deadline-or-schedule (arg type time)
  11557. "Insert DEADLINE or SCHEDULE information in current entry.
  11558. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11559. `org-schedule' for information about ARG and TIME arguments."
  11560. (let* ((deadline? (eq type 'deadline))
  11561. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11562. (log (if deadline? org-log-redeadline org-log-reschedule))
  11563. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11564. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11565. ;; Save repeater cookie from either TIME or current scheduled
  11566. ;; time stamp. We are going to insert it back at the end of
  11567. ;; the process.
  11568. (repeater (or (and (org-string-nw-p time)
  11569. ;; We use `org-repeat-re' because we need
  11570. ;; to tell the difference between a real
  11571. ;; repeater and a time delta, e.g. "+2d".
  11572. (string-match org-repeat-re time)
  11573. (match-string 1 time))
  11574. (and (org-string-nw-p old-date)
  11575. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11576. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11577. old-date)
  11578. (match-string 1 old-date)))))
  11579. (pcase arg
  11580. (`(4)
  11581. (when (and old-date log)
  11582. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11583. nil old-date log))
  11584. (org-remove-timestamp-with-keyword keyword)
  11585. (message (if deadline? "Item no longer has a deadline."
  11586. "Item is no longer scheduled.")))
  11587. (`(16)
  11588. (save-excursion
  11589. (org-back-to-heading t)
  11590. (let ((regexp (if deadline? org-deadline-time-regexp
  11591. org-scheduled-time-regexp)))
  11592. (if (not (re-search-forward regexp (line-end-position 2) t))
  11593. (user-error (if deadline? "No deadline information to update"
  11594. "No scheduled information to update"))
  11595. (let* ((rpl0 (match-string 1))
  11596. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  11597. (msg (if deadline? "Warn starting from" "Delay until")))
  11598. (replace-match
  11599. (concat keyword
  11600. " <" rpl
  11601. (format " -%dd"
  11602. (abs (- (time-to-days
  11603. (save-match-data
  11604. (org-read-date
  11605. nil t nil msg old-date-time)))
  11606. (time-to-days old-date-time))))
  11607. ">") t t))))))
  11608. (_
  11609. (org-add-planning-info type time 'closed)
  11610. (when (and old-date
  11611. log
  11612. (not (equal old-date org-last-inserted-timestamp)))
  11613. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  11614. org-last-inserted-timestamp
  11615. old-date
  11616. log))
  11617. (when repeater
  11618. (save-excursion
  11619. (org-back-to-heading t)
  11620. (when (re-search-forward
  11621. (concat keyword " " org-last-inserted-timestamp)
  11622. (line-end-position 2)
  11623. t)
  11624. (goto-char (1- (match-end 0)))
  11625. (insert " " repeater)
  11626. (setq org-last-inserted-timestamp
  11627. (concat (substring org-last-inserted-timestamp 0 -1)
  11628. " " repeater
  11629. (substring org-last-inserted-timestamp -1))))))
  11630. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  11631. org-last-inserted-timestamp)))))
  11632. (defun org-deadline (arg &optional time)
  11633. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  11634. With one universal prefix argument, remove any deadline from the item.
  11635. With two universal prefix arguments, prompt for a warning delay.
  11636. With argument TIME, set the deadline at the corresponding date. TIME
  11637. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11638. (interactive "P")
  11639. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11640. (org-map-entries
  11641. (lambda () (org--deadline-or-schedule arg 'deadline time))
  11642. nil
  11643. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11644. 'region-start-level
  11645. 'region)
  11646. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11647. (org--deadline-or-schedule arg 'deadline time)))
  11648. (defun org-schedule (arg &optional time)
  11649. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  11650. With one universal prefix argument, remove any scheduling date from the item.
  11651. With two universal prefix arguments, prompt for a delay cookie.
  11652. With argument TIME, scheduled at the corresponding date. TIME can
  11653. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11654. (interactive "P")
  11655. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11656. (org-map-entries
  11657. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  11658. nil
  11659. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11660. 'region-start-level
  11661. 'region)
  11662. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11663. (org--deadline-or-schedule arg 'scheduled time)))
  11664. (defun org-get-scheduled-time (pom &optional inherit)
  11665. "Get the scheduled time as a time tuple, of a format suitable
  11666. for calling org-schedule with, or if there is no scheduling,
  11667. returns nil."
  11668. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  11669. (when time
  11670. (apply 'encode-time (org-parse-time-string time)))))
  11671. (defun org-get-deadline-time (pom &optional inherit)
  11672. "Get the deadline as a time tuple, of a format suitable for
  11673. calling org-deadline with, or if there is no scheduling, returns
  11674. nil."
  11675. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  11676. (when time
  11677. (apply 'encode-time (org-parse-time-string time)))))
  11678. (defun org-remove-timestamp-with-keyword (keyword)
  11679. "Remove all time stamps with KEYWORD in the current entry."
  11680. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  11681. beg)
  11682. (save-excursion
  11683. (org-back-to-heading t)
  11684. (setq beg (point))
  11685. (outline-next-heading)
  11686. (while (re-search-backward re beg t)
  11687. (replace-match "")
  11688. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  11689. (equal (char-before) ?\ ))
  11690. (backward-delete-char 1)
  11691. (when (string-match "^[ \t]*$" (buffer-substring
  11692. (point-at-bol) (point-at-eol)))
  11693. (delete-region (point-at-bol)
  11694. (min (point-max) (1+ (point-at-eol))))))))))
  11695. (defvar org-time-was-given) ; dynamically scoped parameter
  11696. (defvar org-end-time-was-given) ; dynamically scoped parameter
  11697. (defun org-at-planning-p ()
  11698. "Non-nil when point is on a planning info line."
  11699. ;; This is as accurate and faster than `org-element-at-point' since
  11700. ;; planning info location is fixed in the section.
  11701. (org-with-wide-buffer
  11702. (beginning-of-line)
  11703. (and (looking-at-p org-planning-line-re)
  11704. (eq (point)
  11705. (ignore-errors
  11706. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  11707. (org-back-to-heading t)
  11708. (org-with-limited-levels (org-back-to-heading t)))
  11709. (line-beginning-position 2))))))
  11710. (defun org-add-planning-info (what &optional time &rest remove)
  11711. "Insert new timestamp with keyword in the planning line.
  11712. WHAT indicates what kind of time stamp to add. It is a symbol
  11713. among `closed', `deadline', `scheduled' and nil. TIME indicates
  11714. the time to use. If none is given, the user is prompted for
  11715. a date. REMOVE indicates what kind of entries to remove. An old
  11716. WHAT entry will also be removed."
  11717. (let (org-time-was-given org-end-time-was-given default-time default-input)
  11718. (catch 'exit
  11719. (when (and (memq what '(scheduled deadline))
  11720. (or (not time)
  11721. (and (stringp time)
  11722. (string-match "^[-+]+[0-9]" time))))
  11723. ;; Try to get a default date/time from existing timestamp
  11724. (save-excursion
  11725. (org-back-to-heading t)
  11726. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  11727. (when (re-search-forward (if (eq what 'scheduled)
  11728. org-scheduled-time-regexp
  11729. org-deadline-time-regexp)
  11730. end t)
  11731. (setq ts (match-string 1)
  11732. default-time (apply 'encode-time (org-parse-time-string ts))
  11733. default-input (and ts (org-get-compact-tod ts)))))))
  11734. (when what
  11735. (setq time
  11736. (if (stringp time)
  11737. ;; This is a string (relative or absolute), set
  11738. ;; proper date.
  11739. (apply #'encode-time
  11740. (org-read-date-analyze
  11741. time default-time (decode-time default-time)))
  11742. ;; If necessary, get the time from the user
  11743. (or time (org-read-date nil 'to-time nil nil
  11744. default-time default-input)))))
  11745. (org-with-wide-buffer
  11746. (org-back-to-heading t)
  11747. (forward-line)
  11748. (unless (bolp) (insert "\n"))
  11749. (cond ((looking-at-p org-planning-line-re)
  11750. ;; Move to current indentation.
  11751. (skip-chars-forward " \t")
  11752. ;; Check if we have to remove something.
  11753. (dolist (type (if what (cons what remove) remove))
  11754. (save-excursion
  11755. (when (re-search-forward
  11756. (cl-case type
  11757. (closed org-closed-time-regexp)
  11758. (deadline org-deadline-time-regexp)
  11759. (scheduled org-scheduled-time-regexp)
  11760. (otherwise
  11761. (error "Invalid planning type: %s" type)))
  11762. (line-end-position) t)
  11763. ;; Delete until next keyword or end of line.
  11764. (delete-region
  11765. (match-beginning 0)
  11766. (if (re-search-forward org-keyword-time-not-clock-regexp
  11767. (line-end-position)
  11768. t)
  11769. (match-beginning 0)
  11770. (line-end-position))))))
  11771. ;; If there is nothing more to add and no more keyword
  11772. ;; is left, remove the line completely.
  11773. (if (and (looking-at-p "[ \t]*$") (not what))
  11774. (delete-region (line-beginning-position)
  11775. (line-beginning-position 2))
  11776. ;; If we removed last keyword, do not leave trailing
  11777. ;; white space at the end of line.
  11778. (let ((p (point)))
  11779. (save-excursion
  11780. (end-of-line)
  11781. (unless (= (skip-chars-backward " \t" p) 0)
  11782. (delete-region (point) (line-end-position)))))))
  11783. ((not what) (throw 'exit nil)) ; Nothing to do.
  11784. (t (insert-before-markers "\n")
  11785. (backward-char 1)
  11786. (when org-adapt-indentation
  11787. (indent-to-column (1+ (org-outline-level))))))
  11788. (when what
  11789. ;; Insert planning keyword.
  11790. (insert (cl-case what
  11791. (closed org-closed-string)
  11792. (deadline org-deadline-string)
  11793. (scheduled org-scheduled-string)
  11794. (otherwise (error "Invalid planning type: %s" what)))
  11795. " ")
  11796. ;; Insert associated timestamp.
  11797. (let ((ts (org-insert-time-stamp
  11798. time
  11799. (or org-time-was-given
  11800. (and (eq what 'closed) org-log-done-with-time))
  11801. (eq what 'closed)
  11802. nil nil (list org-end-time-was-given))))
  11803. (unless (eolp) (insert " "))
  11804. ts))))))
  11805. (defvar org-log-note-marker (make-marker)
  11806. "Marker pointing at the entry where the note is to be inserted.")
  11807. (defvar org-log-note-purpose nil)
  11808. (defvar org-log-note-state nil)
  11809. (defvar org-log-note-previous-state nil)
  11810. (defvar org-log-note-extra nil)
  11811. (defvar org-log-note-window-configuration nil)
  11812. (defvar org-log-note-return-to (make-marker))
  11813. (defvar org-log-note-effective-time nil
  11814. "Remembered current time so that dynamically scoped
  11815. `org-extend-today-until' affects timestamps in state change log")
  11816. (defvar org-log-post-message nil
  11817. "Message to be displayed after a log note has been stored.
  11818. The auto-repeater uses this.")
  11819. (defun org-add-note ()
  11820. "Add a note to the current entry.
  11821. This is done in the same way as adding a state change note."
  11822. (interactive)
  11823. (org-add-log-setup 'note))
  11824. (defun org-log-beginning (&optional create)
  11825. "Return expected start of log notes in current entry.
  11826. When optional argument CREATE is non-nil, the function creates
  11827. a drawer to store notes, if necessary. Returned position ignores
  11828. narrowing."
  11829. (org-with-wide-buffer
  11830. (let ((drawer (org-log-into-drawer)))
  11831. (cond
  11832. (drawer
  11833. (org-end-of-meta-data)
  11834. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  11835. (end (if (org-at-heading-p) (point)
  11836. (save-excursion (outline-next-heading) (point))))
  11837. (case-fold-search t))
  11838. (catch 'exit
  11839. ;; Try to find existing drawer.
  11840. (while (re-search-forward regexp end t)
  11841. (let ((element (org-element-at-point)))
  11842. (when (eq (org-element-type element) 'drawer)
  11843. (let ((cend (org-element-property :contents-end element)))
  11844. (when (and (not org-log-states-order-reversed) cend)
  11845. (goto-char cend)))
  11846. (throw 'exit nil))))
  11847. ;; No drawer found. Create one, if permitted.
  11848. (when create
  11849. (unless (bolp) (insert "\n"))
  11850. (let ((beg (point)))
  11851. (insert ":" drawer ":\n:END:\n")
  11852. (org-indent-region beg (point))
  11853. (org-flag-region
  11854. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  11855. (end-of-line -1)))))
  11856. (t
  11857. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  11858. (skip-chars-forward " \t\n")
  11859. (beginning-of-line)
  11860. (unless org-log-states-order-reversed
  11861. (org-skip-over-state-notes)
  11862. (skip-chars-backward " \t\n")
  11863. (forward-line)))))
  11864. (if (bolp) (point) (line-beginning-position 2))))
  11865. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  11866. "Set up the post command hook to take a note.
  11867. If this is about to TODO state change, the new state is expected in STATE.
  11868. HOW is an indicator what kind of note should be created.
  11869. EXTRA is additional text that will be inserted into the notes buffer."
  11870. (move-marker org-log-note-marker (point))
  11871. (setq org-log-note-purpose purpose
  11872. org-log-note-state state
  11873. org-log-note-previous-state prev-state
  11874. org-log-note-how how
  11875. org-log-note-extra extra
  11876. org-log-note-effective-time (org-current-effective-time))
  11877. (add-hook 'post-command-hook 'org-add-log-note 'append))
  11878. (defun org-skip-over-state-notes ()
  11879. "Skip past the list of State notes in an entry."
  11880. (when (ignore-errors (goto-char (org-in-item-p)))
  11881. (let* ((struct (org-list-struct))
  11882. (prevs (org-list-prevs-alist struct))
  11883. (regexp
  11884. (concat "[ \t]*- +"
  11885. (replace-regexp-in-string
  11886. " +" " +"
  11887. (org-replace-escapes
  11888. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  11889. `(("%d" . ,org-ts-regexp-inactive)
  11890. ("%D" . ,org-ts-regexp)
  11891. ("%s" . "\"\\S-+\"")
  11892. ("%S" . "\"\\S-+\"")
  11893. ("%t" . ,org-ts-regexp-inactive)
  11894. ("%T" . ,org-ts-regexp)
  11895. ("%u" . ".*?")
  11896. ("%U" . ".*?")))))))
  11897. (while (looking-at-p regexp)
  11898. (goto-char (or (org-list-get-next-item (point) struct prevs)
  11899. (org-list-get-item-end (point) struct)))))))
  11900. (defun org-add-log-note (&optional _purpose)
  11901. "Pop up a window for taking a note, and add this note later."
  11902. (remove-hook 'post-command-hook 'org-add-log-note)
  11903. (setq org-log-note-window-configuration (current-window-configuration))
  11904. (delete-other-windows)
  11905. (move-marker org-log-note-return-to (point))
  11906. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  11907. (goto-char org-log-note-marker)
  11908. (org-switch-to-buffer-other-window "*Org Note*")
  11909. (erase-buffer)
  11910. (if (memq org-log-note-how '(time state))
  11911. (org-store-log-note)
  11912. (let ((org-inhibit-startup t)) (org-mode))
  11913. (insert (format "# Insert note for %s.
  11914. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  11915. (cond
  11916. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  11917. ((eq org-log-note-purpose 'done) "closed todo item")
  11918. ((eq org-log-note-purpose 'state)
  11919. (format "state change from \"%s\" to \"%s\""
  11920. (or org-log-note-previous-state "")
  11921. (or org-log-note-state "")))
  11922. ((eq org-log-note-purpose 'reschedule)
  11923. "rescheduling")
  11924. ((eq org-log-note-purpose 'delschedule)
  11925. "no longer scheduled")
  11926. ((eq org-log-note-purpose 'redeadline)
  11927. "changing deadline")
  11928. ((eq org-log-note-purpose 'deldeadline)
  11929. "removing deadline")
  11930. ((eq org-log-note-purpose 'refile)
  11931. "refiling")
  11932. ((eq org-log-note-purpose 'note)
  11933. "this entry")
  11934. (t (error "This should not happen")))))
  11935. (when org-log-note-extra (insert org-log-note-extra))
  11936. (setq-local org-finish-function 'org-store-log-note)
  11937. (run-hooks 'org-log-buffer-setup-hook)))
  11938. (defvar org-note-abort nil) ; dynamically scoped
  11939. (defun org-store-log-note ()
  11940. "Finish taking a log note, and insert it to where it belongs."
  11941. (let ((txt (prog1 (buffer-string)
  11942. (kill-buffer)))
  11943. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  11944. lines)
  11945. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  11946. (setq txt (replace-match "" t t txt)))
  11947. (when (string-match "\\s-+\\'" txt)
  11948. (setq txt (replace-match "" t t txt)))
  11949. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  11950. (when (org-string-nw-p note)
  11951. (setq note
  11952. (org-replace-escapes
  11953. note
  11954. (list (cons "%u" (user-login-name))
  11955. (cons "%U" user-full-name)
  11956. (cons "%t" (format-time-string
  11957. (org-time-stamp-format 'long 'inactive)
  11958. org-log-note-effective-time))
  11959. (cons "%T" (format-time-string
  11960. (org-time-stamp-format 'long nil)
  11961. org-log-note-effective-time))
  11962. (cons "%d" (format-time-string
  11963. (org-time-stamp-format nil 'inactive)
  11964. org-log-note-effective-time))
  11965. (cons "%D" (format-time-string
  11966. (org-time-stamp-format nil nil)
  11967. org-log-note-effective-time))
  11968. (cons "%s" (cond
  11969. ((not org-log-note-state) "")
  11970. ((string-match-p org-ts-regexp
  11971. org-log-note-state)
  11972. (format "\"[%s]\""
  11973. (substring org-log-note-state 1 -1)))
  11974. (t (format "\"%s\"" org-log-note-state))))
  11975. (cons "%S"
  11976. (cond
  11977. ((not org-log-note-previous-state) "")
  11978. ((string-match-p org-ts-regexp
  11979. org-log-note-previous-state)
  11980. (format "\"[%s]\""
  11981. (substring
  11982. org-log-note-previous-state 1 -1)))
  11983. (t (format "\"%s\""
  11984. org-log-note-previous-state)))))))
  11985. (when lines (setq note (concat note " \\\\")))
  11986. (push note lines))
  11987. (when (and lines (not org-note-abort))
  11988. (with-current-buffer (marker-buffer org-log-note-marker)
  11989. (org-with-wide-buffer
  11990. ;; Find location for the new note.
  11991. (goto-char org-log-note-marker)
  11992. (set-marker org-log-note-marker nil)
  11993. ;; Note associated to a clock is to be located right after
  11994. ;; the clock. Do not move point.
  11995. (unless (eq org-log-note-purpose 'clock-out)
  11996. (goto-char (org-log-beginning t)))
  11997. ;; Make sure point is at the beginning of an empty line.
  11998. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  11999. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12000. ;; In an existing list, add a new item at the top level.
  12001. ;; Otherwise, indent line like a regular one.
  12002. (let ((itemp (org-in-item-p)))
  12003. (if itemp
  12004. (indent-line-to
  12005. (let ((struct (save-excursion
  12006. (goto-char itemp) (org-list-struct))))
  12007. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12008. (org-indent-line)))
  12009. (insert (org-list-bullet-string "-") (pop lines))
  12010. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12011. (dolist (line lines)
  12012. (insert "\n")
  12013. (indent-line-to ind)
  12014. (insert line)))
  12015. (message "Note stored")
  12016. (org-back-to-heading t))
  12017. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12018. ;; from within `org-add-log-note' because `buffer-undo-list'
  12019. ;; is then modified outside of `org-with-remote-undo'.
  12020. (when (eq this-command 'org-agenda-todo)
  12021. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12022. ;; Don't add undo information when called from `org-agenda-todo'.
  12023. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12024. (set-window-configuration org-log-note-window-configuration)
  12025. (with-current-buffer (marker-buffer org-log-note-return-to)
  12026. (goto-char org-log-note-return-to))
  12027. (move-marker org-log-note-return-to nil)
  12028. (when org-log-post-message (message "%s" org-log-post-message))))
  12029. (defun org-remove-empty-drawer-at (pos)
  12030. "Remove an empty drawer at position POS.
  12031. POS may also be a marker."
  12032. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12033. (org-with-wide-buffer
  12034. (goto-char pos)
  12035. (let ((drawer (org-element-at-point)))
  12036. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12037. (not (org-element-property :contents-begin drawer)))
  12038. (delete-region (org-element-property :begin drawer)
  12039. (progn (goto-char (org-element-property :end drawer))
  12040. (skip-chars-backward " \r\t\n")
  12041. (forward-line)
  12042. (point))))))))
  12043. (defvar org-ts-type nil)
  12044. (defun org-sparse-tree (&optional arg type)
  12045. "Create a sparse tree, prompt for the details.
  12046. This command can create sparse trees. You first need to select the type
  12047. of match used to create the tree:
  12048. t Show all TODO entries.
  12049. T Show entries with a specific TODO keyword.
  12050. m Show entries selected by a tags/property match.
  12051. p Enter a property name and its value (both with completion on existing
  12052. names/values) and show entries with that property.
  12053. r Show entries matching a regular expression (`/' can be used as well).
  12054. b Show deadlines and scheduled items before a date.
  12055. a Show deadlines and scheduled items after a date.
  12056. d Show deadlines due within `org-deadline-warning-days'.
  12057. D Show deadlines and scheduled items between a date range."
  12058. (interactive "P")
  12059. (setq type (or type org-sparse-tree-default-date-type))
  12060. (setq org-ts-type type)
  12061. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12062. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12063. \[c]ycle through date types: %s"
  12064. (cl-case type
  12065. (all "all timestamps")
  12066. (scheduled "only scheduled")
  12067. (deadline "only deadline")
  12068. (active "only active timestamps")
  12069. (inactive "only inactive timestamps")
  12070. (closed "with a closed time-stamp")
  12071. (otherwise "scheduled/deadline")))
  12072. (let ((answer (read-char-exclusive)))
  12073. (cl-case answer
  12074. (?c
  12075. (org-sparse-tree
  12076. arg
  12077. (cadr
  12078. (memq type '(nil all scheduled deadline active inactive closed)))))
  12079. (?d (call-interactively 'org-check-deadlines))
  12080. (?b (call-interactively 'org-check-before-date))
  12081. (?a (call-interactively 'org-check-after-date))
  12082. (?D (call-interactively 'org-check-dates-range))
  12083. (?t (call-interactively 'org-show-todo-tree))
  12084. (?T (org-show-todo-tree '(4)))
  12085. (?m (call-interactively 'org-match-sparse-tree))
  12086. ((?p ?P)
  12087. (let* ((kwd (completing-read
  12088. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12089. (value (completing-read
  12090. "Value: " (mapcar #'list (org-property-values kwd)))))
  12091. (unless (string-match "\\`{.*}\\'" value)
  12092. (setq value (concat "\"" value "\"")))
  12093. (org-match-sparse-tree arg (concat kwd "=" value))))
  12094. ((?r ?R ?/) (call-interactively 'org-occur))
  12095. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12096. (defvar-local org-occur-highlights nil
  12097. "List of overlays used for occur matches.")
  12098. (defvar-local org-occur-parameters nil
  12099. "Parameters of the active org-occur calls.
  12100. This is a list, each call to org-occur pushes as cons cell,
  12101. containing the regular expression and the callback, onto the list.
  12102. The list can contain several entries if `org-occur' has been called
  12103. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12104. will only contain one set of parameters. When the highlights are
  12105. removed (for example with `C-c C-c', or with the next edit (depending
  12106. on `org-remove-highlights-with-change'), this variable is emptied
  12107. as well.")
  12108. (defun org-occur (regexp &optional keep-previous callback)
  12109. "Make a compact tree which shows all matches of REGEXP.
  12110. The tree will show the lines where the regexp matches, and any other context
  12111. defined in `org-show-context-detail', which see.
  12112. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12113. done by a previous call to `org-occur' will be kept, to allow stacking of
  12114. calls to this command.
  12115. Optional argument CALLBACK can be a function of no argument. In this case,
  12116. it is called with point at the end of the match, match data being set
  12117. accordingly. Current match is shown only if the return value is non-nil.
  12118. The function must neither move point nor alter narrowing."
  12119. (interactive "sRegexp: \nP")
  12120. (when (equal regexp "")
  12121. (user-error "Regexp cannot be empty"))
  12122. (unless keep-previous
  12123. (org-remove-occur-highlights nil nil t))
  12124. (push (cons regexp callback) org-occur-parameters)
  12125. (let ((cnt 0))
  12126. (save-excursion
  12127. (goto-char (point-min))
  12128. (when (or (not keep-previous) ; do not want to keep
  12129. (not org-occur-highlights)) ; no previous matches
  12130. ;; hide everything
  12131. (org-overview))
  12132. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12133. (isearch-no-upper-case-p regexp t)
  12134. org-occur-case-fold-search)))
  12135. (while (re-search-forward regexp nil t)
  12136. (when (or (not callback)
  12137. (save-match-data (funcall callback)))
  12138. (setq cnt (1+ cnt))
  12139. (when org-highlight-sparse-tree-matches
  12140. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12141. (org-show-context 'occur-tree)))))
  12142. (when org-remove-highlights-with-change
  12143. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12144. nil 'local))
  12145. (unless org-sparse-tree-open-archived-trees
  12146. (org-hide-archived-subtrees (point-min) (point-max)))
  12147. (run-hooks 'org-occur-hook)
  12148. (when (called-interactively-p 'interactive)
  12149. (message "%d match(es) for regexp %s" cnt regexp))
  12150. cnt))
  12151. (defun org-occur-next-match (&optional n _reset)
  12152. "Function for `next-error-function' to find sparse tree matches.
  12153. N is the number of matches to move, when negative move backwards.
  12154. This function always goes back to the starting point when no
  12155. match is found."
  12156. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12157. (search-func (if (< n 0)
  12158. 'previous-single-char-property-change
  12159. 'next-single-char-property-change))
  12160. (n (abs n))
  12161. (pos (point))
  12162. p1)
  12163. (catch 'exit
  12164. (while (setq p1 (funcall search-func (point) 'org-type))
  12165. (when (equal p1 limit)
  12166. (goto-char pos)
  12167. (user-error "No more matches"))
  12168. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12169. (setq n (1- n))
  12170. (when (= n 0)
  12171. (goto-char p1)
  12172. (throw 'exit (point))))
  12173. (goto-char p1))
  12174. (goto-char p1)
  12175. (user-error "No more matches"))))
  12176. (defun org-highlight-new-match (beg end)
  12177. "Highlight from BEG to END and mark the highlight is an occur headline."
  12178. (let ((ov (make-overlay beg end)))
  12179. (overlay-put ov 'face 'secondary-selection)
  12180. (overlay-put ov 'org-type 'org-occur)
  12181. (push ov org-occur-highlights)))
  12182. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12183. "Remove the occur highlights from the buffer.
  12184. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12185. from the `before-change-functions' in the current buffer."
  12186. (interactive)
  12187. (unless org-inhibit-highlight-removal
  12188. (mapc #'delete-overlay org-occur-highlights)
  12189. (setq org-occur-highlights nil)
  12190. (setq org-occur-parameters nil)
  12191. (unless noremove
  12192. (remove-hook 'before-change-functions
  12193. 'org-remove-occur-highlights 'local))))
  12194. ;;;; Priorities
  12195. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12196. "Regular expression matching the priority indicator.")
  12197. (defvar org-remove-priority-next-time nil)
  12198. (defun org-priority-up ()
  12199. "Increase the priority of the current item."
  12200. (interactive)
  12201. (org-priority 'up))
  12202. (defun org-priority-down ()
  12203. "Decrease the priority of the current item."
  12204. (interactive)
  12205. (org-priority 'down))
  12206. (defun org-priority (&optional action _show)
  12207. "Change the priority of an item.
  12208. ACTION can be `set', `up', `down', or a character."
  12209. (interactive "P")
  12210. (if (equal action '(4))
  12211. (org-show-priority)
  12212. (unless org-enable-priority-commands
  12213. (user-error "Priority commands are disabled"))
  12214. (setq action (or action 'set))
  12215. (let (current new news have remove)
  12216. (save-excursion
  12217. (org-back-to-heading t)
  12218. (when (looking-at org-priority-regexp)
  12219. (setq current (string-to-char (match-string 2))
  12220. have t))
  12221. (cond
  12222. ((eq action 'remove)
  12223. (setq remove t new ?\ ))
  12224. ((or (eq action 'set)
  12225. (integerp action))
  12226. (if (not (eq action 'set))
  12227. (setq new action)
  12228. (message "Priority %c-%c, SPC to remove: "
  12229. org-highest-priority org-lowest-priority)
  12230. (save-match-data
  12231. (setq new (read-char-exclusive))))
  12232. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12233. (= (upcase org-lowest-priority) org-lowest-priority))
  12234. (setq new (upcase new)))
  12235. (cond ((equal new ?\ ) (setq remove t))
  12236. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12237. (user-error "Priority must be between `%c' and `%c'"
  12238. org-highest-priority org-lowest-priority))))
  12239. ((eq action 'up)
  12240. (setq new (if have
  12241. (1- current) ; normal cycling
  12242. ;; last priority was empty
  12243. (if (eq last-command this-command)
  12244. org-lowest-priority ; wrap around empty to lowest
  12245. ;; default
  12246. (if org-priority-start-cycle-with-default
  12247. org-default-priority
  12248. (1- org-default-priority))))))
  12249. ((eq action 'down)
  12250. (setq new (if have
  12251. (1+ current) ; normal cycling
  12252. ;; last priority was empty
  12253. (if (eq last-command this-command)
  12254. org-highest-priority ; wrap around empty to highest
  12255. ;; default
  12256. (if org-priority-start-cycle-with-default
  12257. org-default-priority
  12258. (1+ org-default-priority))))))
  12259. (t (user-error "Invalid action")))
  12260. (when (or (< (upcase new) org-highest-priority)
  12261. (> (upcase new) org-lowest-priority))
  12262. (if (and (memq action '(up down))
  12263. (not have) (not (eq last-command this-command)))
  12264. ;; `new' is from default priority
  12265. (error
  12266. "The default can not be set, see `org-default-priority' why")
  12267. ;; normal cycling: `new' is beyond highest/lowest priority
  12268. ;; and is wrapped around to the empty priority
  12269. (setq remove t)))
  12270. (setq news (format "%c" new))
  12271. (if have
  12272. (if remove
  12273. (replace-match "" t t nil 1)
  12274. (replace-match news t t nil 2))
  12275. (if remove
  12276. (user-error "No priority cookie found in line")
  12277. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12278. (if (match-end 2)
  12279. (progn
  12280. (goto-char (match-end 2))
  12281. (insert " [#" news "]"))
  12282. (goto-char (match-beginning 3))
  12283. (insert "[#" news "] "))))
  12284. (org-align-tags))
  12285. (if remove
  12286. (message "Priority removed")
  12287. (message "Priority of current item set to %s" news)))))
  12288. (defun org-show-priority ()
  12289. "Show the priority of the current item.
  12290. This priority is composed of the main priority given with the [#A] cookies,
  12291. and by additional input from the age of a schedules or deadline entry."
  12292. (interactive)
  12293. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12294. (org-get-at-bol 'priority)
  12295. (save-excursion
  12296. (save-match-data
  12297. (beginning-of-line)
  12298. (and (looking-at org-heading-regexp)
  12299. (org-get-priority (match-string 0))))))))
  12300. (message "Priority is %d" (if pri pri -1000))))
  12301. (defun org-get-priority (s)
  12302. "Find priority cookie and return priority."
  12303. (save-match-data
  12304. (if (functionp org-get-priority-function)
  12305. (funcall org-get-priority-function)
  12306. (if (not (string-match org-priority-regexp s))
  12307. (* 1000 (- org-lowest-priority org-default-priority))
  12308. (* 1000 (- org-lowest-priority
  12309. (string-to-char (match-string 2 s))))))))
  12310. ;;;; Tags
  12311. (defvar org-agenda-archives-mode)
  12312. (defvar org-map-continue-from nil
  12313. "Position from where mapping should continue.
  12314. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12315. (defvar org-scanner-tags nil
  12316. "The current tag list while the tags scanner is running.")
  12317. (defvar org-trust-scanner-tags nil
  12318. "Should `org-get-tags' use the tags for the scanner.
  12319. This is for internal dynamical scoping only.
  12320. When this is non-nil, the function `org-get-tags' will return the value
  12321. of `org-scanner-tags' instead of building the list by itself. This
  12322. can lead to large speed-ups when the tags scanner is used in a file with
  12323. many entries, and when the list of tags is retrieved, for example to
  12324. obtain a list of properties. Building the tags list for each entry in such
  12325. a file becomes an N^2 operation - but with this variable set, it scales
  12326. as N.")
  12327. (defvar org--matcher-tags-todo-only nil)
  12328. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12329. "Scan headline tags with inheritance and produce output ACTION.
  12330. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12331. or `agenda' to produce an entry list for an agenda view. It can also be
  12332. a Lisp form or a function that should be called at each matched headline, in
  12333. this case the return value is a list of all return values from these calls.
  12334. MATCHER is a function accepting three arguments, returning
  12335. a non-nil value whenever a given set of tags qualifies a headline
  12336. for inclusion. See `org-make-tags-matcher' for more information.
  12337. As a special case, it can also be set to t (respectively nil) in
  12338. order to match all (respectively none) headline.
  12339. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  12340. included in the output.
  12341. START-LEVEL can be a string with asterisks, reducing the scope to
  12342. headlines matching this string."
  12343. (require 'org-agenda)
  12344. (let* ((re (concat "^"
  12345. (if start-level
  12346. ;; Get the correct level to match
  12347. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12348. org-outline-regexp)
  12349. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  12350. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  12351. (props (list 'face 'default
  12352. 'done-face 'org-agenda-done
  12353. 'undone-face 'default
  12354. 'mouse-face 'highlight
  12355. 'org-not-done-regexp org-not-done-regexp
  12356. 'org-todo-regexp org-todo-regexp
  12357. 'org-complex-heading-regexp org-complex-heading-regexp
  12358. 'help-echo
  12359. (format "mouse-2 or RET jump to Org file %S"
  12360. (abbreviate-file-name
  12361. (or (buffer-file-name (buffer-base-buffer))
  12362. (buffer-name (buffer-base-buffer)))))))
  12363. (org-map-continue-from nil)
  12364. lspos tags tags-list
  12365. (tags-alist (list (cons 0 org-file-tags)))
  12366. (llast 0) rtn rtn1 level category i txt
  12367. todo marker entry priority
  12368. ts-date ts-date-type ts-date-pair)
  12369. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12370. (setq action (list 'lambda nil action)))
  12371. (save-excursion
  12372. (goto-char (point-min))
  12373. (when (eq action 'sparse-tree)
  12374. (org-overview)
  12375. (org-remove-occur-highlights))
  12376. (while (let (case-fold-search)
  12377. (re-search-forward re nil t))
  12378. (setq org-map-continue-from nil)
  12379. (catch :skip
  12380. ;; Ignore closing parts of inline tasks.
  12381. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  12382. (throw :skip t))
  12383. (setq todo
  12384. ;; TODO: is the 1-2 difference a bug?
  12385. (when (match-end 1) (match-string-no-properties 2))
  12386. tags (when (match-end 4) (match-string-no-properties 4)))
  12387. (goto-char (setq lspos (match-beginning 0)))
  12388. (setq level (org-reduced-level (org-outline-level))
  12389. category (org-get-category))
  12390. (when (eq action 'agenda)
  12391. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12392. ts-date (car ts-date-pair)
  12393. ts-date-type (cdr ts-date-pair)))
  12394. (setq i llast llast level)
  12395. ;; remove tag lists from same and sublevels
  12396. (while (>= i level)
  12397. (when (setq entry (assoc i tags-alist))
  12398. (setq tags-alist (delete entry tags-alist)))
  12399. (setq i (1- i)))
  12400. ;; add the next tags
  12401. (when tags
  12402. (setq tags (org-split-string tags ":")
  12403. tags-alist
  12404. (cons (cons level tags) tags-alist)))
  12405. ;; compile tags for current headline
  12406. (setq tags-list
  12407. (if org-use-tag-inheritance
  12408. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12409. tags)
  12410. org-scanner-tags tags-list)
  12411. (when org-use-tag-inheritance
  12412. (setcdr (car tags-alist)
  12413. (mapcar (lambda (x)
  12414. (setq x (copy-sequence x))
  12415. (org-add-prop-inherited x))
  12416. (cdar tags-alist))))
  12417. (when (and tags org-use-tag-inheritance
  12418. (or (not (eq t org-use-tag-inheritance))
  12419. org-tags-exclude-from-inheritance))
  12420. ;; Selective inheritance, remove uninherited ones.
  12421. (setcdr (car tags-alist)
  12422. (org-remove-uninherited-tags (cdar tags-alist))))
  12423. (when (and
  12424. ;; eval matcher only when the todo condition is OK
  12425. (and (or (not todo-only) (member todo org-todo-keywords-1))
  12426. (if (functionp matcher)
  12427. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12428. (funcall matcher todo tags-list level))
  12429. matcher))
  12430. ;; Call the skipper, but return t if it does not
  12431. ;; skip, so that the `and' form continues evaluating.
  12432. (progn
  12433. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12434. t)
  12435. ;; Check if timestamps are deselecting this entry
  12436. (or (not todo-only)
  12437. (and (member todo org-todo-keywords-1)
  12438. (or (not org-agenda-tags-todo-honor-ignore-options)
  12439. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12440. ;; select this headline
  12441. (cond
  12442. ((eq action 'sparse-tree)
  12443. (and org-highlight-sparse-tree-matches
  12444. (org-get-heading) (match-end 0)
  12445. (org-highlight-new-match
  12446. (match-beginning 1) (match-end 1)))
  12447. (org-show-context 'tags-tree))
  12448. ((eq action 'agenda)
  12449. (setq txt (org-agenda-format-item
  12450. ""
  12451. (concat
  12452. (if (eq org-tags-match-list-sublevels 'indented)
  12453. (make-string (1- level) ?.) "")
  12454. (org-get-heading))
  12455. (make-string level ?\s)
  12456. category
  12457. tags-list)
  12458. priority (org-get-priority txt))
  12459. (goto-char lspos)
  12460. (setq marker (org-agenda-new-marker))
  12461. (org-add-props txt props
  12462. 'org-marker marker 'org-hd-marker marker 'org-category category
  12463. 'todo-state todo
  12464. 'ts-date ts-date
  12465. 'priority priority
  12466. 'type (concat "tagsmatch" ts-date-type))
  12467. (push txt rtn))
  12468. ((functionp action)
  12469. (setq org-map-continue-from nil)
  12470. (save-excursion
  12471. (setq rtn1 (funcall action))
  12472. (push rtn1 rtn)))
  12473. (t (user-error "Invalid action")))
  12474. ;; if we are to skip sublevels, jump to end of subtree
  12475. (unless org-tags-match-list-sublevels
  12476. (org-end-of-subtree t)
  12477. (backward-char 1))))
  12478. ;; Get the correct position from where to continue
  12479. (if org-map-continue-from
  12480. (goto-char org-map-continue-from)
  12481. (and (= (point) lspos) (end-of-line 1)))))
  12482. (when (and (eq action 'sparse-tree)
  12483. (not org-sparse-tree-open-archived-trees))
  12484. (org-hide-archived-subtrees (point-min) (point-max)))
  12485. (nreverse rtn)))
  12486. (defun org-remove-uninherited-tags (tags)
  12487. "Remove all tags that are not inherited from the list TAGS."
  12488. (cond
  12489. ((eq org-use-tag-inheritance t)
  12490. (if org-tags-exclude-from-inheritance
  12491. (org-delete-all org-tags-exclude-from-inheritance tags)
  12492. tags))
  12493. ((not org-use-tag-inheritance) nil)
  12494. ((stringp org-use-tag-inheritance)
  12495. (delq nil (mapcar
  12496. (lambda (x)
  12497. (if (and (string-match org-use-tag-inheritance x)
  12498. (not (member x org-tags-exclude-from-inheritance)))
  12499. x nil))
  12500. tags)))
  12501. ((listp org-use-tag-inheritance)
  12502. (delq nil (mapcar
  12503. (lambda (x)
  12504. (if (member x org-use-tag-inheritance) x nil))
  12505. tags)))))
  12506. (defun org-match-sparse-tree (&optional todo-only match)
  12507. "Create a sparse tree according to tags string MATCH.
  12508. MATCH is a string with match syntax. It can contain a selection
  12509. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12510. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12511. those. See the manual for details.
  12512. If optional argument TODO-ONLY is non-nil, only select lines that
  12513. are also TODO tasks."
  12514. (interactive "P")
  12515. (org-agenda-prepare-buffers (list (current-buffer)))
  12516. (let ((org--matcher-tags-todo-only todo-only))
  12517. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12518. org--matcher-tags-todo-only)))
  12519. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12520. (defvar org-cached-props nil)
  12521. (defun org-cached-entry-get (pom property)
  12522. (if (or (eq t org-use-property-inheritance)
  12523. (and (stringp org-use-property-inheritance)
  12524. (let ((case-fold-search t))
  12525. (string-match-p org-use-property-inheritance property)))
  12526. (and (listp org-use-property-inheritance)
  12527. (member-ignore-case property org-use-property-inheritance)))
  12528. ;; Caching is not possible, check it directly.
  12529. (org-entry-get pom property 'inherit)
  12530. ;; Get all properties, so we can do complicated checks easily.
  12531. (cdr (assoc-string property
  12532. (or org-cached-props
  12533. (setq org-cached-props (org-entry-properties pom)))
  12534. t))))
  12535. (defun org-global-tags-completion-table (&optional files)
  12536. "Return the list of all tags in all agenda buffer/files.
  12537. Optional FILES argument is a list of files which can be used
  12538. instead of the agenda files."
  12539. (save-excursion
  12540. (org-uniquify
  12541. (delq nil
  12542. (apply #'append
  12543. (mapcar
  12544. (lambda (file)
  12545. (set-buffer (find-file-noselect file))
  12546. (org--tag-add-to-alist
  12547. (org-get-buffer-tags)
  12548. (mapcar (lambda (x)
  12549. (and (stringp (car-safe x))
  12550. (list (car-safe x))))
  12551. org-current-tag-alist)))
  12552. (if (car-safe files) files
  12553. (org-agenda-files))))))))
  12554. (defun org-make-tags-matcher (match)
  12555. "Create the TAGS/TODO matcher form for the selection string MATCH.
  12556. Returns a cons of the selection string MATCH and a function
  12557. implementing the matcher.
  12558. The matcher is to be called at an Org entry, with point on the
  12559. headline, and returns non-nil if the entry matches the selection
  12560. string MATCH. It must be called with three arguments: the TODO
  12561. keyword at the entry (or nil if none), the list of all tags at
  12562. the entry including inherited ones and the reduced level of the
  12563. headline. Additionally, the category of the entry, if any, must
  12564. be specified as the text property `org-category' on the headline.
  12565. This function sets the variable `org--matcher-tags-todo-only' to
  12566. a non-nil value if the matcher restricts matching to TODO
  12567. entries, otherwise it is not touched.
  12568. See also `org-scan-tags'."
  12569. (unless match
  12570. ;; Get a new match request, with completion against the global
  12571. ;; tags table and the local tags in current buffer.
  12572. (let ((org-last-tags-completion-table
  12573. (org--tag-add-to-alist
  12574. (org-get-buffer-tags)
  12575. (org-global-tags-completion-table))))
  12576. (setq match
  12577. (completing-read
  12578. "Match: "
  12579. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  12580. (let ((match0 match)
  12581. (re (concat
  12582. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  12583. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  12584. "\\([<>=]\\{1,2\\}\\)"
  12585. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  12586. "\\|" org-tag-re "\\)"))
  12587. (start 0)
  12588. tagsmatch todomatch tagsmatcher todomatcher)
  12589. ;; Expand group tags.
  12590. (setq match (org-tags-expand match))
  12591. ;; Check if there is a TODO part of this match, which would be the
  12592. ;; part after a "/". To make sure that this slash is not part of
  12593. ;; a property value to be matched against, we also check that
  12594. ;; there is no / after that slash. First, find the last slash.
  12595. (let ((s 0))
  12596. (while (string-match "/+" match s)
  12597. (setq start (match-beginning 0))
  12598. (setq s (match-end 0))))
  12599. (if (and (string-match "/+" match start)
  12600. (not (string-match-p "\"" match start)))
  12601. ;; Match contains also a TODO-matching request.
  12602. (progn
  12603. (setq tagsmatch (substring match 0 (match-beginning 0)))
  12604. (setq todomatch (substring match (match-end 0)))
  12605. (when (string-prefix-p "!" todomatch)
  12606. (setq org--matcher-tags-todo-only t)
  12607. (setq todomatch (substring todomatch 1)))
  12608. (when (string-match "\\`\\s-*\\'" todomatch)
  12609. (setq todomatch nil)))
  12610. ;; Only matching tags.
  12611. (setq tagsmatch match)
  12612. (setq todomatch nil))
  12613. ;; Make the tags matcher.
  12614. (when (org-string-nw-p tagsmatch)
  12615. (let ((orlist nil)
  12616. (orterms (org-split-string tagsmatch "|"))
  12617. term)
  12618. (while (setq term (pop orterms))
  12619. (while (and (equal (substring term -1) "\\") orterms)
  12620. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  12621. (while (string-match re term)
  12622. (let* ((rest (substring term (match-end 0)))
  12623. (minus (and (match-end 1)
  12624. (equal (match-string 1 term) "-")))
  12625. (tag (save-match-data
  12626. (replace-regexp-in-string
  12627. "\\\\-" "-" (match-string 2 term))))
  12628. (regexp (eq (string-to-char tag) ?{))
  12629. (levelp (match-end 4))
  12630. (propp (match-end 5))
  12631. (mm
  12632. (cond
  12633. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  12634. (levelp
  12635. `(,(org-op-to-function (match-string 3 term))
  12636. level
  12637. ,(string-to-number (match-string 4 term))))
  12638. (propp
  12639. (let* ((gv (pcase (upcase (match-string 5 term))
  12640. ("CATEGORY"
  12641. '(get-text-property (point) 'org-category))
  12642. ("TODO" 'todo)
  12643. (p `(org-cached-entry-get nil ,p))))
  12644. (pv (match-string 7 term))
  12645. (regexp (eq (string-to-char pv) ?{))
  12646. (strp (eq (string-to-char pv) ?\"))
  12647. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  12648. (po (org-op-to-function (match-string 6 term)
  12649. (if timep 'time strp))))
  12650. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  12651. (when timep (setq pv (org-matcher-time pv)))
  12652. (cond ((and regexp (eq po '/=))
  12653. `(not (string-match ,pv (or ,gv ""))))
  12654. (regexp `(string-match ,pv (or ,gv "")))
  12655. (strp `(,po (or ,gv "") ,pv))
  12656. (t
  12657. `(,po
  12658. (string-to-number (or ,gv ""))
  12659. ,(string-to-number pv))))))
  12660. (t `(member ,tag tags-list)))))
  12661. (push (if minus `(not ,mm) mm) tagsmatcher)
  12662. (setq term rest)))
  12663. (push `(and ,@tagsmatcher) orlist)
  12664. (setq tagsmatcher nil))
  12665. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  12666. ;; Make the TODO matcher.
  12667. (when (org-string-nw-p todomatch)
  12668. (let ((orlist nil))
  12669. (dolist (term (org-split-string todomatch "|"))
  12670. (while (string-match re term)
  12671. (let* ((minus (and (match-end 1)
  12672. (equal (match-string 1 term) "-")))
  12673. (kwd (match-string 2 term))
  12674. (regexp (eq (string-to-char kwd) ?{))
  12675. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  12676. `(equal todo ,kwd))))
  12677. (push (if minus `(not ,mm) mm) todomatcher))
  12678. (setq term (substring term (match-end 0))))
  12679. (push (if (> (length todomatcher) 1)
  12680. (cons 'and todomatcher)
  12681. (car todomatcher))
  12682. orlist)
  12683. (setq todomatcher nil))
  12684. (setq todomatcher (cons 'or orlist))))
  12685. ;; Return the string and function of the matcher. If no
  12686. ;; tags-specific or todo-specific matcher exists, match
  12687. ;; everything.
  12688. (let ((matcher (if (and tagsmatcher todomatcher)
  12689. `(and ,tagsmatcher ,todomatcher)
  12690. (or tagsmatcher todomatcher t))))
  12691. (when org--matcher-tags-todo-only
  12692. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  12693. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  12694. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  12695. "Expand group tags in MATCH.
  12696. This replaces every group tag in MATCH with a regexp tag search.
  12697. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  12698. will be replaced like this:
  12699. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12700. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12701. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12702. Replacing by a regexp preserves the structure of the match.
  12703. E.g., this expansion
  12704. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  12705. will match anything tagged with \"Lab\" and \"Home\", or tagged
  12706. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  12707. A group tag in MATCH can contain regular expressions of its own.
  12708. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  12709. will be replaced like this:
  12710. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  12711. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  12712. assumed to be a single group tag, and the function will return
  12713. the list of tags in this group.
  12714. When DOWNCASE is non-nil, expand downcased TAGS."
  12715. (if org-group-tags
  12716. (let* ((case-fold-search t)
  12717. (stable org-mode-syntax-table)
  12718. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  12719. (taggroups (if downcased
  12720. (mapcar (lambda (tg) (mapcar #'downcase tg))
  12721. taggroups)
  12722. taggroups))
  12723. (taggroups-keys (mapcar #'car taggroups))
  12724. (return-match (if downcased (downcase match) match))
  12725. (count 0)
  12726. (work-already-expanded tags-already-expanded)
  12727. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  12728. ;; @ and _ are allowed as word-components in tags.
  12729. (modify-syntax-entry ?@ "w" stable)
  12730. (modify-syntax-entry ?_ "w" stable)
  12731. ;; Temporarily replace regexp-expressions in the match-expression.
  12732. (while (string-match "{.+?}" return-match)
  12733. (cl-incf count)
  12734. (push (match-string 0 return-match) regexps-in-match)
  12735. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  12736. (while (and taggroups-keys
  12737. (with-syntax-table stable
  12738. (string-match
  12739. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  12740. (regexp-opt taggroups-keys) "\\>\\)")
  12741. return-match)))
  12742. (let* ((dir (match-string 1 return-match))
  12743. (tag (match-string 2 return-match))
  12744. (tag (if downcased (downcase tag) tag)))
  12745. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  12746. (member tag tags-already-expanded))
  12747. (setq tags-in-group (assoc tag taggroups))
  12748. (push tag work-already-expanded)
  12749. ;; Recursively expand each tag in the group, if the tag hasn't
  12750. ;; already been expanded. Restore the match-data after all recursive calls.
  12751. (save-match-data
  12752. (let (tags-expanded)
  12753. (dolist (x (cdr tags-in-group))
  12754. (if (and (member x taggroups-keys)
  12755. (not (member x work-already-expanded)))
  12756. (setq tags-expanded
  12757. (delete-dups
  12758. (append
  12759. (org-tags-expand x t downcased
  12760. work-already-expanded)
  12761. tags-expanded)))
  12762. (setq tags-expanded
  12763. (append (list x) tags-expanded)))
  12764. (setq work-already-expanded
  12765. (delete-dups
  12766. (append tags-expanded
  12767. work-already-expanded))))
  12768. (setq tags-in-group
  12769. (delete-dups (cons (car tags-in-group)
  12770. tags-expanded)))))
  12771. ;; Filter tag-regexps from tags.
  12772. (setq regexp-in-group-escaped
  12773. (delq nil (mapcar (lambda (x)
  12774. (if (stringp x)
  12775. (and (equal "{" (substring x 0 1))
  12776. (equal "}" (substring x -1))
  12777. x)
  12778. x))
  12779. tags-in-group))
  12780. regexp-in-group
  12781. (mapcar (lambda (x)
  12782. (substring x 1 -1))
  12783. regexp-in-group-escaped)
  12784. tags-in-group
  12785. (delq nil (mapcar (lambda (x)
  12786. (if (stringp x)
  12787. (and (not (equal "{" (substring x 0 1)))
  12788. (not (equal "}" (substring x -1)))
  12789. x)
  12790. x))
  12791. tags-in-group)))
  12792. ;; If single-as-list, do no more in the while-loop.
  12793. (if (not single-as-list)
  12794. (progn
  12795. (when regexp-in-group
  12796. (setq regexp-in-group
  12797. (concat "\\|"
  12798. (mapconcat 'identity regexp-in-group
  12799. "\\|"))))
  12800. (setq tags-in-group
  12801. (concat dir
  12802. "{\\<"
  12803. (regexp-opt tags-in-group)
  12804. "\\>"
  12805. regexp-in-group
  12806. "}"))
  12807. (when (stringp tags-in-group)
  12808. (org-add-props tags-in-group '(grouptag t)))
  12809. (setq return-match
  12810. (replace-match tags-in-group t t return-match)))
  12811. (setq tags-in-group
  12812. (append regexp-in-group-escaped tags-in-group))))
  12813. (setq taggroups-keys (delete tag taggroups-keys))))
  12814. ;; Add the regular expressions back into the match-expression again.
  12815. (while regexps-in-match
  12816. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  12817. (pop regexps-in-match)
  12818. return-match t t))
  12819. (cl-decf count))
  12820. (if single-as-list
  12821. (if tags-in-group tags-in-group (list return-match))
  12822. return-match))
  12823. (if single-as-list
  12824. (list (if downcased (downcase match) match))
  12825. match)))
  12826. (defun org-op-to-function (op &optional stringp)
  12827. "Turn an operator into the appropriate function."
  12828. (setq op
  12829. (cond
  12830. ((equal op "<" ) '(< org-string< org-time<))
  12831. ((equal op ">" ) '(> org-string> org-time>))
  12832. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  12833. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  12834. ((member op '("=" "==")) '(= string= org-time=))
  12835. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  12836. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  12837. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  12838. (defvar org-tags-overlay (make-overlay 1 1))
  12839. (delete-overlay org-tags-overlay)
  12840. (defun org-add-prop-inherited (s)
  12841. (add-text-properties 0 (length s) '(inherited t) s)
  12842. s)
  12843. (defun org-toggle-tag (tag &optional onoff)
  12844. "Toggle the tag TAG for the current line.
  12845. If ONOFF is `on' or `off', don't toggle but set to this state."
  12846. (save-excursion
  12847. (org-back-to-heading t)
  12848. (let ((current
  12849. ;; Reverse the tags list so any new tag is appended to the
  12850. ;; current list of tags.
  12851. (nreverse (org-get-tags nil t)))
  12852. res)
  12853. (pcase onoff
  12854. (`off (setq current (delete tag current)))
  12855. ((or `on (guard (not (member tag current))))
  12856. (setq res t)
  12857. (cl-pushnew tag current :test #'equal))
  12858. (_ (setq current (delete tag current))))
  12859. (org-set-tags (nreverse current))
  12860. res)))
  12861. (defun org--align-tags-here (to-col)
  12862. "Align tags on the current headline to TO-COL.
  12863. Assume point is on a headline."
  12864. (when (and (org-match-line org-tag-line-re)
  12865. (< (point) (match-beginning 1)))
  12866. (let ((pos (point))
  12867. (shift (if (>= to-col 0) to-col
  12868. (- (abs to-col) (string-width (match-string 1))))))
  12869. ;; Delete all blanks before tags.
  12870. (goto-char (match-beginning 1))
  12871. (skip-chars-backward " \t")
  12872. (delete-region (point) (match-beginning 1))
  12873. ;; Insert new blanks.
  12874. (insert (make-string (max 1 (- shift (current-column))) ?\s))
  12875. ;; Preserve initial position, if possible. In any case, stop
  12876. ;; before tags.
  12877. (when (< pos (point)) (goto-char pos)))))
  12878. (defun org-set-tags-command (&optional arg)
  12879. "Set the tags for the current visible entry.
  12880. When called with `\\[universal-argument]' prefix argument ARG, \
  12881. realign all tags
  12882. in the current buffer. If a region is active, set tags for
  12883. all headlines in the region.
  12884. This function is for interactive use only;
  12885. in Lisp code use `org-set-tags' instead."
  12886. (interactive "P")
  12887. (cond
  12888. (arg (org-align-tags t))
  12889. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12890. ;; Disable `org-loop-over-headlines-in-active-region' for
  12891. ;; successive calls.
  12892. (let (org-loop-over-headlines-in-active-region)
  12893. (org-map-entries
  12894. #'org-set-tags-command
  12895. nil
  12896. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12897. 'region-start-level
  12898. 'region)
  12899. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  12900. (t
  12901. (org-back-to-heading)
  12902. (let* ((all-tags (org-get-tags))
  12903. (table (setq org-last-tags-completion-table
  12904. (org--tag-add-to-alist
  12905. (and org-complete-tags-always-offer-all-agenda-tags
  12906. (org-global-tags-completion-table
  12907. (org-agenda-files)))
  12908. (or org-current-tag-alist (org-get-buffer-tags)))))
  12909. (current-tags
  12910. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  12911. all-tags))
  12912. (inherited-tags
  12913. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  12914. all-tags))
  12915. (tags
  12916. (replace-regexp-in-string
  12917. ;; Ignore all forbidden characters in tags.
  12918. "[^[:alnum:]_@#%]+" ":"
  12919. (if (or (eq t org-use-fast-tag-selection)
  12920. (and org-use-fast-tag-selection
  12921. (delq nil (mapcar #'cdr table))))
  12922. (org-fast-tag-selection
  12923. current-tags
  12924. inherited-tags
  12925. table
  12926. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  12927. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  12928. (org-trim (completing-read
  12929. "Tags: "
  12930. #'org-tags-completion-function
  12931. nil nil (org-make-tag-string current-tags)
  12932. 'org-tags-history)))))))
  12933. (org-set-tags tags)))))
  12934. (defun org-align-tags (&optional all)
  12935. "Align tags in current entry.
  12936. When optional argument ALL is non-nil, align all tags in the
  12937. visible part of the buffer."
  12938. (save-excursion
  12939. (if all (goto-char (point-min)) (org-back-to-heading t))
  12940. (catch :single
  12941. (while (re-search-forward org-tag-line-re nil t)
  12942. (let* ((offset (if (bound-and-true-p org-indent-mode)
  12943. (* (1- org-indent-indentation-per-level)
  12944. (1- (org-current-level)))
  12945. 0))
  12946. (tags-column (+ org-tags-column
  12947. (if (> org-tags-column 0) (- offset) offset))))
  12948. (beginning-of-line)
  12949. (org--align-tags-here tags-column)
  12950. (if all (forward-line) (throw :single nil)))))))
  12951. (defun org-set-tags (tags)
  12952. "Set the tags of the current entry to TAGS, replacing current tags.
  12953. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  12954. If TAGS is nil or the empty string, all tags are removed.
  12955. This function assumes point is on a headline."
  12956. (let ((tags (pcase tags
  12957. ((pred listp) tags)
  12958. ((pred stringp) (split-string (org-trim tags) ":" t))
  12959. (_ (error "Invalid tag specification: %S" tags))))
  12960. (change-flag nil))
  12961. (when (functionp org-tags-sort-function)
  12962. (setq tags (sort tags org-tags-sort-function)))
  12963. (org-with-wide-buffer
  12964. (unless (equal tags (org-get-tags nil t))
  12965. (setq change-flag t)
  12966. ;; Delete previous tags and any trailing white space.
  12967. (goto-char (if (looking-at org-tag-line-re) (match-beginning 1)
  12968. (line-end-position)))
  12969. (skip-chars-backward " \t")
  12970. (delete-region (point) (line-end-position))
  12971. (when tags
  12972. (save-excursion (insert " " (org-make-tag-string tags)))
  12973. ;; When text is being inserted on an invisible region
  12974. ;; boundary, it can be inadvertently sucked into
  12975. ;; invisibility.
  12976. (unless (org-invisible-p (line-beginning-position))
  12977. (org-flag-region (point) (line-end-position) nil 'outline))))
  12978. ;; Align tags, if any. Fix tags column if `org-indent-mode' is
  12979. ;; on.
  12980. (when tags (org-align-tags))
  12981. (when change-flag (run-hooks 'org-after-tags-change-hook)))))
  12982. (defun org-change-tag-in-region (beg end tag off)
  12983. "Add or remove TAG for each entry in the region.
  12984. This works in the agenda, and also in an Org buffer."
  12985. (interactive
  12986. (list (region-beginning) (region-end)
  12987. (let ((org-last-tags-completion-table
  12988. (if (derived-mode-p 'org-mode)
  12989. (org--tag-add-to-alist
  12990. (org-get-buffer-tags)
  12991. (org-global-tags-completion-table))
  12992. (org-global-tags-completion-table))))
  12993. (completing-read
  12994. "Tag: " 'org-tags-completion-function nil nil nil
  12995. 'org-tags-history))
  12996. (progn
  12997. (message "[s]et or [r]emove? ")
  12998. (equal (read-char-exclusive) ?r))))
  12999. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13000. (let ((agendap (equal major-mode 'org-agenda-mode))
  13001. l1 l2 m buf pos newhead (cnt 0))
  13002. (goto-char end)
  13003. (setq l2 (1- (org-current-line)))
  13004. (goto-char beg)
  13005. (setq l1 (org-current-line))
  13006. (cl-loop for l from l1 to l2 do
  13007. (org-goto-line l)
  13008. (setq m (get-text-property (point) 'org-hd-marker))
  13009. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13010. (and agendap m))
  13011. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13012. pos (if agendap m (point)))
  13013. (with-current-buffer buf
  13014. (save-excursion
  13015. (save-restriction
  13016. (goto-char pos)
  13017. (setq cnt (1+ cnt))
  13018. (org-toggle-tag tag (if off 'off 'on))
  13019. (setq newhead (org-get-heading)))))
  13020. (and agendap (org-agenda-change-all-lines newhead m))))
  13021. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13022. (defun org-tags-completion-function (string _predicate &optional flag)
  13023. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13024. (confirm (lambda (x) (stringp (car x)))))
  13025. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13026. (setq s1 (match-string 1 string)
  13027. s2 (match-string 2 string))
  13028. (setq s1 "" s2 string))
  13029. (cond
  13030. ((eq flag nil)
  13031. ;; try completion
  13032. (setq rtn (try-completion s2 ctable confirm))
  13033. (when (stringp rtn)
  13034. (setq rtn
  13035. (concat s1 s2 (substring rtn (length s2))
  13036. (if (and org-add-colon-after-tag-completion
  13037. (assoc rtn ctable))
  13038. ":" ""))))
  13039. rtn)
  13040. ((eq flag t)
  13041. ;; all-completions
  13042. (all-completions s2 ctable confirm))
  13043. ((eq flag 'lambda)
  13044. ;; exact match?
  13045. (assoc s2 ctable)))))
  13046. (defun org-fast-tag-insert (kwd tags face &optional end)
  13047. "Insert KDW, and the TAGS, the latter with face FACE.
  13048. Also insert END."
  13049. (insert (format "%-12s" (concat kwd ":"))
  13050. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13051. (or end "")))
  13052. (defun org-fast-tag-show-exit (flag)
  13053. (save-excursion
  13054. (org-goto-line 3)
  13055. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13056. (replace-match ""))
  13057. (when flag
  13058. (end-of-line 1)
  13059. (org-move-to-column (- (window-width) 19) t)
  13060. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13061. (defun org-set-current-tags-overlay (current prefix)
  13062. "Add an overlay to CURRENT tag with PREFIX."
  13063. (let ((s (org-make-tag-string current)))
  13064. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13065. (org-overlay-display org-tags-overlay (concat prefix s))))
  13066. (defvar org-last-tag-selection-key nil)
  13067. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13068. "Fast tag selection with single keys.
  13069. CURRENT is the current list of tags in the headline, INHERITED is the
  13070. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13071. possibly with grouping information. TODO-TABLE is a similar table with
  13072. TODO keywords, should these have keys assigned to them.
  13073. If the keys are nil, a-z are automatically assigned.
  13074. Returns the new tags string, or nil to not change the current settings."
  13075. (let* ((fulltable (append table todo-table))
  13076. (maxlen (if (null fulltable) 0
  13077. (apply #'max
  13078. (mapcar (lambda (x)
  13079. (if (stringp (car x)) (string-width (car x))
  13080. 0))
  13081. fulltable))))
  13082. (buf (current-buffer))
  13083. (expert (eq org-fast-tag-selection-single-key 'expert))
  13084. (buffer-tags nil)
  13085. (fwidth (+ maxlen 3 1 3))
  13086. (ncol (/ (- (window-width) 4) fwidth))
  13087. (i-face 'org-done)
  13088. (c-face 'org-todo)
  13089. tg cnt e c char c1 c2 ntable tbl rtn
  13090. ov-start ov-end ov-prefix
  13091. (exit-after-next org-fast-tag-selection-single-key)
  13092. (done-keywords org-done-keywords)
  13093. groups ingroup intaggroup)
  13094. (save-excursion
  13095. (beginning-of-line)
  13096. (if (looking-at org-tag-line-re)
  13097. (setq ov-start (match-beginning 1)
  13098. ov-end (match-end 1)
  13099. ov-prefix "")
  13100. (setq ov-start (1- (point-at-eol))
  13101. ov-end (1+ ov-start))
  13102. (skip-chars-forward "^\n\r")
  13103. (setq ov-prefix
  13104. (concat
  13105. (buffer-substring (1- (point)) (point))
  13106. (if (> (current-column) org-tags-column)
  13107. " "
  13108. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13109. (move-overlay org-tags-overlay ov-start ov-end)
  13110. (save-window-excursion
  13111. (if expert
  13112. (set-buffer (get-buffer-create " *Org tags*"))
  13113. (delete-other-windows)
  13114. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13115. (org-switch-to-buffer-other-window " *Org tags*"))
  13116. (erase-buffer)
  13117. (setq-local org-done-keywords done-keywords)
  13118. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13119. (org-fast-tag-insert "Current" current c-face "\n\n")
  13120. (org-fast-tag-show-exit exit-after-next)
  13121. (org-set-current-tags-overlay current ov-prefix)
  13122. (setq tbl fulltable char ?a cnt 0)
  13123. (while (setq e (pop tbl))
  13124. (cond
  13125. ((eq (car e) :startgroup)
  13126. (push '() groups) (setq ingroup t)
  13127. (unless (zerop cnt)
  13128. (setq cnt 0)
  13129. (insert "\n"))
  13130. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13131. ((eq (car e) :endgroup)
  13132. (setq ingroup nil cnt 0)
  13133. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13134. ((eq (car e) :startgrouptag)
  13135. (setq intaggroup t)
  13136. (unless (zerop cnt)
  13137. (setq cnt 0)
  13138. (insert "\n"))
  13139. (insert "[ "))
  13140. ((eq (car e) :endgrouptag)
  13141. (setq intaggroup nil cnt 0)
  13142. (insert "]\n"))
  13143. ((equal e '(:newline))
  13144. (unless (zerop cnt)
  13145. (setq cnt 0)
  13146. (insert "\n")
  13147. (setq e (car tbl))
  13148. (while (equal (car tbl) '(:newline))
  13149. (insert "\n")
  13150. (setq tbl (cdr tbl)))))
  13151. ((equal e '(:grouptags)) (insert " : "))
  13152. (t
  13153. (setq tg (copy-sequence (car e)) c2 nil)
  13154. (if (cdr e)
  13155. (setq c (cdr e))
  13156. ;; automatically assign a character.
  13157. (setq c1 (string-to-char
  13158. (downcase (substring
  13159. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13160. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13161. (while (or (rassoc char ntable) (rassoc char table))
  13162. (setq char (1+ char)))
  13163. (setq c2 c1))
  13164. (setq c (or c2 char)))
  13165. (when ingroup (push tg (car groups)))
  13166. (setq tg (org-add-props tg nil 'face
  13167. (cond
  13168. ((not (assoc tg table))
  13169. (org-get-todo-face tg))
  13170. ((member tg current) c-face)
  13171. ((member tg inherited) i-face))))
  13172. (when (equal (caar tbl) :grouptags)
  13173. (org-add-props tg nil 'face 'org-tag-group))
  13174. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13175. (insert "[" c "] " tg (make-string
  13176. (- fwidth 4 (length tg)) ?\ ))
  13177. (push (cons tg c) ntable)
  13178. (when (= (cl-incf cnt) ncol)
  13179. (insert "\n")
  13180. (when (or ingroup intaggroup) (insert " "))
  13181. (setq cnt 0)))))
  13182. (setq ntable (nreverse ntable))
  13183. (insert "\n")
  13184. (goto-char (point-min))
  13185. (unless expert (org-fit-window-to-buffer))
  13186. (setq rtn
  13187. (catch 'exit
  13188. (while t
  13189. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  13190. (if (not groups) "no " "")
  13191. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13192. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13193. (setq org-last-tag-selection-key c)
  13194. (cond
  13195. ((= c ?\r) (throw 'exit t))
  13196. ((= c ?!)
  13197. (setq groups (not groups))
  13198. (goto-char (point-min))
  13199. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13200. ((= c ?\C-c)
  13201. (if (not expert)
  13202. (org-fast-tag-show-exit
  13203. (setq exit-after-next (not exit-after-next)))
  13204. (setq expert nil)
  13205. (delete-other-windows)
  13206. (set-window-buffer (split-window-vertically) " *Org tags*")
  13207. (org-switch-to-buffer-other-window " *Org tags*")
  13208. (org-fit-window-to-buffer)))
  13209. ((or (= c ?\C-g)
  13210. (and (= c ?q) (not (rassoc c ntable))))
  13211. (delete-overlay org-tags-overlay)
  13212. (setq quit-flag t))
  13213. ((= c ?\ )
  13214. (setq current nil)
  13215. (when exit-after-next (setq exit-after-next 'now)))
  13216. ((= c ?\t)
  13217. (condition-case nil
  13218. (setq tg (completing-read
  13219. "Tag: "
  13220. (or buffer-tags
  13221. (with-current-buffer buf
  13222. (setq buffer-tags
  13223. (org-get-buffer-tags))))))
  13224. (quit (setq tg "")))
  13225. (when (string-match "\\S-" tg)
  13226. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13227. (if (member tg current)
  13228. (setq current (delete tg current))
  13229. (push tg current)))
  13230. (when exit-after-next (setq exit-after-next 'now)))
  13231. ((setq e (rassoc c todo-table) tg (car e))
  13232. (with-current-buffer buf
  13233. (save-excursion (org-todo tg)))
  13234. (when exit-after-next (setq exit-after-next 'now)))
  13235. ((setq e (rassoc c ntable) tg (car e))
  13236. (if (member tg current)
  13237. (setq current (delete tg current))
  13238. (cl-loop for g in groups do
  13239. (when (member tg g)
  13240. (dolist (x g) (setq current (delete x current)))))
  13241. (push tg current))
  13242. (when exit-after-next (setq exit-after-next 'now))))
  13243. ;; Create a sorted list
  13244. (setq current
  13245. (sort current
  13246. (lambda (a b)
  13247. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13248. (when (eq exit-after-next 'now) (throw 'exit t))
  13249. (goto-char (point-min))
  13250. (beginning-of-line 2)
  13251. (delete-region (point) (point-at-eol))
  13252. (org-fast-tag-insert "Current" current c-face)
  13253. (org-set-current-tags-overlay current ov-prefix)
  13254. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  13255. (while (re-search-forward tag-re nil t)
  13256. (let ((tag (match-string 1)))
  13257. (add-text-properties
  13258. (match-beginning 1) (match-end 1)
  13259. (list 'face
  13260. (cond
  13261. ((member tag current) c-face)
  13262. ((member tag inherited) i-face)
  13263. (t (get-text-property (match-beginning 1) '
  13264. face))))))))
  13265. (goto-char (point-min)))))
  13266. (delete-overlay org-tags-overlay)
  13267. (if rtn
  13268. (mapconcat 'identity current ":")
  13269. nil))))
  13270. (defun org-make-tag-string (tags)
  13271. "Return string associated to TAGS.
  13272. TAGS is a list of strings."
  13273. (if (null tags) ""
  13274. (format ":%s:" (mapconcat #'identity tags ":"))))
  13275. (defun org--get-local-tags ()
  13276. "Return list of tags for the current headline.
  13277. Assume point is at the beginning of the headline."
  13278. (and (looking-at org-tag-line-re)
  13279. (split-string (match-string-no-properties 2) ":" t)))
  13280. (defun org-get-tags (&optional pos local)
  13281. "Get the list of tags specified in the current headline.
  13282. When argument POS is non-nil, retrieve tags for headline at POS.
  13283. Accoring to `org-use-tags-inheritance', tags may be inherited
  13284. from parent headlines, and from the whole document, through
  13285. `org-file-tags'. However, when optional argument LOCAL is
  13286. non-nil, only return tags really specified in the considered
  13287. headline.
  13288. Inherited tags have the `inherited' text property."
  13289. (if (and org-trust-scanner-tags
  13290. (or (not pos) (eq pos (point)))
  13291. (not local))
  13292. org-scanner-tags
  13293. (org-with-point-at (or pos (point))
  13294. (unless (org-before-first-heading-p)
  13295. (org-back-to-heading t)
  13296. (let ((tags (org--get-local-tags)))
  13297. (if (or local (not org-use-tag-inheritance)) tags
  13298. (while (org-up-heading-safe)
  13299. (setq tags (append (mapcar #'org-add-prop-inherited
  13300. (org--get-local-tags))
  13301. tags)))
  13302. (org-remove-uninherited-tags
  13303. (delete-dups (append org-file-tags tags)))))))))
  13304. (defun org-get-buffer-tags ()
  13305. "Get a table of all tags used in the buffer, for completion."
  13306. (org-with-point-at 1
  13307. (let (tags)
  13308. (while (re-search-forward org-tag-line-re nil t)
  13309. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  13310. tags)))
  13311. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  13312. ;;;; The mapping API
  13313. (defvar org-agenda-skip-comment-trees)
  13314. (defvar org-agenda-skip-function)
  13315. (defun org-map-entries (func &optional match scope &rest skip)
  13316. "Call FUNC at each headline selected by MATCH in SCOPE.
  13317. FUNC is a function or a lisp form. The function will be called without
  13318. arguments, with the cursor positioned at the beginning of the headline.
  13319. The return values of all calls to the function will be collected and
  13320. returned as a list.
  13321. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13322. does not need to preserve point. After evaluation, the cursor will be
  13323. moved to the end of the line (presumably of the headline of the
  13324. processed entry) and search continues from there. Under some
  13325. circumstances, this may not produce the wanted results. For example,
  13326. if you have removed (e.g. archived) the current (sub)tree it could
  13327. mean that the next entry will be skipped entirely. In such cases, you
  13328. can specify the position from where search should continue by making
  13329. FUNC set the variable `org-map-continue-from' to the desired buffer
  13330. position.
  13331. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13332. Only headlines that are matched by this query will be considered during
  13333. the iteration. When MATCH is nil or t, all headlines will be
  13334. visited by the iteration.
  13335. SCOPE determines the scope of this command. It can be any of:
  13336. nil The current buffer, respecting the restriction if any
  13337. tree The subtree started with the entry at point
  13338. region The entries within the active region, if any
  13339. region-start-level
  13340. The entries within the active region, but only those at
  13341. the same level than the first one.
  13342. file The current buffer, without restriction
  13343. file-with-archives
  13344. The current buffer, and any archives associated with it
  13345. agenda All agenda files
  13346. agenda-with-archives
  13347. All agenda files with any archive files associated with them
  13348. \(file1 file2 ...)
  13349. If this is a list, all files in the list will be scanned
  13350. The remaining args are treated as settings for the skipping facilities of
  13351. the scanner. The following items can be given here:
  13352. archive skip trees with the archive tag
  13353. comment skip trees with the COMMENT keyword
  13354. function or Emacs Lisp form:
  13355. will be used as value for `org-agenda-skip-function', so
  13356. whenever the function returns a position, FUNC will not be
  13357. called for that entry and search will continue from the
  13358. position returned
  13359. If your function needs to retrieve the tags including inherited tags
  13360. at the *current* entry, you can use the value of the variable
  13361. `org-scanner-tags' which will be much faster than getting the value
  13362. with `org-get-tags'. If your function gets properties with
  13363. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  13364. to t around the call to `org-entry-properties' to get the same speedup.
  13365. Note that if your function moves around to retrieve tags and properties at
  13366. a *different* entry, you cannot use these techniques."
  13367. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  13368. (not (org-region-active-p)))
  13369. (let* ((org-agenda-archives-mode nil) ; just to make sure
  13370. (org-agenda-skip-archived-trees (memq 'archive skip))
  13371. (org-agenda-skip-comment-trees (memq 'comment skip))
  13372. (org-agenda-skip-function
  13373. (car (org-delete-all '(comment archive) skip)))
  13374. (org-tags-match-list-sublevels t)
  13375. (start-level (eq scope 'region-start-level))
  13376. matcher res
  13377. org-todo-keywords-for-agenda
  13378. org-done-keywords-for-agenda
  13379. org-todo-keyword-alist-for-agenda
  13380. org-tag-alist-for-agenda
  13381. org--matcher-tags-todo-only)
  13382. (cond
  13383. ((eq match t) (setq matcher t))
  13384. ((eq match nil) (setq matcher t))
  13385. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  13386. (save-excursion
  13387. (save-restriction
  13388. (cond ((eq scope 'tree)
  13389. (org-back-to-heading t)
  13390. (org-narrow-to-subtree)
  13391. (setq scope nil))
  13392. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  13393. (org-region-active-p))
  13394. ;; If needed, set start-level to a string like "2"
  13395. (when start-level
  13396. (save-excursion
  13397. (goto-char (region-beginning))
  13398. (unless (org-at-heading-p) (outline-next-heading))
  13399. (setq start-level (org-current-level))))
  13400. (narrow-to-region (region-beginning)
  13401. (save-excursion
  13402. (goto-char (region-end))
  13403. (unless (and (bolp) (org-at-heading-p))
  13404. (outline-next-heading))
  13405. (point)))
  13406. (setq scope nil)))
  13407. (if (not scope)
  13408. (progn
  13409. (org-agenda-prepare-buffers
  13410. (and buffer-file-name (list buffer-file-name)))
  13411. (setq res
  13412. (org-scan-tags
  13413. func matcher org--matcher-tags-todo-only start-level)))
  13414. ;; Get the right scope
  13415. (cond
  13416. ((and scope (listp scope) (symbolp (car scope)))
  13417. (setq scope (eval scope)))
  13418. ((eq scope 'agenda)
  13419. (setq scope (org-agenda-files t)))
  13420. ((eq scope 'agenda-with-archives)
  13421. (setq scope (org-agenda-files t))
  13422. (setq scope (org-add-archive-files scope)))
  13423. ((eq scope 'file)
  13424. (setq scope (and buffer-file-name (list buffer-file-name))))
  13425. ((eq scope 'file-with-archives)
  13426. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  13427. (org-agenda-prepare-buffers scope)
  13428. (dolist (file scope)
  13429. (with-current-buffer (org-find-base-buffer-visiting file)
  13430. (org-with-wide-buffer
  13431. (goto-char (point-min))
  13432. (setq res
  13433. (append
  13434. res
  13435. (org-scan-tags
  13436. func matcher org--matcher-tags-todo-only)))))))))
  13437. res)))
  13438. ;;; Properties API
  13439. (defconst org-special-properties
  13440. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  13441. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  13442. "The special properties valid in Org mode.
  13443. These are properties that are not defined in the property drawer,
  13444. but in some other way.")
  13445. (defconst org-default-properties
  13446. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  13447. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  13448. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  13449. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  13450. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  13451. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  13452. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  13453. "Some properties that are used by Org mode for various purposes.
  13454. Being in this list makes sure that they are offered for completion.")
  13455. (defun org--valid-property-p (property)
  13456. "Non nil when string PROPERTY is a valid property name."
  13457. (not
  13458. (or (equal property "")
  13459. (string-match-p "\\s-" property))))
  13460. (defun org--update-property-plist (key val props)
  13461. "Associate KEY to VAL in alist PROPS.
  13462. Modifications are made by side-effect. Return new alist."
  13463. (let* ((appending (string= (substring key -1) "+"))
  13464. (key (if appending (substring key 0 -1) key))
  13465. (old (assoc-string key props t)))
  13466. (if (not old) (cons (cons key val) props)
  13467. (setcdr old (if appending (concat (cdr old) " " val) val))
  13468. props)))
  13469. (defun org-get-property-block (&optional beg force)
  13470. "Return the (beg . end) range of the body of the property drawer.
  13471. BEG is the beginning of the current subtree, or of the part
  13472. before the first headline. If it is not given, it will be found.
  13473. If the drawer does not exist, create it if FORCE is non-nil, or
  13474. return nil."
  13475. (org-with-wide-buffer
  13476. (when beg (goto-char beg))
  13477. (unless (org-before-first-heading-p)
  13478. (let ((beg (cond (beg)
  13479. ((or (not (featurep 'org-inlinetask))
  13480. (org-inlinetask-in-task-p))
  13481. (org-back-to-heading t))
  13482. (t (org-with-limited-levels (org-back-to-heading t))))))
  13483. (forward-line)
  13484. (when (looking-at-p org-planning-line-re) (forward-line))
  13485. (cond ((looking-at org-property-drawer-re)
  13486. (forward-line)
  13487. (cons (point) (progn (goto-char (match-end 0))
  13488. (line-beginning-position))))
  13489. (force
  13490. (goto-char beg)
  13491. (org-insert-property-drawer)
  13492. (let ((pos (save-excursion (search-forward ":END:")
  13493. (line-beginning-position))))
  13494. (cons pos pos))))))))
  13495. (defun org-at-property-p ()
  13496. "Non-nil when point is inside a property drawer.
  13497. See `org-property-re' for match data, if applicable."
  13498. (save-excursion
  13499. (beginning-of-line)
  13500. (and (looking-at org-property-re)
  13501. (let ((property-drawer (save-match-data (org-get-property-block))))
  13502. (and property-drawer
  13503. (>= (point) (car property-drawer))
  13504. (< (point) (cdr property-drawer)))))))
  13505. (defun org-property-action ()
  13506. "Do an action on properties."
  13507. (interactive)
  13508. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  13509. (let ((c (read-char-exclusive)))
  13510. (cl-case c
  13511. (?s (call-interactively #'org-set-property))
  13512. (?d (call-interactively #'org-delete-property))
  13513. (?D (call-interactively #'org-delete-property-globally))
  13514. (?c (call-interactively #'org-compute-property-at-point))
  13515. (otherwise (user-error "No such property action %c" c)))))
  13516. (defun org-inc-effort ()
  13517. "Increment the value of the effort property in the current entry."
  13518. (interactive)
  13519. (org-set-effort t))
  13520. (defvar org-clock-effort) ; Defined in org-clock.el.
  13521. (defvar org-clock-current-task) ; Defined in org-clock.el.
  13522. (defun org-set-effort (&optional increment value)
  13523. "Set the effort property of the current entry.
  13524. If INCREMENT is non-nil, set the property to the next allowed
  13525. value. Otherwise, if optional argument VALUE is provided, use
  13526. it. Eventually, prompt for the new value if none of the previous
  13527. variables is set."
  13528. (interactive "P")
  13529. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  13530. (current (org-entry-get nil org-effort-property))
  13531. (value
  13532. (cond
  13533. (increment
  13534. (unless allowed (user-error "Allowed effort values are not set"))
  13535. (or (cl-caadr (member (list current) allowed))
  13536. (user-error "Unknown value %S among allowed values" current)))
  13537. (value
  13538. (if (stringp value) value
  13539. (error "Invalid effort value: %S" value)))
  13540. (t
  13541. (let ((must-match
  13542. (and allowed
  13543. (not (get-text-property 0 'org-unrestricted
  13544. (caar allowed))))))
  13545. (completing-read "Effort: " allowed nil must-match))))))
  13546. (unless (equal current value)
  13547. (org-entry-put nil org-effort-property value))
  13548. (org-refresh-property '((effort . identity)
  13549. (effort-minutes . org-duration-to-minutes))
  13550. value)
  13551. (when (equal (org-get-heading t t t t)
  13552. (bound-and-true-p org-clock-current-task))
  13553. (setq org-clock-effort (org-get-at-bol 'effort))
  13554. (org-clock-update-mode-line))
  13555. (message "%s is now %s" org-effort-property value)))
  13556. (defun org-entry-properties (&optional pom which)
  13557. "Get all properties of the current entry.
  13558. When POM is a buffer position, get all properties from the entry
  13559. there instead.
  13560. This includes the TODO keyword, the tags, time strings for
  13561. deadline, scheduled, and clocking, and any additional properties
  13562. defined in the entry.
  13563. If WHICH is nil or `all', get all properties. If WHICH is
  13564. `special' or `standard', only get that subclass. If WHICH is
  13565. a string, only get that property.
  13566. Return value is an alist. Keys are properties, as upcased
  13567. strings."
  13568. (org-with-point-at pom
  13569. (when (and (derived-mode-p 'org-mode)
  13570. (ignore-errors (org-back-to-heading t)))
  13571. (catch 'exit
  13572. (let* ((beg (point))
  13573. (specific (and (stringp which) (upcase which)))
  13574. (which (cond ((not specific) which)
  13575. ((member specific org-special-properties) 'special)
  13576. (t 'standard)))
  13577. props)
  13578. ;; Get the special properties, like TODO and TAGS.
  13579. (when (memq which '(nil all special))
  13580. (when (or (not specific) (string= specific "CLOCKSUM"))
  13581. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  13582. (when clocksum
  13583. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  13584. props)))
  13585. (when specific (throw 'exit props)))
  13586. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  13587. (let ((clocksumt (get-text-property (point)
  13588. :org-clock-minutes-today)))
  13589. (when clocksumt
  13590. (push (cons "CLOCKSUM_T"
  13591. (org-duration-from-minutes clocksumt))
  13592. props)))
  13593. (when specific (throw 'exit props)))
  13594. (when (or (not specific) (string= specific "ITEM"))
  13595. (let ((case-fold-search nil))
  13596. (when (looking-at org-complex-heading-regexp)
  13597. (push (cons "ITEM"
  13598. (let ((title (match-string-no-properties 4)))
  13599. (if (org-string-nw-p title)
  13600. (org-remove-tabs title)
  13601. "")))
  13602. props)))
  13603. (when specific (throw 'exit props)))
  13604. (when (or (not specific) (string= specific "TODO"))
  13605. (let ((case-fold-search nil))
  13606. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  13607. (push (cons "TODO" (match-string-no-properties 2)) props)))
  13608. (when specific (throw 'exit props)))
  13609. (when (or (not specific) (string= specific "PRIORITY"))
  13610. (push (cons "PRIORITY"
  13611. (if (looking-at org-priority-regexp)
  13612. (match-string-no-properties 2)
  13613. (char-to-string org-default-priority)))
  13614. props)
  13615. (when specific (throw 'exit props)))
  13616. (when (or (not specific) (string= specific "FILE"))
  13617. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  13618. props)
  13619. (when specific (throw 'exit props)))
  13620. (when (or (not specific) (string= specific "TAGS"))
  13621. (let ((tags (org-get-tags nil t)))
  13622. (when tags
  13623. (push (cons "TAGS" (org-make-tag-string tags))
  13624. props)))
  13625. (when specific (throw 'exit props)))
  13626. (when (or (not specific) (string= specific "ALLTAGS"))
  13627. (let ((tags (org-get-tags)))
  13628. (when tags
  13629. (push (cons "ALLTAGS" (org-make-tag-string tags))
  13630. props)))
  13631. (when specific (throw 'exit props)))
  13632. (when (or (not specific) (string= specific "BLOCKED"))
  13633. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  13634. (when specific (throw 'exit props)))
  13635. (when (or (not specific)
  13636. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  13637. (forward-line)
  13638. (when (looking-at-p org-planning-line-re)
  13639. (end-of-line)
  13640. (let ((bol (line-beginning-position))
  13641. ;; Backward compatibility: time keywords used to
  13642. ;; be configurable (before 8.3). Make sure we
  13643. ;; get the correct keyword.
  13644. (key-assoc `(("CLOSED" . ,org-closed-string)
  13645. ("DEADLINE" . ,org-deadline-string)
  13646. ("SCHEDULED" . ,org-scheduled-string))))
  13647. (dolist (pair (if specific (list (assoc specific key-assoc))
  13648. key-assoc))
  13649. (save-excursion
  13650. (when (search-backward (cdr pair) bol t)
  13651. (goto-char (match-end 0))
  13652. (skip-chars-forward " \t")
  13653. (and (looking-at org-ts-regexp-both)
  13654. (push (cons (car pair)
  13655. (match-string-no-properties 0))
  13656. props)))))))
  13657. (when specific (throw 'exit props)))
  13658. (when (or (not specific)
  13659. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  13660. (let ((find-ts
  13661. (lambda (end ts)
  13662. ;; Fix next time-stamp before END. TS is the
  13663. ;; list of time-stamps found so far.
  13664. (let ((ts ts)
  13665. (regexp (cond
  13666. ((string= specific "TIMESTAMP")
  13667. org-ts-regexp)
  13668. ((string= specific "TIMESTAMP_IA")
  13669. org-ts-regexp-inactive)
  13670. ((assoc "TIMESTAMP_IA" ts)
  13671. org-ts-regexp)
  13672. ((assoc "TIMESTAMP" ts)
  13673. org-ts-regexp-inactive)
  13674. (t org-ts-regexp-both))))
  13675. (catch 'next
  13676. (while (re-search-forward regexp end t)
  13677. (backward-char)
  13678. (let ((object (org-element-context)))
  13679. ;; Accept to match timestamps in node
  13680. ;; properties, too.
  13681. (when (memq (org-element-type object)
  13682. '(node-property timestamp))
  13683. (let ((type
  13684. (org-element-property :type object)))
  13685. (cond
  13686. ((and (memq type '(active active-range))
  13687. (not (equal specific "TIMESTAMP_IA")))
  13688. (unless (assoc "TIMESTAMP" ts)
  13689. (push (cons "TIMESTAMP"
  13690. (org-element-property
  13691. :raw-value object))
  13692. ts)
  13693. (when specific (throw 'exit ts))))
  13694. ((and (memq type '(inactive inactive-range))
  13695. (not (string= specific "TIMESTAMP")))
  13696. (unless (assoc "TIMESTAMP_IA" ts)
  13697. (push (cons "TIMESTAMP_IA"
  13698. (org-element-property
  13699. :raw-value object))
  13700. ts)
  13701. (when specific (throw 'exit ts))))))
  13702. ;; Both timestamp types are found,
  13703. ;; move to next part.
  13704. (when (= (length ts) 2) (throw 'next ts)))))
  13705. ts)))))
  13706. (goto-char beg)
  13707. ;; First look for timestamps within headline.
  13708. (let ((ts (funcall find-ts (line-end-position) nil)))
  13709. (if (= (length ts) 2) (setq props (nconc ts props))
  13710. ;; Then find timestamps in the section, skipping
  13711. ;; planning line.
  13712. (let ((end (save-excursion (outline-next-heading))))
  13713. (forward-line)
  13714. (when (looking-at-p org-planning-line-re) (forward-line))
  13715. (setq props (nconc (funcall find-ts end ts) props))))))))
  13716. ;; Get the standard properties, like :PROP:.
  13717. (when (memq which '(nil all standard))
  13718. ;; If we are looking after a specific property, delegate
  13719. ;; to `org-entry-get', which is faster. However, make an
  13720. ;; exception for "CATEGORY", since it can be also set
  13721. ;; through keywords (i.e. #+CATEGORY).
  13722. (if (and specific (not (equal specific "CATEGORY")))
  13723. (let ((value (org-entry-get beg specific nil t)))
  13724. (throw 'exit (and value (list (cons specific value)))))
  13725. (let ((range (org-get-property-block beg)))
  13726. (when range
  13727. (let ((end (cdr range)) seen-base)
  13728. (goto-char (car range))
  13729. ;; Unlike to `org--update-property-plist', we
  13730. ;; handle the case where base values is found
  13731. ;; after its extension. We also forbid standard
  13732. ;; properties to be named as special properties.
  13733. (while (re-search-forward org-property-re end t)
  13734. (let* ((key (upcase (match-string-no-properties 2)))
  13735. (extendp (string-match-p "\\+\\'" key))
  13736. (key-base (if extendp (substring key 0 -1) key))
  13737. (value (match-string-no-properties 3)))
  13738. (cond
  13739. ((member-ignore-case key-base org-special-properties))
  13740. (extendp
  13741. (setq props
  13742. (org--update-property-plist key value props)))
  13743. ((member key seen-base))
  13744. (t (push key seen-base)
  13745. (let ((p (assoc-string key props t)))
  13746. (if p (setcdr p (concat value " " (cdr p)))
  13747. (push (cons key value) props))))))))))))
  13748. (unless (assoc "CATEGORY" props)
  13749. (push (cons "CATEGORY" (org-get-category beg)) props)
  13750. (when (string= specific "CATEGORY") (throw 'exit props)))
  13751. ;; Return value.
  13752. props)))))
  13753. (defun org--property-local-values (property literal-nil)
  13754. "Return value for PROPERTY in current entry.
  13755. Value is a list whose car is the base value for PROPERTY and cdr
  13756. a list of accumulated values. Return nil if neither is found in
  13757. the entry. Also return nil when PROPERTY is set to \"nil\",
  13758. unless LITERAL-NIL is non-nil."
  13759. (let ((range (org-get-property-block)))
  13760. (when range
  13761. (goto-char (car range))
  13762. (let* ((case-fold-search t)
  13763. (end (cdr range))
  13764. (value
  13765. ;; Base value.
  13766. (save-excursion
  13767. (let ((v (and (re-search-forward
  13768. (org-re-property property nil t) end t)
  13769. (match-string-no-properties 3))))
  13770. (list (if literal-nil v (org-not-nil v)))))))
  13771. ;; Find additional values.
  13772. (let* ((property+ (org-re-property (concat property "+") nil t)))
  13773. (while (re-search-forward property+ end t)
  13774. (push (match-string-no-properties 3) value)))
  13775. ;; Return final values.
  13776. (and (not (equal value '(nil))) (nreverse value))))))
  13777. (defun org--property-global-value (property literal-nil)
  13778. "Return value for PROPERTY in current buffer.
  13779. Return value is a string. Return nil if property is not set
  13780. globally. Also return nil when PROPERTY is set to \"nil\",
  13781. unless LITERAL-NIL is non-nil."
  13782. (let ((global
  13783. (cdr (or (assoc-string property org-file-properties t)
  13784. (assoc-string property org-global-properties t)
  13785. (assoc-string property org-global-properties-fixed t)))))
  13786. (if literal-nil global (org-not-nil global))))
  13787. (defun org-entry-get (pom property &optional inherit literal-nil)
  13788. "Get value of PROPERTY for entry or content at point-or-marker POM.
  13789. If INHERIT is non-nil and the entry does not have the property,
  13790. then also check higher levels of the hierarchy. If INHERIT is
  13791. the symbol `selective', use inheritance only if the setting in
  13792. `org-use-property-inheritance' selects PROPERTY for inheritance.
  13793. If the property is present but empty, the return value is the
  13794. empty string. If the property is not present at all, nil is
  13795. returned. In any other case, return the value as a string.
  13796. Search is case-insensitive.
  13797. If LITERAL-NIL is set, return the string value \"nil\" as
  13798. a string, do not interpret it as the list atom nil. This is used
  13799. for inheritance when a \"nil\" value can supersede a non-nil
  13800. value higher up the hierarchy."
  13801. (org-with-point-at pom
  13802. (cond
  13803. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  13804. ;; We need a special property. Use `org-entry-properties' to
  13805. ;; retrieve it, but specify the wanted property.
  13806. (cdr (assoc-string property (org-entry-properties nil property))))
  13807. ((and inherit
  13808. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  13809. (org-entry-get-with-inheritance property literal-nil))
  13810. (t
  13811. (let* ((local (org--property-local-values property literal-nil))
  13812. (value (and local (mapconcat #'identity (delq nil local) " "))))
  13813. (if literal-nil value (org-not-nil value)))))))
  13814. (defun org-property-or-variable-value (var &optional inherit)
  13815. "Check if there is a property fixing the value of VAR.
  13816. If yes, return this value. If not, return the current value of the variable."
  13817. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  13818. (if (and prop (stringp prop) (string-match "\\S-" prop))
  13819. (read prop)
  13820. (symbol-value var))))
  13821. (defun org-entry-delete (pom property)
  13822. "Delete PROPERTY from entry at point-or-marker POM.
  13823. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  13824. non-nil when a property was removed."
  13825. (org-with-point-at pom
  13826. (pcase (org-get-property-block)
  13827. (`(,begin . ,origin)
  13828. (let* ((end (copy-marker origin))
  13829. (re (org-re-property
  13830. (concat (regexp-quote property) "\\+?") t t)))
  13831. (goto-char begin)
  13832. (while (re-search-forward re end t)
  13833. (delete-region (match-beginning 0) (line-beginning-position 2)))
  13834. ;; If drawer is empty, remove it altogether.
  13835. (when (= begin end)
  13836. (delete-region (line-beginning-position 0)
  13837. (line-beginning-position 2)))
  13838. ;; Return non-nil if some property was removed.
  13839. (prog1 (/= end origin) (set-marker end nil))))
  13840. (_ nil))))
  13841. ;; Multi-values properties are properties that contain multiple values
  13842. ;; These values are assumed to be single words, separated by whitespace.
  13843. (defun org-entry-add-to-multivalued-property (pom property value)
  13844. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  13845. (let* ((old (org-entry-get pom property))
  13846. (values (and old (split-string old))))
  13847. (setq value (org-entry-protect-space value))
  13848. (unless (member value values)
  13849. (setq values (append values (list value)))
  13850. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13851. (defun org-entry-remove-from-multivalued-property (pom property value)
  13852. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  13853. (let* ((old (org-entry-get pom property))
  13854. (values (and old (split-string old))))
  13855. (setq value (org-entry-protect-space value))
  13856. (when (member value values)
  13857. (setq values (delete value values))
  13858. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13859. (defun org-entry-member-in-multivalued-property (pom property value)
  13860. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  13861. (let* ((old (org-entry-get pom property))
  13862. (values (and old (split-string old))))
  13863. (setq value (org-entry-protect-space value))
  13864. (member value values)))
  13865. (defun org-entry-get-multivalued-property (pom property)
  13866. "Return a list of values in a multivalued property."
  13867. (let* ((value (org-entry-get pom property))
  13868. (values (and value (split-string value))))
  13869. (mapcar #'org-entry-restore-space values)))
  13870. (defun org-entry-put-multivalued-property (pom property &rest values)
  13871. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  13872. VALUES should be a list of strings. Spaces will be protected."
  13873. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  13874. (let* ((value (org-entry-get pom property))
  13875. (values (and value (split-string value))))
  13876. (mapcar #'org-entry-restore-space values)))
  13877. (defun org-entry-protect-space (s)
  13878. "Protect spaces and newline in string S."
  13879. (while (string-match " " s)
  13880. (setq s (replace-match "%20" t t s)))
  13881. (while (string-match "\n" s)
  13882. (setq s (replace-match "%0A" t t s)))
  13883. s)
  13884. (defun org-entry-restore-space (s)
  13885. "Restore spaces and newline in string S."
  13886. (while (string-match "%20" s)
  13887. (setq s (replace-match " " t t s)))
  13888. (while (string-match "%0A" s)
  13889. (setq s (replace-match "\n" t t s)))
  13890. s)
  13891. (defvar org-entry-property-inherited-from (make-marker)
  13892. "Marker pointing to the entry from where a property was inherited.
  13893. Each call to `org-entry-get-with-inheritance' will set this marker to the
  13894. location of the entry where the inheritance search matched. If there was
  13895. no match, the marker will point nowhere.
  13896. Note that also `org-entry-get' calls this function, if the INHERIT flag
  13897. is set.")
  13898. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  13899. "Get PROPERTY of entry or content at point, search higher levels if needed.
  13900. The search will stop at the first ancestor which has the property defined.
  13901. If the value found is \"nil\", return nil to show that the property
  13902. should be considered as undefined (this is the meaning of nil here).
  13903. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  13904. (move-marker org-entry-property-inherited-from nil)
  13905. (org-with-wide-buffer
  13906. (let (value)
  13907. (catch 'exit
  13908. (while t
  13909. (let ((v (org--property-local-values property literal-nil)))
  13910. (when v
  13911. (setq value
  13912. (concat (mapconcat #'identity (delq nil v) " ")
  13913. (and value " ")
  13914. value)))
  13915. (cond
  13916. ((car v)
  13917. (org-back-to-heading t)
  13918. (move-marker org-entry-property-inherited-from (point))
  13919. (throw 'exit nil))
  13920. ((org-up-heading-safe))
  13921. (t
  13922. (let ((global (org--property-global-value property literal-nil)))
  13923. (cond ((not global))
  13924. (value (setq value (concat global " " value)))
  13925. (t (setq value global))))
  13926. (throw 'exit nil))))))
  13927. (if literal-nil value (org-not-nil value)))))
  13928. (defvar org-property-changed-functions nil
  13929. "Hook called when the value of a property has changed.
  13930. Each hook function should accept two arguments, the name of the property
  13931. and the new value.")
  13932. (defun org-entry-put (pom property value)
  13933. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  13934. If the value is nil, it is converted to the empty string. If it
  13935. is not a string, an error is raised. Also raise an error on
  13936. invalid property names.
  13937. PROPERTY can be any regular property (see
  13938. `org-special-properties'). It can also be \"TODO\",
  13939. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  13940. For the last two properties, VALUE may have any of the special
  13941. values \"earlier\" and \"later\". The function then increases or
  13942. decreases scheduled or deadline date by one day."
  13943. (cond ((null value) (setq value ""))
  13944. ((not (stringp value)) (error "Properties values should be strings"))
  13945. ((not (org--valid-property-p property))
  13946. (user-error "Invalid property name: \"%s\"" property)))
  13947. (org-with-point-at pom
  13948. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  13949. (org-back-to-heading t)
  13950. (org-with-limited-levels (org-back-to-heading t)))
  13951. (let ((beg (point)))
  13952. (cond
  13953. ((equal property "TODO")
  13954. (cond ((not (org-string-nw-p value)) (setq value 'none))
  13955. ((not (member value org-todo-keywords-1))
  13956. (user-error "\"%s\" is not a valid TODO state" value)))
  13957. (org-todo value)
  13958. (org-align-tags))
  13959. ((equal property "PRIORITY")
  13960. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  13961. (org-align-tags))
  13962. ((equal property "SCHEDULED")
  13963. (forward-line)
  13964. (if (and (looking-at-p org-planning-line-re)
  13965. (re-search-forward
  13966. org-scheduled-time-regexp (line-end-position) t))
  13967. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  13968. ((string= value "later") (org-timestamp-change 1 'day))
  13969. ((string= value "") (org-schedule '(4)))
  13970. (t (org-schedule nil value)))
  13971. (if (member value '("earlier" "later" ""))
  13972. (call-interactively #'org-schedule)
  13973. (org-schedule nil value))))
  13974. ((equal property "DEADLINE")
  13975. (forward-line)
  13976. (if (and (looking-at-p org-planning-line-re)
  13977. (re-search-forward
  13978. org-deadline-time-regexp (line-end-position) t))
  13979. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  13980. ((string= value "later") (org-timestamp-change 1 'day))
  13981. ((string= value "") (org-deadline '(4)))
  13982. (t (org-deadline nil value)))
  13983. (if (member value '("earlier" "later" ""))
  13984. (call-interactively #'org-deadline)
  13985. (org-deadline nil value))))
  13986. ((member property org-special-properties)
  13987. (error "The %s property cannot be set with `org-entry-put'" property))
  13988. (t
  13989. (let* ((range (org-get-property-block beg 'force))
  13990. (end (cdr range))
  13991. (case-fold-search t))
  13992. (goto-char (car range))
  13993. (if (re-search-forward (org-re-property property nil t) end t)
  13994. (progn (delete-region (match-beginning 0) (match-end 0))
  13995. (goto-char (match-beginning 0)))
  13996. (goto-char end)
  13997. (insert "\n")
  13998. (backward-char))
  13999. (insert ":" property ":")
  14000. (when value (insert " " value))
  14001. (org-indent-line)))))
  14002. (run-hook-with-args 'org-property-changed-functions property value)))
  14003. (defun org-buffer-property-keys (&optional specials defaults columns)
  14004. "Get all property keys in the current buffer.
  14005. When SPECIALS is non-nil, also list the special properties that
  14006. reflect things like tags and TODO state.
  14007. When DEFAULTS is non-nil, also include properties that has
  14008. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14009. DESCRIPTION, LOCATION, and LOGGING and others.
  14010. When COLUMNS in non-nil, also include property names given in
  14011. COLUMN formats in the current buffer."
  14012. (let ((case-fold-search t)
  14013. (props (append
  14014. (and specials org-special-properties)
  14015. (and defaults (cons org-effort-property org-default-properties))
  14016. nil)))
  14017. (org-with-wide-buffer
  14018. (goto-char (point-min))
  14019. (while (re-search-forward org-property-start-re nil t)
  14020. (catch :skip
  14021. (let ((range (org-get-property-block)))
  14022. (unless range (throw :skip nil))
  14023. (goto-char (car range))
  14024. (let ((begin (car range))
  14025. (end (cdr range)))
  14026. ;; Make sure that found property block is not located
  14027. ;; before current point, as it would generate an infloop.
  14028. ;; It can happen, for example, in the following
  14029. ;; situation:
  14030. ;;
  14031. ;; * Headline
  14032. ;; :PROPERTIES:
  14033. ;; ...
  14034. ;; :END:
  14035. ;; *************** Inlinetask
  14036. ;; #+BEGIN_EXAMPLE
  14037. ;; :PROPERTIES:
  14038. ;; #+END_EXAMPLE
  14039. ;;
  14040. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  14041. (while (< (point) end)
  14042. (let ((p (progn (looking-at org-property-re)
  14043. (match-string-no-properties 2))))
  14044. ;; Only add true property name, not extension symbol.
  14045. (push (if (not (string-match-p "\\+\\'" p)) p
  14046. (substring p 0 -1))
  14047. props))
  14048. (forward-line))))
  14049. (outline-next-heading)))
  14050. (when columns
  14051. (goto-char (point-min))
  14052. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14053. (let ((element (org-element-at-point)))
  14054. (when (memq (org-element-type element) '(keyword node-property))
  14055. (let ((value (org-element-property :value element))
  14056. (start 0))
  14057. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  14058. \\(?:{[^}]+}\\)?"
  14059. value start)
  14060. (setq start (match-end 0))
  14061. (let ((p (match-string-no-properties 1 value)))
  14062. (unless (member-ignore-case p org-special-properties)
  14063. (push p props))))))))))
  14064. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14065. (defun org-property-values (key)
  14066. "List all non-nil values of property KEY in current buffer."
  14067. (org-with-wide-buffer
  14068. (goto-char (point-min))
  14069. (let ((case-fold-search t)
  14070. (re (org-re-property key))
  14071. values)
  14072. (while (re-search-forward re nil t)
  14073. (push (org-entry-get (point) key) values))
  14074. (delete-dups values))))
  14075. (defun org-insert-property-drawer ()
  14076. "Insert a property drawer into the current entry."
  14077. (org-with-wide-buffer
  14078. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14079. (org-back-to-heading t)
  14080. (org-with-limited-levels (org-back-to-heading t)))
  14081. (forward-line)
  14082. (when (looking-at-p org-planning-line-re) (forward-line))
  14083. (unless (looking-at-p org-property-drawer-re)
  14084. ;; Make sure we start editing a line from current entry, not from
  14085. ;; next one. It prevents extending text properties or overlays
  14086. ;; belonging to the latter.
  14087. (when (bolp) (backward-char))
  14088. (let ((begin (1+ (point)))
  14089. (inhibit-read-only t))
  14090. (insert "\n:PROPERTIES:\n:END:")
  14091. (when (eobp) (insert "\n"))
  14092. (org-indent-region begin (point))))))
  14093. (defun org-insert-drawer (&optional arg drawer)
  14094. "Insert a drawer at point.
  14095. When optional argument ARG is non-nil, insert a property drawer.
  14096. Optional argument DRAWER, when non-nil, is a string representing
  14097. drawer's name. Otherwise, the user is prompted for a name.
  14098. If a region is active, insert the drawer around that region
  14099. instead.
  14100. Point is left between drawer's boundaries."
  14101. (interactive "P")
  14102. (let* ((drawer (if arg "PROPERTIES"
  14103. (or drawer (read-from-minibuffer "Drawer: ")))))
  14104. (cond
  14105. ;; With C-u, fall back on `org-insert-property-drawer'
  14106. (arg (org-insert-property-drawer))
  14107. ;; Check validity of suggested drawer's name.
  14108. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14109. (user-error "Invalid drawer name"))
  14110. ;; With an active region, insert a drawer at point.
  14111. ((not (org-region-active-p))
  14112. (progn
  14113. (unless (bolp) (insert "\n"))
  14114. (insert (format ":%s:\n\n:END:\n" drawer))
  14115. (forward-line -2)))
  14116. ;; Otherwise, insert the drawer at point
  14117. (t
  14118. (let ((rbeg (region-beginning))
  14119. (rend (copy-marker (region-end))))
  14120. (unwind-protect
  14121. (progn
  14122. (goto-char rbeg)
  14123. (beginning-of-line)
  14124. (when (save-excursion
  14125. (re-search-forward org-outline-regexp-bol rend t))
  14126. (user-error "Drawers cannot contain headlines"))
  14127. ;; Position point at the beginning of the first
  14128. ;; non-blank line in region. Insert drawer's opening
  14129. ;; there, then indent it.
  14130. (org-skip-whitespace)
  14131. (beginning-of-line)
  14132. (insert ":" drawer ":\n")
  14133. (forward-line -1)
  14134. (indent-for-tab-command)
  14135. ;; Move point to the beginning of the first blank line
  14136. ;; after the last non-blank line in region. Insert
  14137. ;; drawer's closing, then indent it.
  14138. (goto-char rend)
  14139. (skip-chars-backward " \r\t\n")
  14140. (insert "\n:END:")
  14141. (deactivate-mark t)
  14142. (indent-for-tab-command)
  14143. (unless (eolp) (insert "\n")))
  14144. ;; Clear marker, whatever the outcome of insertion is.
  14145. (set-marker rend nil)))))))
  14146. (defvar org-property-set-functions-alist nil
  14147. "Property set function alist.
  14148. Each entry should have the following format:
  14149. (PROPERTY . READ-FUNCTION)
  14150. The read function will be called with the same argument as
  14151. `org-completing-read'.")
  14152. (defun org-set-property-function (property)
  14153. "Get the function that should be used to set PROPERTY.
  14154. This is computed according to `org-property-set-functions-alist'."
  14155. (or (cdr (assoc property org-property-set-functions-alist))
  14156. 'org-completing-read))
  14157. (defun org-read-property-value (property)
  14158. "Read PROPERTY value from user."
  14159. (let* ((completion-ignore-case t)
  14160. (allowed (org-property-get-allowed-values nil property 'table))
  14161. (cur (org-entry-get nil property))
  14162. (prompt (concat property " value"
  14163. (if (and cur (string-match "\\S-" cur))
  14164. (concat " [" cur "]") "") ": "))
  14165. (set-function (org-set-property-function property))
  14166. (val (if allowed
  14167. (funcall set-function prompt allowed nil
  14168. (not (get-text-property 0 'org-unrestricted
  14169. (caar allowed))))
  14170. (funcall set-function prompt
  14171. (mapcar 'list (org-property-values property))
  14172. nil nil "" nil cur))))
  14173. (org-trim val)))
  14174. (defvar org-last-set-property nil)
  14175. (defvar org-last-set-property-value nil)
  14176. (defun org-read-property-name ()
  14177. "Read a property name."
  14178. (let ((completion-ignore-case t)
  14179. (default-prop (or (and (org-at-property-p)
  14180. (match-string-no-properties 2))
  14181. org-last-set-property)))
  14182. (org-completing-read
  14183. (concat "Property"
  14184. (if default-prop (concat " [" default-prop "]") "")
  14185. ": ")
  14186. (mapcar #'list (org-buffer-property-keys nil t t))
  14187. nil nil nil nil default-prop)))
  14188. (defun org-set-property-and-value (use-last)
  14189. "Allow to set [PROPERTY]: [value] direction from prompt.
  14190. When use-default, don't even ask, just use the last
  14191. \"[PROPERTY]: [value]\" string from the history."
  14192. (interactive "P")
  14193. (let* ((completion-ignore-case t)
  14194. (pv (or (and use-last org-last-set-property-value)
  14195. (org-completing-read
  14196. "Enter a \"[Property]: [value]\" pair: "
  14197. nil nil nil nil nil
  14198. org-last-set-property-value)))
  14199. prop val)
  14200. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14201. (setq prop (match-string 1 pv)
  14202. val (match-string 2 pv))
  14203. (org-set-property prop val))))
  14204. (defun org-set-property (property value)
  14205. "In the current entry, set PROPERTY to VALUE.
  14206. When called interactively, this will prompt for a property name, offering
  14207. completion on existing and default properties. And then it will prompt
  14208. for a value, offering completion either on allowed values (via an inherited
  14209. xxx_ALL property) or on existing values in other instances of this property
  14210. in the current file.
  14211. Throw an error when trying to set a property with an invalid name."
  14212. (interactive (list nil nil))
  14213. (let ((property (or property (org-read-property-name))))
  14214. ;; `org-entry-put' also makes the following check, but this one
  14215. ;; avoids polluting `org-last-set-property' and
  14216. ;; `org-last-set-property-value' needlessly.
  14217. (unless (org--valid-property-p property)
  14218. (user-error "Invalid property name: \"%s\"" property))
  14219. (let ((value (or value (org-read-property-value property)))
  14220. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14221. (setq org-last-set-property property)
  14222. (setq org-last-set-property-value (concat property ": " value))
  14223. ;; Possibly postprocess the inserted value:
  14224. (when fn (setq value (funcall fn value)))
  14225. (unless (equal (org-entry-get nil property) value)
  14226. (org-entry-put nil property value)))))
  14227. (defun org-find-property (property &optional value)
  14228. "Find first entry in buffer that sets PROPERTY.
  14229. When optional argument VALUE is non-nil, only consider an entry
  14230. if it contains PROPERTY set to this value. If PROPERTY should be
  14231. explicitly set to nil, use string \"nil\" for VALUE.
  14232. Return position where the entry begins, or nil if there is no
  14233. such entry. If narrowing is in effect, only search the visible
  14234. part of the buffer."
  14235. (save-excursion
  14236. (goto-char (point-min))
  14237. (let ((case-fold-search t)
  14238. (re (org-re-property property nil (not value) value)))
  14239. (catch 'exit
  14240. (while (re-search-forward re nil t)
  14241. (when (if value (org-at-property-p)
  14242. (org-entry-get (point) property nil t))
  14243. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14244. (defun org-delete-property (property)
  14245. "In the current entry, delete PROPERTY."
  14246. (interactive
  14247. (let* ((completion-ignore-case t)
  14248. (cat (org-entry-get (point) "CATEGORY"))
  14249. (props0 (org-entry-properties nil 'standard))
  14250. (props (if cat props0
  14251. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14252. (prop (if (< 1 (length props))
  14253. (completing-read "Property: " props nil t)
  14254. (caar props))))
  14255. (list prop)))
  14256. (if (not property)
  14257. (message "No property to delete in this entry")
  14258. (org-entry-delete nil property)
  14259. (message "Property \"%s\" deleted" property)))
  14260. (defun org-delete-property-globally (property)
  14261. "Remove PROPERTY globally, from all entries.
  14262. This function ignores narrowing, if any."
  14263. (interactive
  14264. (let* ((completion-ignore-case t)
  14265. (prop (completing-read
  14266. "Globally remove property: "
  14267. (mapcar #'list (org-buffer-property-keys)))))
  14268. (list prop)))
  14269. (org-with-wide-buffer
  14270. (goto-char (point-min))
  14271. (let ((count 0)
  14272. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14273. (while (re-search-forward re nil t)
  14274. (when (org-entry-delete (point) property) (cl-incf count)))
  14275. (message "Property \"%s\" removed from %d entries" property count))))
  14276. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14277. (defun org-compute-property-at-point ()
  14278. "Compute the property at point.
  14279. This looks for an enclosing column format, extracts the operator and
  14280. then applies it to the property in the column format's scope."
  14281. (interactive)
  14282. (unless (org-at-property-p)
  14283. (user-error "Not at a property"))
  14284. (let ((prop (match-string-no-properties 2)))
  14285. (org-columns-get-format-and-top-level)
  14286. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14287. (user-error "No operator defined for property %s" prop))
  14288. (org-columns-compute prop)))
  14289. (defvar org-property-allowed-value-functions nil
  14290. "Hook for functions supplying allowed values for a specific property.
  14291. The functions must take a single argument, the name of the property, and
  14292. return a flat list of allowed values. If \":ETC\" is one of
  14293. the values, this means that these values are intended as defaults for
  14294. completion, but that other values should be allowed too.
  14295. The functions must return nil if they are not responsible for this
  14296. property.")
  14297. (defun org-property-get-allowed-values (pom property &optional table)
  14298. "Get allowed values for the property PROPERTY.
  14299. When TABLE is non-nil, return an alist that can directly be used for
  14300. completion."
  14301. (let (vals)
  14302. (cond
  14303. ((equal property "TODO")
  14304. (setq vals (org-with-point-at pom
  14305. (append org-todo-keywords-1 '("")))))
  14306. ((equal property "PRIORITY")
  14307. (let ((n org-lowest-priority))
  14308. (while (>= n org-highest-priority)
  14309. (push (char-to-string n) vals)
  14310. (setq n (1- n)))))
  14311. ((equal property "CATEGORY"))
  14312. ((member property org-special-properties))
  14313. ((setq vals (run-hook-with-args-until-success
  14314. 'org-property-allowed-value-functions property)))
  14315. (t
  14316. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14317. (when (and vals (string-match "\\S-" vals))
  14318. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14319. (setq vals (mapcar (lambda (x)
  14320. (cond ((stringp x) x)
  14321. ((numberp x) (number-to-string x))
  14322. ((symbolp x) (symbol-name x))
  14323. (t "???")))
  14324. vals)))))
  14325. (when (member ":ETC" vals)
  14326. (setq vals (remove ":ETC" vals))
  14327. (org-add-props (car vals) '(org-unrestricted t)))
  14328. (if table (mapcar 'list vals) vals)))
  14329. (defun org-property-previous-allowed-value (&optional _previous)
  14330. "Switch to the next allowed value for this property."
  14331. (interactive)
  14332. (org-property-next-allowed-value t))
  14333. (defun org-property-next-allowed-value (&optional previous)
  14334. "Switch to the next allowed value for this property."
  14335. (interactive)
  14336. (unless (org-at-property-p)
  14337. (user-error "Not at a property"))
  14338. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14339. (key (match-string 2))
  14340. (value (match-string 3))
  14341. (allowed (or (org-property-get-allowed-values (point) key)
  14342. (and (member value '("[ ]" "[-]" "[X]"))
  14343. '("[ ]" "[X]"))))
  14344. (heading (save-match-data (nth 4 (org-heading-components))))
  14345. nval)
  14346. (unless allowed
  14347. (user-error "Allowed values for this property have not been defined"))
  14348. (when previous (setq allowed (reverse allowed)))
  14349. (when (member value allowed)
  14350. (setq nval (car (cdr (member value allowed)))))
  14351. (setq nval (or nval (car allowed)))
  14352. (when (equal nval value)
  14353. (user-error "Only one allowed value for this property"))
  14354. (org-at-property-p)
  14355. (replace-match (concat " :" key ": " nval) t t)
  14356. (org-indent-line)
  14357. (beginning-of-line 1)
  14358. (skip-chars-forward " \t")
  14359. (when (equal prop org-effort-property)
  14360. (org-refresh-property
  14361. '((effort . identity)
  14362. (effort-minutes . org-duration-to-minutes))
  14363. nval)
  14364. (when (string= org-clock-current-task heading)
  14365. (setq org-clock-effort nval)
  14366. (org-clock-update-mode-line)))
  14367. (run-hook-with-args 'org-property-changed-functions key nval)))
  14368. (defun org-find-olp (path &optional this-buffer)
  14369. "Return a marker pointing to the entry at outline path OLP.
  14370. If anything goes wrong, throw an error.
  14371. You can wrap this call to catch the error like this:
  14372. (condition-case msg
  14373. (org-mobile-locate-entry (match-string 4))
  14374. (error (nth 1 msg)))
  14375. The return value will then be either a string with the error message,
  14376. or a marker if everything is OK.
  14377. If THIS-BUFFER is set, the outline path does not contain a file,
  14378. only headings."
  14379. (let* ((file (if this-buffer buffer-file-name (pop path)))
  14380. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  14381. (level 1)
  14382. (lmin 1)
  14383. (lmax 1)
  14384. end found flevel)
  14385. (unless buffer (error "File not found :%s" file))
  14386. (with-current-buffer buffer
  14387. (unless (derived-mode-p 'org-mode)
  14388. (error "Buffer %s needs to be in Org mode" buffer))
  14389. (org-with-wide-buffer
  14390. (goto-char (point-min))
  14391. (dolist (heading path)
  14392. (let ((re (format org-complex-heading-regexp-format
  14393. (regexp-quote heading)))
  14394. (cnt 0))
  14395. (while (re-search-forward re end t)
  14396. (setq level (- (match-end 1) (match-beginning 1)))
  14397. (when (and (>= level lmin) (<= level lmax))
  14398. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  14399. (when (= cnt 0)
  14400. (error "Heading not found on level %d: %s" lmax heading))
  14401. (when (> cnt 1)
  14402. (error "Heading not unique on level %d: %s" lmax heading))
  14403. (goto-char found)
  14404. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  14405. (setq end (save-excursion (org-end-of-subtree t t)))))
  14406. (when (org-at-heading-p)
  14407. (point-marker))))))
  14408. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  14409. "Find node HEADING in BUFFER.
  14410. Return a marker to the heading if it was found, or nil if not.
  14411. If POS-ONLY is set, return just the position instead of a marker.
  14412. The heading text must match exact, but it may have a TODO keyword,
  14413. a priority cookie and tags in the standard locations."
  14414. (with-current-buffer (or buffer (current-buffer))
  14415. (org-with-wide-buffer
  14416. (goto-char (point-min))
  14417. (let (case-fold-search)
  14418. (when (re-search-forward
  14419. (format org-complex-heading-regexp-format
  14420. (regexp-quote heading)) nil t)
  14421. (if pos-only
  14422. (match-beginning 0)
  14423. (move-marker (make-marker) (match-beginning 0))))))))
  14424. (defun org-find-exact-heading-in-directory (heading &optional dir)
  14425. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  14426. When the target headline is found, return a marker to this location."
  14427. (let ((files (directory-files (or dir default-directory)
  14428. t "\\`[^.#].*\\.org\\'"))
  14429. visiting m buffer)
  14430. (catch 'found
  14431. (dolist (file files)
  14432. (message "trying %s" file)
  14433. (setq visiting (org-find-base-buffer-visiting file))
  14434. (setq buffer (or visiting (find-file-noselect file)))
  14435. (setq m (org-find-exact-headline-in-buffer
  14436. heading buffer))
  14437. (when (and (not m) (not visiting)) (kill-buffer buffer))
  14438. (and m (throw 'found m))))))
  14439. (defun org-find-entry-with-id (ident)
  14440. "Locate the entry that contains the ID property with exact value IDENT.
  14441. IDENT can be a string, a symbol or a number, this function will search for
  14442. the string representation of it.
  14443. Return the position where this entry starts, or nil if there is no such entry."
  14444. (interactive "sID: ")
  14445. (let ((id (cond
  14446. ((stringp ident) ident)
  14447. ((symbolp ident) (symbol-name ident))
  14448. ((numberp ident) (number-to-string ident))
  14449. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  14450. (org-with-wide-buffer (org-find-property "ID" id))))
  14451. ;;;; Timestamps
  14452. (defvar org-last-changed-timestamp nil)
  14453. (defvar org-last-inserted-timestamp nil
  14454. "The last time stamp inserted with `org-insert-time-stamp'.")
  14455. (defun org-time-stamp (arg &optional inactive)
  14456. "Prompt for a date/time and insert a time stamp.
  14457. If the user specifies a time like HH:MM or if this command is
  14458. called with at least one prefix argument, the time stamp contains
  14459. the date and the time. Otherwise, only the date is included.
  14460. All parts of a date not specified by the user are filled in from
  14461. the timestamp at point, if any, or the current date/time
  14462. otherwise.
  14463. If there is already a timestamp at the cursor, it is replaced.
  14464. With two universal prefix arguments, insert an active timestamp
  14465. with the current time without prompting the user.
  14466. When called from lisp, the timestamp is inactive if INACTIVE is
  14467. non-nil."
  14468. (interactive "P")
  14469. (let* ((ts (cond
  14470. ((org-at-date-range-p t)
  14471. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  14472. ((org-at-timestamp-p 'lax) (match-string 0))))
  14473. ;; Default time is either the timestamp at point or today.
  14474. ;; When entering a range, only the range start is considered.
  14475. (default-time (if (not ts) (current-time)
  14476. (apply #'encode-time (org-parse-time-string ts))))
  14477. (default-input (and ts (org-get-compact-tod ts)))
  14478. (repeater (and ts
  14479. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  14480. (match-string 0 ts)))
  14481. org-time-was-given
  14482. org-end-time-was-given
  14483. (time
  14484. (and (if (equal arg '(16)) (current-time)
  14485. ;; Preserve `this-command' and `last-command'.
  14486. (let ((this-command this-command)
  14487. (last-command last-command))
  14488. (org-read-date
  14489. arg 'totime nil nil default-time default-input
  14490. inactive))))))
  14491. (cond
  14492. ((and ts
  14493. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  14494. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  14495. (insert "--")
  14496. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  14497. (ts
  14498. ;; Make sure we're on a timestamp. When in the middle of a date
  14499. ;; range, move arbitrarily to range end.
  14500. (unless (org-at-timestamp-p 'lax)
  14501. (skip-chars-forward "-")
  14502. (org-at-timestamp-p 'lax))
  14503. (replace-match "")
  14504. (setq org-last-changed-timestamp
  14505. (org-insert-time-stamp
  14506. time (or org-time-was-given arg)
  14507. inactive nil nil (list org-end-time-was-given)))
  14508. (when repeater
  14509. (backward-char)
  14510. (insert " " repeater)
  14511. (setq org-last-changed-timestamp
  14512. (concat (substring org-last-inserted-timestamp 0 -1)
  14513. " " repeater ">")))
  14514. (message "Timestamp updated"))
  14515. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  14516. (t (org-insert-time-stamp
  14517. time (or org-time-was-given arg) inactive nil nil
  14518. (list org-end-time-was-given))))))
  14519. ;; FIXME: can we use this for something else, like computing time differences?
  14520. (defun org-get-compact-tod (s)
  14521. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  14522. (let* ((t1 (match-string 1 s))
  14523. (h1 (string-to-number (match-string 2 s)))
  14524. (m1 (string-to-number (match-string 3 s)))
  14525. (t2 (and (match-end 4) (match-string 5 s)))
  14526. (h2 (and t2 (string-to-number (match-string 6 s))))
  14527. (m2 (and t2 (string-to-number (match-string 7 s))))
  14528. dh dm)
  14529. (if (not t2)
  14530. t1
  14531. (setq dh (- h2 h1) dm (- m2 m1))
  14532. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  14533. (concat t1 "+" (number-to-string dh)
  14534. (and (/= 0 dm) (format ":%02d" dm)))))))
  14535. (defun org-time-stamp-inactive (&optional arg)
  14536. "Insert an inactive time stamp.
  14537. An inactive time stamp is enclosed in square brackets instead of angle
  14538. brackets. It is inactive in the sense that it does not trigger agenda entries,
  14539. does not link to the calendar and cannot be changed with the S-cursor keys.
  14540. So these are more for recording a certain time/date.
  14541. If the user specifies a time like HH:MM or if this command is called with
  14542. at least one prefix argument, the time stamp contains the date and the time.
  14543. Otherwise, only the date is included.
  14544. When called with two universal prefix arguments, insert an active time stamp
  14545. with the current time without prompting the user."
  14546. (interactive "P")
  14547. (org-time-stamp arg 'inactive))
  14548. (defvar org-date-ovl (make-overlay 1 1))
  14549. (overlay-put org-date-ovl 'face 'org-date-selected)
  14550. (delete-overlay org-date-ovl)
  14551. (defvar org-ans1) ; dynamically scoped parameter
  14552. (defvar org-ans2) ; dynamically scoped parameter
  14553. (defvar org-plain-time-of-day-regexp) ; defined below
  14554. (defvar org-overriding-default-time nil) ; dynamically scoped
  14555. (defvar org-read-date-overlay nil)
  14556. (defvar org-dcst nil) ; dynamically scoped
  14557. (defvar org-read-date-history nil)
  14558. (defvar org-read-date-final-answer nil)
  14559. (defvar org-read-date-analyze-futurep nil)
  14560. (defvar org-read-date-analyze-forced-year nil)
  14561. (defvar org-read-date-inactive)
  14562. (defvar org-read-date-minibuffer-local-map
  14563. (let* ((map (make-sparse-keymap)))
  14564. (set-keymap-parent map minibuffer-local-map)
  14565. (org-defkey map (kbd ".")
  14566. (lambda () (interactive)
  14567. ;; Are we at the beginning of the prompt?
  14568. (if (looking-back "^[^:]+: "
  14569. (let ((inhibit-field-text-motion t))
  14570. (line-beginning-position)))
  14571. (org-eval-in-calendar '(calendar-goto-today))
  14572. (insert "."))))
  14573. (org-defkey map (kbd "C-.")
  14574. (lambda () (interactive)
  14575. (org-eval-in-calendar '(calendar-goto-today))))
  14576. (org-defkey map (kbd "M-S-<left>")
  14577. (lambda () (interactive)
  14578. (org-eval-in-calendar '(calendar-backward-month 1))))
  14579. (org-defkey map (kbd "ESC S-<left>")
  14580. (lambda () (interactive)
  14581. (org-eval-in-calendar '(calendar-backward-month 1))))
  14582. (org-defkey map (kbd "M-S-<right>")
  14583. (lambda () (interactive)
  14584. (org-eval-in-calendar '(calendar-forward-month 1))))
  14585. (org-defkey map (kbd "ESC S-<right>")
  14586. (lambda () (interactive)
  14587. (org-eval-in-calendar '(calendar-forward-month 1))))
  14588. (org-defkey map (kbd "M-S-<up>")
  14589. (lambda () (interactive)
  14590. (org-eval-in-calendar '(calendar-backward-year 1))))
  14591. (org-defkey map (kbd "ESC S-<up>")
  14592. (lambda () (interactive)
  14593. (org-eval-in-calendar '(calendar-backward-year 1))))
  14594. (org-defkey map (kbd "M-S-<down>")
  14595. (lambda () (interactive)
  14596. (org-eval-in-calendar '(calendar-forward-year 1))))
  14597. (org-defkey map (kbd "ESC S-<down>")
  14598. (lambda () (interactive)
  14599. (org-eval-in-calendar '(calendar-forward-year 1))))
  14600. (org-defkey map (kbd "S-<up>")
  14601. (lambda () (interactive)
  14602. (org-eval-in-calendar '(calendar-backward-week 1))))
  14603. (org-defkey map (kbd "S-<down>")
  14604. (lambda () (interactive)
  14605. (org-eval-in-calendar '(calendar-forward-week 1))))
  14606. (org-defkey map (kbd "S-<left>")
  14607. (lambda () (interactive)
  14608. (org-eval-in-calendar '(calendar-backward-day 1))))
  14609. (org-defkey map (kbd "S-<right>")
  14610. (lambda () (interactive)
  14611. (org-eval-in-calendar '(calendar-forward-day 1))))
  14612. (org-defkey map (kbd "!")
  14613. (lambda () (interactive)
  14614. (org-eval-in-calendar '(diary-view-entries))
  14615. (message "")))
  14616. (org-defkey map (kbd ">")
  14617. (lambda () (interactive)
  14618. (org-eval-in-calendar '(calendar-scroll-left 1))))
  14619. (org-defkey map (kbd "<")
  14620. (lambda () (interactive)
  14621. (org-eval-in-calendar '(calendar-scroll-right 1))))
  14622. (org-defkey map (kbd "C-v")
  14623. (lambda () (interactive)
  14624. (org-eval-in-calendar
  14625. '(calendar-scroll-left-three-months 1))))
  14626. (org-defkey map (kbd "M-v")
  14627. (lambda () (interactive)
  14628. (org-eval-in-calendar
  14629. '(calendar-scroll-right-three-months 1))))
  14630. map)
  14631. "Keymap for minibuffer commands when using `org-read-date'.")
  14632. (defvar org-def)
  14633. (defvar org-defdecode)
  14634. (defvar org-with-time)
  14635. (defvar calendar-setup) ; Dynamically scoped.
  14636. (defun org-read-date (&optional with-time to-time from-string prompt
  14637. default-time default-input inactive)
  14638. "Read a date, possibly a time, and make things smooth for the user.
  14639. The prompt will suggest to enter an ISO date, but you can also enter anything
  14640. which will at least partially be understood by `parse-time-string'.
  14641. Unrecognized parts of the date will default to the current day, month, year,
  14642. hour and minute. If this command is called to replace a timestamp at point,
  14643. or to enter the second timestamp of a range, the default time is taken
  14644. from the existing stamp. Furthermore, the command prefers the future,
  14645. so if you are giving a date where the year is not given, and the day-month
  14646. combination is already past in the current year, it will assume you
  14647. mean next year. For details, see the manual. A few examples:
  14648. 3-2-5 --> 2003-02-05
  14649. feb 15 --> currentyear-02-15
  14650. 2/15 --> currentyear-02-15
  14651. sep 12 9 --> 2009-09-12
  14652. 12:45 --> today 12:45
  14653. 22 sept 0:34 --> currentyear-09-22 0:34
  14654. 12 --> currentyear-currentmonth-12
  14655. Fri --> nearest Friday after today
  14656. -Tue --> last Tuesday
  14657. etc.
  14658. Furthermore you can specify a relative date by giving, as the *first* thing
  14659. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  14660. change in days weeks, months, years.
  14661. With a single plus or minus, the date is relative to today. With a double
  14662. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  14663. +4d --> four days from today
  14664. +4 --> same as above
  14665. +2w --> two weeks from today
  14666. ++5 --> five days from default date
  14667. The function understands only English month and weekday abbreviations.
  14668. While prompting, a calendar is popped up - you can also select the
  14669. date with the mouse (button 1). The calendar shows a period of three
  14670. months. To scroll it to other months, use the keys `>' and `<'.
  14671. If you don't like the calendar, turn it off with
  14672. (setq org-read-date-popup-calendar nil)
  14673. With optional argument TO-TIME, the date will immediately be converted
  14674. to an internal time.
  14675. With an optional argument WITH-TIME, the prompt will suggest to
  14676. also insert a time. Note that when WITH-TIME is not set, you can
  14677. still enter a time, and this function will inform the calling routine
  14678. about this change. The calling routine may then choose to change the
  14679. format used to insert the time stamp into the buffer to include the time.
  14680. With optional argument FROM-STRING, read from this string instead from
  14681. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  14682. the time/date that is used for everything that is not specified by the
  14683. user."
  14684. (require 'parse-time)
  14685. (let* ((org-with-time with-time)
  14686. (org-time-stamp-rounding-minutes
  14687. (if (equal org-with-time '(16))
  14688. '(0 0)
  14689. org-time-stamp-rounding-minutes))
  14690. (org-dcst org-display-custom-times)
  14691. (ct (org-current-time))
  14692. (org-def (or org-overriding-default-time default-time ct))
  14693. (org-defdecode (decode-time org-def))
  14694. (cur-frame (selected-frame))
  14695. (mouse-autoselect-window nil) ; Don't let the mouse jump
  14696. (calendar-setup
  14697. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  14698. (calendar-move-hook nil)
  14699. (calendar-view-diary-initially-flag nil)
  14700. (calendar-view-holidays-initially-flag nil)
  14701. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  14702. ;; Rationalize `org-def' and `org-defdecode', if required.
  14703. (when (< (nth 2 org-defdecode) org-extend-today-until)
  14704. (setf (nth 2 org-defdecode) -1)
  14705. (setf (nth 1 org-defdecode) 59)
  14706. (setq org-def (apply #'encode-time org-defdecode))
  14707. (setq org-defdecode (decode-time org-def)))
  14708. (let* ((timestr (format-time-string
  14709. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  14710. org-def))
  14711. (prompt (concat (if prompt (concat prompt " ") "")
  14712. (format "Date+time [%s]: " timestr))))
  14713. (cond
  14714. (from-string (setq ans from-string))
  14715. (org-read-date-popup-calendar
  14716. (save-excursion
  14717. (save-window-excursion
  14718. (calendar)
  14719. (when (eq calendar-setup 'calendar-only)
  14720. (setq cal-frame
  14721. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  14722. (select-frame cal-frame))
  14723. (org-eval-in-calendar '(setq cursor-type nil) t)
  14724. (unwind-protect
  14725. (progn
  14726. (calendar-forward-day (- (time-to-days org-def)
  14727. (calendar-absolute-from-gregorian
  14728. (calendar-current-date))))
  14729. (org-eval-in-calendar nil t)
  14730. (let* ((old-map (current-local-map))
  14731. (map (copy-keymap calendar-mode-map))
  14732. (minibuffer-local-map
  14733. (copy-keymap org-read-date-minibuffer-local-map)))
  14734. (org-defkey map (kbd "RET") 'org-calendar-select)
  14735. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  14736. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  14737. (unwind-protect
  14738. (progn
  14739. (use-local-map map)
  14740. (setq org-read-date-inactive inactive)
  14741. (add-hook 'post-command-hook 'org-read-date-display)
  14742. (setq org-ans0
  14743. (read-string prompt
  14744. default-input
  14745. 'org-read-date-history
  14746. nil))
  14747. ;; org-ans0: from prompt
  14748. ;; org-ans1: from mouse click
  14749. ;; org-ans2: from calendar motion
  14750. (setq ans
  14751. (concat org-ans0 " " (or org-ans1 org-ans2))))
  14752. (remove-hook 'post-command-hook 'org-read-date-display)
  14753. (use-local-map old-map)
  14754. (when org-read-date-overlay
  14755. (delete-overlay org-read-date-overlay)
  14756. (setq org-read-date-overlay nil)))))
  14757. (bury-buffer "*Calendar*")
  14758. (when cal-frame
  14759. (delete-frame cal-frame)
  14760. (select-frame-set-input-focus cur-frame))))))
  14761. (t ; Naked prompt only
  14762. (unwind-protect
  14763. (setq ans (read-string prompt default-input
  14764. 'org-read-date-history timestr))
  14765. (when org-read-date-overlay
  14766. (delete-overlay org-read-date-overlay)
  14767. (setq org-read-date-overlay nil))))))
  14768. (setq final (org-read-date-analyze ans org-def org-defdecode))
  14769. (when org-read-date-analyze-forced-year
  14770. (message "Year was forced into %s"
  14771. (if org-read-date-force-compatible-dates
  14772. "compatible range (1970-2037)"
  14773. "range representable on this machine"))
  14774. (ding))
  14775. ;; One round trip to get rid of 34th of August and stuff like that....
  14776. (setq final (decode-time (apply 'encode-time final)))
  14777. (setq org-read-date-final-answer ans)
  14778. (if to-time
  14779. (apply 'encode-time final)
  14780. (if (and (boundp 'org-time-was-given) org-time-was-given)
  14781. (format "%04d-%02d-%02d %02d:%02d"
  14782. (nth 5 final) (nth 4 final) (nth 3 final)
  14783. (nth 2 final) (nth 1 final))
  14784. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  14785. (defun org-read-date-display ()
  14786. "Display the current date prompt interpretation in the minibuffer."
  14787. (when org-read-date-display-live
  14788. (when org-read-date-overlay
  14789. (delete-overlay org-read-date-overlay))
  14790. (when (minibufferp (current-buffer))
  14791. (save-excursion
  14792. (end-of-line 1)
  14793. (while (not (equal (buffer-substring
  14794. (max (point-min) (- (point) 4)) (point))
  14795. " "))
  14796. (insert " ")))
  14797. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  14798. " " (or org-ans1 org-ans2)))
  14799. (org-end-time-was-given nil)
  14800. (f (org-read-date-analyze ans org-def org-defdecode))
  14801. (fmts (if org-dcst
  14802. org-time-stamp-custom-formats
  14803. org-time-stamp-formats))
  14804. (fmt (if (or org-with-time
  14805. (and (boundp 'org-time-was-given) org-time-was-given))
  14806. (cdr fmts)
  14807. (car fmts)))
  14808. (txt (format-time-string fmt (apply 'encode-time f)))
  14809. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  14810. (txt (concat "=> " txt)))
  14811. (when (and org-end-time-was-given
  14812. (string-match org-plain-time-of-day-regexp txt))
  14813. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  14814. org-end-time-was-given
  14815. (substring txt (match-end 0)))))
  14816. (when org-read-date-analyze-futurep
  14817. (setq txt (concat txt " (=>F)")))
  14818. (setq org-read-date-overlay
  14819. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  14820. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  14821. (defun org-read-date-analyze (ans def defdecode)
  14822. "Analyze the combined answer of the date prompt."
  14823. ;; FIXME: cleanup and comment
  14824. ;; Pass `current-time' result to `decode-time' (instead of calling
  14825. ;; without arguments) so that only `current-time' has to be
  14826. ;; overridden in tests.
  14827. (let ((org-def def)
  14828. (org-defdecode defdecode)
  14829. (nowdecode (decode-time (current-time)))
  14830. delta deltan deltaw deltadef year month day
  14831. hour minute second wday pm h2 m2 tl wday1
  14832. iso-year iso-weekday iso-week iso-date futurep kill-year)
  14833. (setq org-read-date-analyze-futurep nil
  14834. org-read-date-analyze-forced-year nil)
  14835. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  14836. (setq ans "+0"))
  14837. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  14838. (setq ans (replace-match "" t t ans)
  14839. deltan (car delta)
  14840. deltaw (nth 1 delta)
  14841. deltadef (nth 2 delta)))
  14842. ;; Check if there is an iso week date in there. If yes, store the
  14843. ;; info and postpone interpreting it until the rest of the parsing
  14844. ;; is done.
  14845. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  14846. (setq iso-year (when (match-end 1)
  14847. (org-small-year-to-year
  14848. (string-to-number (match-string 1 ans))))
  14849. iso-weekday (when (match-end 3)
  14850. (string-to-number (match-string 3 ans)))
  14851. iso-week (string-to-number (match-string 2 ans)))
  14852. (setq ans (replace-match "" t t ans)))
  14853. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  14854. (when (string-match
  14855. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  14856. (setq year (if (match-end 2)
  14857. (string-to-number (match-string 2 ans))
  14858. (progn (setq kill-year t)
  14859. (string-to-number (format-time-string "%Y"))))
  14860. month (string-to-number (match-string 3 ans))
  14861. day (string-to-number (match-string 4 ans)))
  14862. (setq year (org-small-year-to-year year))
  14863. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14864. t nil ans)))
  14865. ;; Help matching dotted european dates
  14866. (when (string-match
  14867. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  14868. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  14869. (setq kill-year t)
  14870. (string-to-number (format-time-string "%Y")))
  14871. day (string-to-number (match-string 1 ans))
  14872. month (string-to-number (match-string 2 ans))
  14873. ans (replace-match (format "%04d-%02d-%02d" year month day)
  14874. t nil ans)))
  14875. ;; Help matching american dates, like 5/30 or 5/30/7
  14876. (when (string-match
  14877. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  14878. (setq year (if (match-end 4)
  14879. (string-to-number (match-string 4 ans))
  14880. (progn (setq kill-year t)
  14881. (string-to-number (format-time-string "%Y"))))
  14882. month (string-to-number (match-string 1 ans))
  14883. day (string-to-number (match-string 2 ans)))
  14884. (setq year (org-small-year-to-year year))
  14885. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14886. t nil ans)))
  14887. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  14888. ;; If there is a time with am/pm, and *no* time without it, we convert
  14889. ;; so that matching will be successful.
  14890. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  14891. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  14892. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  14893. (setq hour (string-to-number (match-string 1 ans))
  14894. minute (if (match-end 3)
  14895. (string-to-number (match-string 3 ans))
  14896. 0)
  14897. pm (equal ?p
  14898. (string-to-char (downcase (match-string 4 ans)))))
  14899. (if (and (= hour 12) (not pm))
  14900. (setq hour 0)
  14901. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  14902. (setq ans (replace-match (format "%02d:%02d" hour minute)
  14903. t t ans))))
  14904. ;; Check if a time range is given as a duration
  14905. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  14906. (setq hour (string-to-number (match-string 1 ans))
  14907. h2 (+ hour (string-to-number (match-string 3 ans)))
  14908. minute (string-to-number (match-string 2 ans))
  14909. m2 (+ minute (if (match-end 5) (string-to-number
  14910. (match-string 5 ans))0)))
  14911. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  14912. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  14913. t t ans)))
  14914. ;; Check if there is a time range
  14915. (when (boundp 'org-end-time-was-given)
  14916. (setq org-time-was-given nil)
  14917. (when (and (string-match org-plain-time-of-day-regexp ans)
  14918. (match-end 8))
  14919. (setq org-end-time-was-given (match-string 8 ans))
  14920. (setq ans (concat (substring ans 0 (match-beginning 7))
  14921. (substring ans (match-end 7))))))
  14922. (setq tl (parse-time-string ans)
  14923. day (or (nth 3 tl) (nth 3 org-defdecode))
  14924. month
  14925. (cond ((nth 4 tl))
  14926. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  14927. ;; Day was specified. Make sure DAY+MONTH
  14928. ;; combination happens in the future.
  14929. ((nth 3 tl)
  14930. (setq futurep t)
  14931. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  14932. (nth 4 nowdecode)))
  14933. (t (nth 4 org-defdecode)))
  14934. year
  14935. (cond ((and (not kill-year) (nth 5 tl)))
  14936. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  14937. ;; Month was guessed in the future and is at least
  14938. ;; equal to NOWDECODE's. Fix year accordingly.
  14939. (futurep
  14940. (if (or (> month (nth 4 nowdecode))
  14941. (>= day (nth 3 nowdecode)))
  14942. (nth 5 nowdecode)
  14943. (1+ (nth 5 nowdecode))))
  14944. ;; Month was specified. Make sure MONTH+YEAR
  14945. ;; combination happens in the future.
  14946. ((nth 4 tl)
  14947. (setq futurep t)
  14948. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  14949. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  14950. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  14951. (t (nth 5 nowdecode))))
  14952. (t (nth 5 org-defdecode)))
  14953. hour (or (nth 2 tl) (nth 2 org-defdecode))
  14954. minute (or (nth 1 tl) (nth 1 org-defdecode))
  14955. second (or (nth 0 tl) 0)
  14956. wday (nth 6 tl))
  14957. (when (and (eq org-read-date-prefer-future 'time)
  14958. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  14959. (equal day (nth 3 nowdecode))
  14960. (equal month (nth 4 nowdecode))
  14961. (equal year (nth 5 nowdecode))
  14962. (nth 2 tl)
  14963. (or (< (nth 2 tl) (nth 2 nowdecode))
  14964. (and (= (nth 2 tl) (nth 2 nowdecode))
  14965. (nth 1 tl)
  14966. (< (nth 1 tl) (nth 1 nowdecode)))))
  14967. (setq day (1+ day)
  14968. futurep t))
  14969. ;; Special date definitions below
  14970. (cond
  14971. (iso-week
  14972. ;; There was an iso week
  14973. (require 'cal-iso)
  14974. (setq futurep nil)
  14975. (setq year (or iso-year year)
  14976. day (or iso-weekday wday 1)
  14977. wday nil ; to make sure that the trigger below does not match
  14978. iso-date (calendar-gregorian-from-absolute
  14979. (calendar-iso-to-absolute
  14980. (list iso-week day year))))
  14981. ; FIXME: Should we also push ISO weeks into the future?
  14982. ; (when (and org-read-date-prefer-future
  14983. ; (not iso-year)
  14984. ; (< (calendar-absolute-from-gregorian iso-date)
  14985. ; (time-to-days (current-time))))
  14986. ; (setq year (1+ year)
  14987. ; iso-date (calendar-gregorian-from-absolute
  14988. ; (calendar-iso-to-absolute
  14989. ; (list iso-week day year)))))
  14990. (setq month (car iso-date)
  14991. year (nth 2 iso-date)
  14992. day (nth 1 iso-date)))
  14993. (deltan
  14994. (setq futurep nil)
  14995. (unless deltadef
  14996. ;; Pass `current-time' result to `decode-time' (instead of
  14997. ;; calling without arguments) so that only `current-time' has
  14998. ;; to be overridden in tests.
  14999. (let ((now (decode-time (current-time))))
  15000. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15001. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15002. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15003. ((equal deltaw "m") (setq month (+ month deltan)))
  15004. ((equal deltaw "y") (setq year (+ year deltan)))))
  15005. ((and wday (not (nth 3 tl)))
  15006. ;; Weekday was given, but no day, so pick that day in the week
  15007. ;; on or after the derived date.
  15008. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15009. (unless (equal wday wday1)
  15010. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15011. (when (and (boundp 'org-time-was-given)
  15012. (nth 2 tl))
  15013. (setq org-time-was-given t))
  15014. (when (< year 100) (setq year (+ 2000 year)))
  15015. ;; Check of the date is representable
  15016. (if org-read-date-force-compatible-dates
  15017. (progn
  15018. (when (< year 1970)
  15019. (setq year 1970 org-read-date-analyze-forced-year t))
  15020. (when (> year 2037)
  15021. (setq year 2037 org-read-date-analyze-forced-year t)))
  15022. (condition-case nil
  15023. (ignore (encode-time second minute hour day month year))
  15024. (error
  15025. (setq year (nth 5 org-defdecode))
  15026. (setq org-read-date-analyze-forced-year t))))
  15027. (setq org-read-date-analyze-futurep futurep)
  15028. (list second minute hour day month year)))
  15029. (defvar parse-time-weekdays)
  15030. (defun org-read-date-get-relative (s today default)
  15031. "Check string S for special relative date string.
  15032. TODAY and DEFAULT are internal times, for today and for a default.
  15033. Return shift list (N what def-flag)
  15034. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15035. N is the number of WHATs to shift.
  15036. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15037. the DEFAULT date rather than TODAY."
  15038. (require 'parse-time)
  15039. (when (and
  15040. (string-match
  15041. (concat
  15042. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15043. "\\([0-9]+\\)?"
  15044. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15045. "\\([ \t]\\|$\\)") s)
  15046. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15047. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15048. (string-to-char (substring (match-string 1 s) -1))
  15049. ?+))
  15050. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15051. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15052. (what (if (match-end 3) (match-string 3 s) "d"))
  15053. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15054. (date (if rel default today))
  15055. (wday (nth 6 (decode-time date)))
  15056. delta)
  15057. (if wday1
  15058. (progn
  15059. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15060. (when (= delta 0) (setq delta 7))
  15061. (when (= dir ?-)
  15062. (setq delta (- delta 7))
  15063. (when (= delta 0) (setq delta -7)))
  15064. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15065. (list delta "d" rel))
  15066. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15067. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15068. "Turn a user-specified date into the internal representation.
  15069. The internal representation needed by the calendar is (month day year).
  15070. This is a wrapper to handle the brain-dead convention in calendar that
  15071. user function argument order change dependent on argument order."
  15072. (pcase calendar-date-style
  15073. (`american (list arg1 arg2 arg3))
  15074. (`european (list arg2 arg1 arg3))
  15075. (`iso (list arg2 arg3 arg1))))
  15076. (defun org-eval-in-calendar (form &optional keepdate)
  15077. "Eval FORM in the calendar window and return to current window.
  15078. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15079. (let ((sf (selected-frame))
  15080. (sw (selected-window)))
  15081. (select-window (get-buffer-window "*Calendar*" t))
  15082. (eval form)
  15083. (when (and (not keepdate) (calendar-cursor-to-date))
  15084. (let* ((date (calendar-cursor-to-date))
  15085. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15086. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15087. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15088. (select-window sw)
  15089. (select-frame-set-input-focus sf)))
  15090. (defun org-calendar-select ()
  15091. "Return to `org-read-date' with the date currently selected.
  15092. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15093. (interactive)
  15094. (when (calendar-cursor-to-date)
  15095. (let* ((date (calendar-cursor-to-date))
  15096. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15097. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15098. (when (active-minibuffer-window) (exit-minibuffer))))
  15099. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15100. "Insert a date stamp for the date given by the internal TIME.
  15101. See `format-time-string' for the format of TIME.
  15102. WITH-HM means use the stamp format that includes the time of the day.
  15103. INACTIVE means use square brackets instead of angular ones, so that the
  15104. stamp will not contribute to the agenda.
  15105. PRE and POST are optional strings to be inserted before and after the
  15106. stamp.
  15107. The command returns the inserted time stamp."
  15108. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15109. stamp)
  15110. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15111. (insert-before-markers (or pre ""))
  15112. (when (listp extra)
  15113. (setq extra (car extra))
  15114. (if (and (stringp extra)
  15115. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15116. (setq extra (format "-%02d:%02d"
  15117. (string-to-number (match-string 1 extra))
  15118. (string-to-number (match-string 2 extra))))
  15119. (setq extra nil)))
  15120. (when extra
  15121. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15122. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15123. (insert-before-markers (or post ""))
  15124. (setq org-last-inserted-timestamp stamp)))
  15125. (defun org-toggle-time-stamp-overlays ()
  15126. "Toggle the use of custom time stamp formats."
  15127. (interactive)
  15128. (setq org-display-custom-times (not org-display-custom-times))
  15129. (unless org-display-custom-times
  15130. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15131. (while (setq p (next-single-property-change p 'display))
  15132. (when (and (get-text-property p 'display)
  15133. (eq (get-text-property p 'face) 'org-date))
  15134. (remove-text-properties
  15135. p (setq p (next-single-property-change p 'display))
  15136. '(display t))))
  15137. (set-buffer-modified-p bmp)))
  15138. (org-restart-font-lock)
  15139. (setq org-table-may-need-update t)
  15140. (if org-display-custom-times
  15141. (message "Time stamps are overlaid with custom format")
  15142. (message "Time stamp overlays removed")))
  15143. (defun org-display-custom-time (beg end)
  15144. "Overlay modified time stamp format over timestamp between BEG and END."
  15145. (let* ((ts (buffer-substring beg end))
  15146. t1 with-hm tf time str (off 0))
  15147. (save-match-data
  15148. (setq t1 (org-parse-time-string ts t))
  15149. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15150. (setq off (- (match-end 0) (match-beginning 0)))))
  15151. (setq end (- end off))
  15152. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  15153. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15154. time (org-fix-decoded-time t1)
  15155. str (org-add-props
  15156. (format-time-string
  15157. (substring tf 1 -1) (apply 'encode-time time))
  15158. nil 'mouse-face 'highlight))
  15159. (put-text-property beg end 'display str)))
  15160. (defun org-fix-decoded-time (time)
  15161. "Set 0 instead of nil for the first 6 elements of time.
  15162. Don't touch the rest."
  15163. (let ((n 0))
  15164. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15165. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15166. "Difference between TIMESTAMP-STRING and now in days.
  15167. If SECONDS is non-nil, return the difference in seconds."
  15168. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15169. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15170. (funcall fdiff (current-time)))))
  15171. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15172. "Is the time in TIMESTAMP-STRING close to the current date?"
  15173. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15174. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15175. (not (org-entry-is-done-p))))
  15176. (defun org-get-wdays (ts &optional delay zero-delay)
  15177. "Get the deadline lead time appropriate for timestring TS.
  15178. When DELAY is non-nil, get the delay time for scheduled items
  15179. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15180. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15181. don't try to find the delay cookie in the scheduled timestamp."
  15182. (let ((tv (if delay org-scheduled-delay-days
  15183. org-deadline-warning-days)))
  15184. (cond
  15185. ((or (and delay (< tv 0))
  15186. (and delay zero-delay (<= tv 0))
  15187. (and (not delay) (<= tv 0)))
  15188. ;; Enforce this value no matter what
  15189. (- tv))
  15190. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15191. ;; lead time is specified.
  15192. (floor (* (string-to-number (match-string 1 ts))
  15193. (cdr (assoc (match-string 2 ts)
  15194. '(("d" . 1) ("w" . 7)
  15195. ("m" . 30.4) ("y" . 365.25)
  15196. ("h" . 0.041667)))))))
  15197. ;; go for the default.
  15198. (t tv))))
  15199. (defun org-calendar-select-mouse (ev)
  15200. "Return to `org-read-date' with the date currently selected.
  15201. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15202. (interactive "e")
  15203. (mouse-set-point ev)
  15204. (when (calendar-cursor-to-date)
  15205. (let* ((date (calendar-cursor-to-date))
  15206. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15207. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15208. (when (active-minibuffer-window) (exit-minibuffer))))
  15209. (defun org-check-deadlines (ndays)
  15210. "Check if there are any deadlines due or past due.
  15211. A deadline is considered due if it happens within `org-deadline-warning-days'
  15212. days from today's date. If the deadline appears in an entry marked DONE,
  15213. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15214. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15215. are shown."
  15216. (interactive "P")
  15217. (let* ((org-warn-days
  15218. (cond
  15219. ((equal ndays '(4)) 100000)
  15220. (ndays (prefix-numeric-value ndays))
  15221. (t (abs org-deadline-warning-days))))
  15222. (case-fold-search nil)
  15223. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15224. (callback
  15225. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15226. (message "%d deadlines past-due or due within %d days"
  15227. (org-occur regexp nil callback)
  15228. org-warn-days)))
  15229. (defsubst org-re-timestamp (type)
  15230. "Return a regexp for timestamp TYPE.
  15231. Allowed values for TYPE are:
  15232. all: all timestamps
  15233. active: only active timestamps (<...>)
  15234. inactive: only inactive timestamps ([...])
  15235. scheduled: only scheduled timestamps
  15236. deadline: only deadline timestamps
  15237. closed: only closed time-stamps
  15238. When TYPE is nil, fall back on returning a regexp that matches
  15239. both scheduled and deadline timestamps."
  15240. (cl-case type
  15241. (all org-ts-regexp-both)
  15242. (active org-ts-regexp)
  15243. (inactive org-ts-regexp-inactive)
  15244. (scheduled org-scheduled-time-regexp)
  15245. (deadline org-deadline-time-regexp)
  15246. (closed org-closed-time-regexp)
  15247. (otherwise
  15248. (concat "\\<"
  15249. (regexp-opt (list org-deadline-string org-scheduled-string))
  15250. " *<\\([^>]+\\)>"))))
  15251. (defun org-check-before-date (d)
  15252. "Check if there are deadlines or scheduled entries before date D."
  15253. (interactive (list (org-read-date)))
  15254. (let* ((case-fold-search nil)
  15255. (regexp (org-re-timestamp org-ts-type))
  15256. (ts-type org-ts-type)
  15257. (callback
  15258. (lambda ()
  15259. (let ((match (match-string 1)))
  15260. (and (if (memq ts-type '(active inactive all))
  15261. (eq (org-element-type (save-excursion
  15262. (backward-char)
  15263. (org-element-context)))
  15264. 'timestamp)
  15265. (org-at-planning-p))
  15266. (time-less-p
  15267. (org-time-string-to-time match)
  15268. (org-time-string-to-time d)))))))
  15269. (message "%d entries before %s"
  15270. (org-occur regexp nil callback)
  15271. d)))
  15272. (defun org-check-after-date (d)
  15273. "Check if there are deadlines or scheduled entries after date D."
  15274. (interactive (list (org-read-date)))
  15275. (let* ((case-fold-search nil)
  15276. (regexp (org-re-timestamp org-ts-type))
  15277. (ts-type org-ts-type)
  15278. (callback
  15279. (lambda ()
  15280. (let ((match (match-string 1)))
  15281. (and (if (memq ts-type '(active inactive all))
  15282. (eq (org-element-type (save-excursion
  15283. (backward-char)
  15284. (org-element-context)))
  15285. 'timestamp)
  15286. (org-at-planning-p))
  15287. (not (time-less-p
  15288. (org-time-string-to-time match)
  15289. (org-time-string-to-time d))))))))
  15290. (message "%d entries after %s"
  15291. (org-occur regexp nil callback)
  15292. d)))
  15293. (defun org-check-dates-range (start-date end-date)
  15294. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15295. (interactive (list (org-read-date nil nil nil "Range starts")
  15296. (org-read-date nil nil nil "Range end")))
  15297. (let ((case-fold-search nil)
  15298. (regexp (org-re-timestamp org-ts-type))
  15299. (callback
  15300. (let ((type org-ts-type))
  15301. (lambda ()
  15302. (let ((match (match-string 1)))
  15303. (and
  15304. (if (memq type '(active inactive all))
  15305. (eq (org-element-type (save-excursion
  15306. (backward-char)
  15307. (org-element-context)))
  15308. 'timestamp)
  15309. (org-at-planning-p))
  15310. (not (time-less-p
  15311. (org-time-string-to-time match)
  15312. (org-time-string-to-time start-date)))
  15313. (time-less-p
  15314. (org-time-string-to-time match)
  15315. (org-time-string-to-time end-date))))))))
  15316. (message "%d entries between %s and %s"
  15317. (org-occur regexp nil callback) start-date end-date)))
  15318. (defun org-evaluate-time-range (&optional to-buffer)
  15319. "Evaluate a time range by computing the difference between start and end.
  15320. Normally the result is just printed in the echo area, but with prefix arg
  15321. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15322. If the time range is actually in a table, the result is inserted into the
  15323. next column.
  15324. For time difference computation, a year is assumed to be exactly 365
  15325. days in order to avoid rounding problems."
  15326. (interactive "P")
  15327. (or
  15328. (org-clock-update-time-maybe)
  15329. (save-excursion
  15330. (unless (org-at-date-range-p t)
  15331. (goto-char (point-at-bol))
  15332. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15333. (unless (org-at-date-range-p t)
  15334. (user-error "Not at a time-stamp range, and none found in current line")))
  15335. (let* ((ts1 (match-string 1))
  15336. (ts2 (match-string 2))
  15337. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15338. (match-end (match-end 0))
  15339. (time1 (org-time-string-to-time ts1))
  15340. (time2 (org-time-string-to-time ts2))
  15341. (t1 (float-time time1))
  15342. (t2 (float-time time2))
  15343. (diff (abs (- t2 t1)))
  15344. (negative (< (- t2 t1) 0))
  15345. ;; (ys (floor (* 365 24 60 60)))
  15346. (ds (* 24 60 60))
  15347. (hs (* 60 60))
  15348. (fy "%dy %dd %02d:%02d")
  15349. (fy1 "%dy %dd")
  15350. (fd "%dd %02d:%02d")
  15351. (fd1 "%dd")
  15352. (fh "%02d:%02d")
  15353. y d h m align)
  15354. (if havetime
  15355. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15356. y 0
  15357. d (floor (/ diff ds)) diff (mod diff ds)
  15358. h (floor (/ diff hs)) diff (mod diff hs)
  15359. m (floor (/ diff 60)))
  15360. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15361. y 0
  15362. d (floor (+ (/ diff ds) 0.5))
  15363. h 0 m 0))
  15364. (if (not to-buffer)
  15365. (message "%s" (org-make-tdiff-string y d h m))
  15366. (if (org-at-table-p)
  15367. (progn
  15368. (goto-char match-end)
  15369. (setq align t)
  15370. (and (looking-at " *|") (goto-char (match-end 0))))
  15371. (goto-char match-end))
  15372. (when (looking-at
  15373. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  15374. (replace-match ""))
  15375. (when negative (insert " -"))
  15376. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  15377. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  15378. (insert " " (format fh h m))))
  15379. (when align (org-table-align))
  15380. (message "Time difference inserted")))))
  15381. (defun org-make-tdiff-string (y d h m)
  15382. (let ((fmt "")
  15383. (l nil))
  15384. (when (> y 0)
  15385. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  15386. (push y l))
  15387. (when (> d 0)
  15388. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  15389. (push d l))
  15390. (when (> h 0)
  15391. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  15392. (push h l))
  15393. (when (> m 0)
  15394. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  15395. (push m l))
  15396. (apply 'format fmt (nreverse l))))
  15397. (defun org-time-string-to-time (s)
  15398. "Convert timestamp string S into internal time."
  15399. (apply #'encode-time (org-parse-time-string s)))
  15400. (defun org-time-string-to-seconds (s)
  15401. "Convert a timestamp string S into a number of seconds."
  15402. (float-time (org-time-string-to-time s)))
  15403. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  15404. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  15405. "Convert time stamp S to an absolute day number.
  15406. If DAYNR in non-nil, and there is a specifier for a cyclic time
  15407. stamp, get the closest date to DAYNR. If PREFER is
  15408. `past' (respectively `future') return a date past (respectively
  15409. after) or equal to DAYNR.
  15410. POS is the location of time stamp S, as a buffer position in
  15411. BUFFER.
  15412. Diary sexp timestamps are matched against DAYNR, when non-nil.
  15413. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  15414. signaled."
  15415. (cond
  15416. ((string-match "\\`%%\\((.*)\\)" s)
  15417. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  15418. ;; only able to match individual dates. If it fails, raise an
  15419. ;; error.
  15420. (if (and daynr
  15421. (org-diary-sexp-entry
  15422. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  15423. daynr
  15424. (signal 'org-diary-sexp-no-match (list s))))
  15425. (daynr (org-closest-date s daynr prefer))
  15426. (t (time-to-days
  15427. (condition-case errdata
  15428. (apply #'encode-time (org-parse-time-string s))
  15429. (error (error "Bad timestamp `%s'%s\nError was: %s"
  15430. s
  15431. (if (not (and buffer pos)) ""
  15432. (format-message " at %d in buffer `%s'" pos buffer))
  15433. (cdr errdata))))))))
  15434. (defun org-days-to-iso-week (days)
  15435. "Return the iso week number."
  15436. (require 'cal-iso)
  15437. (car (calendar-iso-from-absolute days)))
  15438. (defun org-small-year-to-year (year)
  15439. "Convert 2-digit years into 4-digit years.
  15440. YEAR is expanded into one of the 30 next years, if possible, or
  15441. into a past one. Any year larger than 99 is returned unchanged."
  15442. (if (>= year 100) year
  15443. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  15444. (century (/ current 100))
  15445. (offset (- year (% current 100))))
  15446. (cond ((> offset 30) (+ (* (1- century) 100) year))
  15447. ((> offset -70) (+ (* century 100) year))
  15448. (t (+ (* (1+ century) 100) year))))))
  15449. (defun org-time-from-absolute (d)
  15450. "Return the time corresponding to date D.
  15451. D may be an absolute day number, or a calendar-type list (month day year)."
  15452. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  15453. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  15454. (defvar org-agenda-current-date)
  15455. (defun org-calendar-holiday ()
  15456. "List of holidays, for Diary display in Org mode."
  15457. (require 'holidays)
  15458. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  15459. (and hl (mapconcat #'identity hl "; "))))
  15460. (defun org-diary-sexp-entry (sexp entry d)
  15461. "Process a SEXP diary ENTRY for date D."
  15462. (require 'diary-lib)
  15463. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  15464. ;; dynamically.
  15465. (let* ((sexp `(let ((entry ,entry)
  15466. (date ',d))
  15467. ,(car (read-from-string sexp))))
  15468. (result (if calendar-debug-sexp (eval sexp)
  15469. (condition-case nil
  15470. (eval sexp)
  15471. (error
  15472. (beep)
  15473. (message "Bad sexp at line %d in %s: %s"
  15474. (org-current-line)
  15475. (buffer-file-name) sexp)
  15476. (sleep-for 2))))))
  15477. (cond ((stringp result) (split-string result "; "))
  15478. ((and (consp result)
  15479. (not (consp (cdr result)))
  15480. (stringp (cdr result))) (cdr result))
  15481. ((and (consp result)
  15482. (stringp (car result))) result)
  15483. (result entry))))
  15484. (defun org-diary-to-ical-string (frombuf)
  15485. "Get iCalendar entries from diary entries in buffer FROMBUF.
  15486. This uses the icalendar.el library."
  15487. (let* ((tmpdir temporary-file-directory)
  15488. (tmpfile (make-temp-name
  15489. (expand-file-name "orgics" tmpdir)))
  15490. buf rtn b e)
  15491. (with-current-buffer frombuf
  15492. (icalendar-export-region (point-min) (point-max) tmpfile)
  15493. (setq buf (find-buffer-visiting tmpfile))
  15494. (set-buffer buf)
  15495. (goto-char (point-min))
  15496. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  15497. (setq b (match-beginning 0)))
  15498. (goto-char (point-max))
  15499. (when (re-search-backward "^END:VEVENT" nil t)
  15500. (setq e (match-end 0)))
  15501. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  15502. (kill-buffer buf)
  15503. (delete-file tmpfile)
  15504. rtn))
  15505. (defun org-closest-date (start current prefer)
  15506. "Return closest date to CURRENT starting from START.
  15507. CURRENT and START are both time stamps.
  15508. When PREFER is `past', return a date that is either CURRENT or
  15509. past. When PREFER is `future', return a date that is either
  15510. CURRENT or future.
  15511. Only time stamps with a repeater are modified. Any other time
  15512. stamp stay unchanged. In any case, return value is an absolute
  15513. day number."
  15514. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  15515. ;; No repeater. Do not shift time stamp.
  15516. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15517. (let ((value (string-to-number (match-string 1 start)))
  15518. (type (match-string 2 start)))
  15519. (if (= 0 value)
  15520. ;; Repeater with a 0-value is considered as void.
  15521. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15522. (let* ((base (org-date-to-gregorian start))
  15523. (target (org-date-to-gregorian current))
  15524. (sday (calendar-absolute-from-gregorian base))
  15525. (cday (calendar-absolute-from-gregorian target))
  15526. n1 n2)
  15527. ;; If START is already past CURRENT, just return START.
  15528. (if (<= cday sday) sday
  15529. ;; Compute closest date before (N1) and closest date past
  15530. ;; (N2) CURRENT.
  15531. (pcase type
  15532. ("h"
  15533. (let ((missing-hours
  15534. (mod (+ (- (* 24 (- cday sday))
  15535. (nth 2 (org-parse-time-string start)))
  15536. org-extend-today-until)
  15537. value)))
  15538. (setf n1 (if (= missing-hours 0) cday
  15539. (- cday (1+ (/ missing-hours 24)))))
  15540. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  15541. ((or "d" "w")
  15542. (let ((value (if (equal type "w") (* 7 value) value)))
  15543. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  15544. (setf n2 (+ n1 value))))
  15545. ("m"
  15546. (let* ((add-months
  15547. (lambda (d n)
  15548. ;; Add N months to gregorian date D, i.e.,
  15549. ;; a list (MONTH DAY YEAR). Return a valid
  15550. ;; gregorian date.
  15551. (let ((m (+ (nth 0 d) n)))
  15552. (list (mod m 12)
  15553. (nth 1 d)
  15554. (+ (/ m 12) (nth 2 d))))))
  15555. (months ; Complete months to TARGET.
  15556. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  15557. (- (nth 0 target) (nth 0 base))
  15558. ;; If START's day is greater than
  15559. ;; TARGET's, remove incomplete month.
  15560. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  15561. value)
  15562. value))
  15563. (before (funcall add-months base months)))
  15564. (setf n1 (calendar-absolute-from-gregorian before))
  15565. (setf n2
  15566. (calendar-absolute-from-gregorian
  15567. (funcall add-months before value)))))
  15568. (_
  15569. (let* ((d (nth 1 base))
  15570. (m (nth 0 base))
  15571. (y (nth 2 base))
  15572. (years ; Complete years to TARGET.
  15573. (* (/ (- (nth 2 target)
  15574. y
  15575. ;; If START's month and day are
  15576. ;; greater than TARGET's, remove
  15577. ;; incomplete year.
  15578. (if (or (> (nth 0 target) m)
  15579. (and (= (nth 0 target) m)
  15580. (> (nth 1 target) d)))
  15581. 0
  15582. 1))
  15583. value)
  15584. value))
  15585. (before (list m d (+ y years))))
  15586. (setf n1 (calendar-absolute-from-gregorian before))
  15587. (setf n2 (calendar-absolute-from-gregorian
  15588. (list m d (+ (nth 2 before) value)))))))
  15589. ;; Handle PREFER parameter, if any.
  15590. (cond
  15591. ((eq prefer 'past) (if (= cday n2) n2 n1))
  15592. ((eq prefer 'future) (if (= cday n1) n1 n2))
  15593. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  15594. (defun org-date-to-gregorian (d)
  15595. "Turn any specification of date D into a Gregorian date for the calendar."
  15596. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  15597. ((and (listp d) (= (length d) 3)) d)
  15598. ((stringp d)
  15599. (let ((d (org-parse-time-string d)))
  15600. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  15601. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  15602. (defun org-parse-time-string (s &optional nodefault)
  15603. "Parse the standard Org time string.
  15604. This should be a lot faster than the normal `parse-time-string'.
  15605. If time is not given, defaults to 0:00. However, with optional
  15606. NODEFAULT, hour and minute fields will be nil if not given."
  15607. (cond ((string-match org-ts-regexp0 s)
  15608. (list 0
  15609. (when (or (match-beginning 8) (not nodefault))
  15610. (string-to-number (or (match-string 8 s) "0")))
  15611. (when (or (match-beginning 7) (not nodefault))
  15612. (string-to-number (or (match-string 7 s) "0")))
  15613. (string-to-number (match-string 4 s))
  15614. (string-to-number (match-string 3 s))
  15615. (string-to-number (match-string 2 s))
  15616. nil nil nil))
  15617. ((string-match "^<[^>]+>$" s)
  15618. ;; FIXME: `decode-time' needs to be called with ZONE as its
  15619. ;; second argument. However, this requires at least Emacs
  15620. ;; 25.1. We can do it when we switch to this version as our
  15621. ;; minimal requirement.
  15622. (decode-time (seconds-to-time (org-matcher-time s))))
  15623. (t (error "Not a standard Org time string: %s" s))))
  15624. (defun org-timestamp-up (&optional arg)
  15625. "Increase the date item at the cursor by one.
  15626. If the cursor is on the year, change the year. If it is on the month,
  15627. the day or the time, change that. If the cursor is on the enclosing
  15628. bracket, change the timestamp type.
  15629. With prefix ARG, change by that many units."
  15630. (interactive "p")
  15631. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  15632. (defun org-timestamp-down (&optional arg)
  15633. "Decrease the date item at the cursor by one.
  15634. If the cursor is on the year, change the year. If it is on the month,
  15635. the day or the time, change that. If the cursor is on the enclosing
  15636. bracket, change the timestamp type.
  15637. With prefix ARG, change by that many units."
  15638. (interactive "p")
  15639. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  15640. (defun org-timestamp-up-day (&optional arg)
  15641. "Increase the date in the time stamp by one day.
  15642. With prefix ARG, change that many days."
  15643. (interactive "p")
  15644. (if (and (not (org-at-timestamp-p 'lax))
  15645. (org-at-heading-p))
  15646. (org-todo 'up)
  15647. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  15648. (defun org-timestamp-down-day (&optional arg)
  15649. "Decrease the date in the time stamp by one day.
  15650. With prefix ARG, change that many days."
  15651. (interactive "p")
  15652. (if (and (not (org-at-timestamp-p 'lax))
  15653. (org-at-heading-p))
  15654. (org-todo 'down)
  15655. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  15656. (defun org-at-timestamp-p (&optional extended)
  15657. "Non-nil if point is inside a timestamp.
  15658. By default, the function only consider syntactically valid active
  15659. timestamps. However, the caller may have a broader definition
  15660. for timestamps. As a consequence, optional argument EXTENDED can
  15661. be set to the following values
  15662. `inactive'
  15663. Include also syntactically valid inactive timestamps.
  15664. `agenda'
  15665. Include timestamps allowed in Agenda, i.e., those in
  15666. properties drawers, planning lines and clock lines.
  15667. `lax'
  15668. Ignore context. The function matches any part of the
  15669. document looking like a timestamp. This includes comments,
  15670. example blocks...
  15671. For backward-compatibility with Org 9.0, every other non-nil
  15672. value is equivalent to `inactive'.
  15673. When at a timestamp, return the position of the point as a symbol
  15674. among `bracket', `after', `year', `month', `hour', `minute',
  15675. `day' or a number of character from the last know part of the
  15676. time stamp.
  15677. When matching, the match groups are the following:
  15678. group 1: year
  15679. group 2: month
  15680. group 3: day number
  15681. group 4: day name
  15682. group 5: hours, if any
  15683. group 6: minutes, if any"
  15684. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  15685. (pos (point))
  15686. (match?
  15687. (let ((boundaries (org-in-regexp regexp)))
  15688. (save-match-data
  15689. (cond ((null boundaries) nil)
  15690. ((eq extended 'lax) t)
  15691. (t
  15692. (or (and (eq extended 'agenda)
  15693. (or (org-at-planning-p)
  15694. (org-at-property-p)
  15695. (and (bound-and-true-p
  15696. org-agenda-include-inactive-timestamps)
  15697. (org-at-clock-log-p))))
  15698. (eq 'timestamp
  15699. (save-excursion
  15700. (when (= pos (cdr boundaries)) (forward-char -1))
  15701. (org-element-type (org-element-context)))))))))))
  15702. (cond
  15703. ((not match?) nil)
  15704. ((= pos (match-beginning 0)) 'bracket)
  15705. ;; Distinguish location right before the closing bracket from
  15706. ;; right after it.
  15707. ((= pos (1- (match-end 0))) 'bracket)
  15708. ((= pos (match-end 0)) 'after)
  15709. ((org-pos-in-match-range pos 2) 'year)
  15710. ((org-pos-in-match-range pos 3) 'month)
  15711. ((org-pos-in-match-range pos 7) 'hour)
  15712. ((org-pos-in-match-range pos 8) 'minute)
  15713. ((or (org-pos-in-match-range pos 4)
  15714. (org-pos-in-match-range pos 5)) 'day)
  15715. ((and (> pos (or (match-end 8) (match-end 5)))
  15716. (< pos (match-end 0)))
  15717. (- pos (or (match-end 8) (match-end 5))))
  15718. (t 'day))))
  15719. (defun org-toggle-timestamp-type ()
  15720. "Toggle the type (<active> or [inactive]) of a time stamp."
  15721. (interactive)
  15722. (when (org-at-timestamp-p 'lax)
  15723. (let ((beg (match-beginning 0)) (end (match-end 0))
  15724. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  15725. (save-excursion
  15726. (goto-char beg)
  15727. (while (re-search-forward "[][<>]" end t)
  15728. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  15729. t t)))
  15730. (message "Timestamp is now %sactive"
  15731. (if (equal (char-after beg) ?<) "" "in")))))
  15732. (defun org-at-clock-log-p ()
  15733. "Non-nil if point is on a clock log line."
  15734. (and (org-match-line org-clock-line-re)
  15735. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  15736. (defvar org-clock-history) ; defined in org-clock.el
  15737. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  15738. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  15739. "Change the date in the time stamp at point.
  15740. The date will be changed by N times WHAT. WHAT can be `day', `month',
  15741. `year', `minute', `second'. If WHAT is not given, the cursor position
  15742. in the timestamp determines what will be changed.
  15743. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  15744. (let ((origin (point))
  15745. (timestamp? (org-at-timestamp-p 'lax))
  15746. origin-cat
  15747. with-hm inactive
  15748. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  15749. extra rem
  15750. ts time time0 fixnext clrgx)
  15751. (unless timestamp? (user-error "Not at a timestamp"))
  15752. (if (and (not what) (eq timestamp? 'bracket))
  15753. (org-toggle-timestamp-type)
  15754. ;; Point isn't on brackets. Remember the part of the time-stamp
  15755. ;; the point was in. Indeed, size of time-stamps may change,
  15756. ;; but point must be kept in the same category nonetheless.
  15757. (setq origin-cat timestamp?)
  15758. (when (and (not what) (not (eq timestamp? 'day))
  15759. org-display-custom-times
  15760. (get-text-property (point) 'display)
  15761. (not (get-text-property (1- (point)) 'display)))
  15762. (setq timestamp? 'day))
  15763. (setq timestamp? (or what timestamp?)
  15764. inactive (= (char-after (match-beginning 0)) ?\[)
  15765. ts (match-string 0))
  15766. (replace-match "")
  15767. (when (string-match
  15768. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  15769. ts)
  15770. (setq extra (match-string 1 ts))
  15771. (when suppress-tmp-delay
  15772. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  15773. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  15774. (setq with-hm t))
  15775. (setq time0 (org-parse-time-string ts))
  15776. (when (and updown
  15777. (eq timestamp? 'minute)
  15778. (not current-prefix-arg))
  15779. ;; This looks like s-up and s-down. Change by one rounding step.
  15780. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  15781. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  15782. (setcar (cdr time0) (+ (nth 1 time0)
  15783. (if (> n 0) (- rem) (- dm rem))))))
  15784. (setq time
  15785. (apply #'encode-time
  15786. (or (car time0) 0)
  15787. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  15788. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  15789. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  15790. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  15791. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  15792. (nthcdr 6 time0)))
  15793. (when (and (memq timestamp? '(hour minute))
  15794. extra
  15795. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  15796. (setq extra (org-modify-ts-extra
  15797. extra
  15798. (if (eq timestamp? 'hour) 2 5)
  15799. n dm)))
  15800. (when (integerp timestamp?)
  15801. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  15802. (when (eq what 'calendar)
  15803. (let ((cal-date (org-get-date-from-calendar)))
  15804. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  15805. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  15806. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  15807. (setcar time0 (or (car time0) 0))
  15808. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  15809. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  15810. (setq time (apply 'encode-time time0))))
  15811. ;; Insert the new time-stamp, and ensure point stays in the same
  15812. ;; category as before (i.e. not after the last position in that
  15813. ;; category).
  15814. (let ((pos (point)))
  15815. ;; Stay before inserted string. `save-excursion' is of no use.
  15816. (setq org-last-changed-timestamp
  15817. (org-insert-time-stamp time with-hm inactive nil nil extra))
  15818. (goto-char pos))
  15819. (save-match-data
  15820. (looking-at org-ts-regexp3)
  15821. (goto-char
  15822. (pcase origin-cat
  15823. ;; `day' category ends before `hour' if any, or at the end
  15824. ;; of the day name.
  15825. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  15826. (`hour (min (match-end 7) origin))
  15827. (`minute (min (1- (match-end 8)) origin))
  15828. ((pred integerp) (min (1- (match-end 0)) origin))
  15829. ;; Point was right after the time-stamp. However, the
  15830. ;; time-stamp length might have changed, so refer to
  15831. ;; (match-end 0) instead.
  15832. (`after (match-end 0))
  15833. ;; `year' and `month' have both fixed size: point couldn't
  15834. ;; have moved into another part.
  15835. (_ origin))))
  15836. ;; Update clock if on a CLOCK line.
  15837. (org-clock-update-time-maybe)
  15838. ;; Maybe adjust the closest clock in `org-clock-history'
  15839. (when org-clock-adjust-closest
  15840. (if (not (and (org-at-clock-log-p)
  15841. (< 1 (length (delq nil (mapcar 'marker-position
  15842. org-clock-history))))))
  15843. (message "No clock to adjust")
  15844. (cond ((save-excursion ; fix previous clock?
  15845. (re-search-backward org-ts-regexp0 nil t)
  15846. (looking-back (concat org-clock-string " \\[")
  15847. (line-beginning-position)))
  15848. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  15849. ((save-excursion ; fix next clock?
  15850. (re-search-backward org-ts-regexp0 nil t)
  15851. (looking-at (concat org-ts-regexp0 "\\] =>")))
  15852. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  15853. (save-window-excursion
  15854. ;; Find closest clock to point, adjust the previous/next one in history
  15855. (let* ((p (save-excursion (org-back-to-heading t)))
  15856. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  15857. (clfixnth
  15858. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  15859. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  15860. (if (not clfixpos)
  15861. (message "No clock to adjust")
  15862. (save-excursion
  15863. (org-goto-marker-or-bmk clfixpos)
  15864. (org-show-subtree)
  15865. (when (re-search-forward clrgx nil t)
  15866. (goto-char (match-beginning 1))
  15867. (let (org-clock-adjust-closest)
  15868. (org-timestamp-change n timestamp? updown))
  15869. (message "Clock adjusted in %s for heading: %s"
  15870. (file-name-nondirectory (buffer-file-name))
  15871. (org-get-heading t t)))))))))
  15872. ;; Try to recenter the calendar window, if any.
  15873. (when (and org-calendar-follow-timestamp-change
  15874. (get-buffer-window "*Calendar*" t)
  15875. (memq timestamp? '(day month year)))
  15876. (org-recenter-calendar (time-to-days time))))))
  15877. (defun org-modify-ts-extra (s pos n dm)
  15878. "Change the different parts of the lead-time and repeat fields in timestamp."
  15879. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  15880. ng h m new rem)
  15881. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  15882. (cond
  15883. ((or (org-pos-in-match-range pos 2)
  15884. (org-pos-in-match-range pos 3))
  15885. (setq m (string-to-number (match-string 3 s))
  15886. h (string-to-number (match-string 2 s)))
  15887. (if (org-pos-in-match-range pos 2)
  15888. (setq h (+ h n))
  15889. (setq n (* dm (with-no-warnings (signum n))))
  15890. (unless (= 0 (setq rem (% m dm)))
  15891. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  15892. (setq m (+ m n)))
  15893. (when (< m 0) (setq m (+ m 60) h (1- h)))
  15894. (when (> m 59) (setq m (- m 60) h (1+ h)))
  15895. (setq h (mod h 24))
  15896. (setq ng 1 new (format "-%02d:%02d" h m)))
  15897. ((org-pos-in-match-range pos 6)
  15898. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  15899. ((org-pos-in-match-range pos 5)
  15900. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  15901. ((org-pos-in-match-range pos 9)
  15902. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  15903. ((org-pos-in-match-range pos 8)
  15904. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  15905. (when ng
  15906. (setq s (concat
  15907. (substring s 0 (match-beginning ng))
  15908. new
  15909. (substring s (match-end ng))))))
  15910. s))
  15911. (defun org-recenter-calendar (d)
  15912. "If the calendar is visible, recenter it to date D."
  15913. (let ((cwin (get-buffer-window "*Calendar*" t)))
  15914. (when cwin
  15915. (let ((calendar-move-hook nil))
  15916. (with-selected-window cwin
  15917. (calendar-goto-date
  15918. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  15919. (defun org-goto-calendar (&optional arg)
  15920. "Go to the Emacs calendar at the current date.
  15921. If there is a time stamp in the current line, go to that date.
  15922. A prefix ARG can be used to force the current date."
  15923. (interactive "P")
  15924. (let ((calendar-move-hook nil)
  15925. (calendar-view-holidays-initially-flag nil)
  15926. (calendar-view-diary-initially-flag nil)
  15927. diff)
  15928. (when (or (org-at-timestamp-p 'lax)
  15929. (org-match-line (concat ".*" org-ts-regexp)))
  15930. (let ((d1 (time-to-days (current-time)))
  15931. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  15932. (setq diff (- d2 d1))))
  15933. (calendar)
  15934. (calendar-goto-today)
  15935. (when (and diff (not arg)) (calendar-forward-day diff))))
  15936. (defun org-get-date-from-calendar ()
  15937. "Return a list (month day year) of date at point in calendar."
  15938. (with-current-buffer "*Calendar*"
  15939. (save-match-data
  15940. (calendar-cursor-to-date))))
  15941. (defun org-date-from-calendar ()
  15942. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  15943. If there is already a time stamp at the cursor position, update it."
  15944. (interactive)
  15945. (if (org-at-timestamp-p 'lax)
  15946. (org-timestamp-change 0 'calendar)
  15947. (let ((cal-date (org-get-date-from-calendar)))
  15948. (org-insert-time-stamp
  15949. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  15950. (defcustom org-effort-durations
  15951. `(("min" . 1)
  15952. ("h" . 60)
  15953. ("d" . ,(* 60 8))
  15954. ("w" . ,(* 60 8 5))
  15955. ("m" . ,(* 60 8 5 4))
  15956. ("y" . ,(* 60 8 5 40)))
  15957. "Conversion factor to minutes for an effort modifier.
  15958. Each entry has the form (MODIFIER . MINUTES).
  15959. In an effort string, a number followed by MODIFIER is multiplied
  15960. by the specified number of MINUTES to obtain an effort in
  15961. minutes.
  15962. For example, if the value of this variable is ((\"hours\" . 60)), then an
  15963. effort string \"2hours\" is equivalent to 120 minutes."
  15964. :group 'org-agenda
  15965. :version "26.1"
  15966. :package-version '(Org . "8.3")
  15967. :type '(alist :key-type (string :tag "Modifier")
  15968. :value-type (number :tag "Minutes")))
  15969. (defcustom org-image-actual-width t
  15970. "Should we use the actual width of images when inlining them?
  15971. When set to t, always use the image width.
  15972. When set to a number, use imagemagick (when available) to set
  15973. the image's width to this value.
  15974. When set to a number in a list, try to get the width from any
  15975. #+ATTR.* keyword if it matches a width specification like
  15976. #+ATTR_HTML: :width 300px
  15977. and fall back on that number if none is found.
  15978. When set to nil, try to get the width from an #+ATTR.* keyword
  15979. and fall back on the original width if none is found.
  15980. This requires Emacs >= 24.1, build with imagemagick support."
  15981. :group 'org-appearance
  15982. :version "24.4"
  15983. :package-version '(Org . "8.0")
  15984. :type '(choice
  15985. (const :tag "Use the image width" t)
  15986. (integer :tag "Use a number of pixels")
  15987. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  15988. (const :tag "Use #+ATTR* or don't resize" nil)))
  15989. (defcustom org-agenda-inhibit-startup nil
  15990. "Inhibit startup when preparing agenda buffers.
  15991. When this variable is t, the initialization of the Org agenda
  15992. buffers is inhibited: e.g. the visibility state is not set, the
  15993. tables are not re-aligned, etc."
  15994. :type 'boolean
  15995. :version "24.3"
  15996. :group 'org-agenda)
  15997. (defcustom org-agenda-ignore-properties nil
  15998. "Avoid updating text properties when building the agenda.
  15999. Properties are used to prepare buffers for effort estimates,
  16000. appointments, statistics and subtree-local categories.
  16001. If you don't use these in the agenda, you can add them to this
  16002. list and agenda building will be a bit faster.
  16003. The value is a list, with zero or more of the symbols `effort', `appt',
  16004. `stats' or `category'."
  16005. :type '(set :greedy t
  16006. (const effort)
  16007. (const appt)
  16008. (const stats)
  16009. (const category))
  16010. :version "26.1"
  16011. :package-version '(Org . "8.3")
  16012. :group 'org-agenda)
  16013. ;;;; Files
  16014. (defun org-save-all-org-buffers ()
  16015. "Save all Org buffers without user confirmation."
  16016. (interactive)
  16017. (message "Saving all Org buffers...")
  16018. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16019. (when (featurep 'org-id) (org-id-locations-save))
  16020. (message "Saving all Org buffers... done"))
  16021. (defun org-revert-all-org-buffers ()
  16022. "Revert all Org buffers.
  16023. Prompt for confirmation when there are unsaved changes.
  16024. Be sure you know what you are doing before letting this function
  16025. overwrite your changes.
  16026. This function is useful in a setup where one tracks Org files
  16027. with a version control system, to revert on one machine after pulling
  16028. changes from another. I believe the procedure must be like this:
  16029. 1. M-x org-save-all-org-buffers
  16030. 2. Pull changes from the other machine, resolve conflicts
  16031. 3. M-x org-revert-all-org-buffers"
  16032. (interactive)
  16033. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16034. (user-error "Abort"))
  16035. (save-excursion
  16036. (save-window-excursion
  16037. (dolist (b (buffer-list))
  16038. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16039. (with-current-buffer b buffer-file-name))
  16040. (pop-to-buffer-same-window b)
  16041. (revert-buffer t 'no-confirm)))
  16042. (when (and (featurep 'org-id) org-id-track-globally)
  16043. (org-id-locations-load)))))
  16044. ;;;; Agenda files
  16045. ;;;###autoload
  16046. (defun org-switchb (&optional arg)
  16047. "Switch between Org buffers.
  16048. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16049. With `\\[universal-argument] \\[universal-argument]' \
  16050. prefix, restrict available buffers to agenda files."
  16051. (interactive "P")
  16052. (let ((blist (org-buffer-list
  16053. (cond ((equal arg '(4)) 'files)
  16054. ((equal arg '(16)) 'agenda)))))
  16055. (pop-to-buffer-same-window
  16056. (completing-read "Org buffer: "
  16057. (mapcar #'list (mapcar #'buffer-name blist))
  16058. nil t))))
  16059. (defun org-buffer-list (&optional predicate exclude-tmp)
  16060. "Return a list of Org buffers.
  16061. PREDICATE can be `export', `files' or `agenda'.
  16062. export restrict the list to Export buffers.
  16063. files restrict the list to buffers visiting Org files.
  16064. agenda restrict the list to buffers visiting agenda files.
  16065. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16066. (let* ((bfn nil)
  16067. (agenda-files (and (eq predicate 'agenda)
  16068. (mapcar 'file-truename (org-agenda-files t))))
  16069. (filter
  16070. (cond
  16071. ((eq predicate 'files)
  16072. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16073. ((eq predicate 'export)
  16074. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16075. ((eq predicate 'agenda)
  16076. (lambda (b)
  16077. (with-current-buffer b
  16078. (and (derived-mode-p 'org-mode)
  16079. (setq bfn (buffer-file-name b))
  16080. (member (file-truename bfn) agenda-files)))))
  16081. (t (lambda (b) (with-current-buffer b
  16082. (or (derived-mode-p 'org-mode)
  16083. (string-match "\\*Org .*Export"
  16084. (buffer-name b)))))))))
  16085. (delq nil
  16086. (mapcar
  16087. (lambda(b)
  16088. (if (and (funcall filter b)
  16089. (or (not exclude-tmp)
  16090. (not (string-match "tmp" (buffer-name b)))))
  16091. b
  16092. nil))
  16093. (buffer-list)))))
  16094. (defun org-agenda-files (&optional unrestricted archives)
  16095. "Get the list of agenda files.
  16096. Optional UNRESTRICTED means return the full list even if a restriction
  16097. is currently in place.
  16098. When ARCHIVES is t, include all archive files that are really being
  16099. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16100. `org-agenda-archives-mode' is t."
  16101. (let ((files
  16102. (cond
  16103. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16104. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16105. ((listp org-agenda-files) org-agenda-files)
  16106. (t (error "Invalid value of `org-agenda-files'")))))
  16107. (setq files (apply 'append
  16108. (mapcar (lambda (f)
  16109. (if (file-directory-p f)
  16110. (directory-files
  16111. f t org-agenda-file-regexp)
  16112. (list f)))
  16113. files)))
  16114. (when org-agenda-skip-unavailable-files
  16115. (setq files (delq nil
  16116. (mapcar (function
  16117. (lambda (file)
  16118. (and (file-readable-p file) file)))
  16119. files))))
  16120. (when (or (eq archives t)
  16121. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16122. (setq files (org-add-archive-files files)))
  16123. files))
  16124. (defun org-agenda-file-p (&optional file)
  16125. "Return non-nil, if FILE is an agenda file.
  16126. If FILE is omitted, use the file associated with the current
  16127. buffer."
  16128. (let ((fname (or file (buffer-file-name))))
  16129. (and fname
  16130. (member (file-truename fname)
  16131. (mapcar #'file-truename (org-agenda-files t))))))
  16132. (defun org-edit-agenda-file-list ()
  16133. "Edit the list of agenda files.
  16134. Depending on setup, this either uses customize to edit the variable
  16135. `org-agenda-files', or it visits the file that is holding the list. In the
  16136. latter case, the buffer is set up in a way that saving it automatically kills
  16137. the buffer and restores the previous window configuration."
  16138. (interactive)
  16139. (if (stringp org-agenda-files)
  16140. (let ((cw (current-window-configuration)))
  16141. (find-file org-agenda-files)
  16142. (setq-local org-window-configuration cw)
  16143. (add-hook 'after-save-hook
  16144. (lambda ()
  16145. (set-window-configuration
  16146. (prog1 org-window-configuration
  16147. (kill-buffer (current-buffer))))
  16148. (org-install-agenda-files-menu)
  16149. (message "New agenda file list installed"))
  16150. nil 'local)
  16151. (message "%s" (substitute-command-keys
  16152. "Edit list and finish with \\[save-buffer]")))
  16153. (customize-variable 'org-agenda-files)))
  16154. (defun org-store-new-agenda-file-list (list)
  16155. "Set new value for the agenda file list and save it correctly."
  16156. (if (stringp org-agenda-files)
  16157. (let ((fe (org-read-agenda-file-list t)) b u)
  16158. (while (setq b (find-buffer-visiting org-agenda-files))
  16159. (kill-buffer b))
  16160. (with-temp-file org-agenda-files
  16161. (insert
  16162. (mapconcat
  16163. (lambda (f) ;; Keep un-expanded entries.
  16164. (if (setq u (assoc f fe))
  16165. (cdr u)
  16166. f))
  16167. list "\n")
  16168. "\n")))
  16169. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16170. (org-insert-mode-line-in-empty-file nil))
  16171. (setq org-agenda-files list)
  16172. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16173. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16174. "Read the list of agenda files from a file.
  16175. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16176. filenames, used by `org-store-new-agenda-file-list' to write back
  16177. un-expanded file names."
  16178. (when (file-directory-p org-agenda-files)
  16179. (error "`org-agenda-files' cannot be a single directory"))
  16180. (when (stringp org-agenda-files)
  16181. (with-temp-buffer
  16182. (insert-file-contents org-agenda-files)
  16183. (mapcar
  16184. (lambda (f)
  16185. (let ((e (expand-file-name (substitute-in-file-name f)
  16186. org-directory)))
  16187. (if pair-with-expansion
  16188. (cons e f)
  16189. e)))
  16190. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16191. ;;;###autoload
  16192. (defun org-cycle-agenda-files ()
  16193. "Cycle through the files in `org-agenda-files'.
  16194. If the current buffer visits an agenda file, find the next one in the list.
  16195. If the current buffer does not, find the first agenda file."
  16196. (interactive)
  16197. (let* ((fs (or (org-agenda-files t)
  16198. (user-error "No agenda files")))
  16199. (files (copy-sequence fs))
  16200. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16201. file)
  16202. (when tcf
  16203. (while (and (setq file (pop files))
  16204. (not (equal (file-truename file) tcf)))))
  16205. (find-file (car (or files fs)))
  16206. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16207. (defun org-agenda-file-to-front (&optional to-end)
  16208. "Move/add the current file to the top of the agenda file list.
  16209. If the file is not present in the list, it is added to the front. If it is
  16210. present, it is moved there. With optional argument TO-END, add/move to the
  16211. end of the list."
  16212. (interactive "P")
  16213. (let ((org-agenda-skip-unavailable-files nil)
  16214. (file-alist (mapcar (lambda (x)
  16215. (cons (file-truename x) x))
  16216. (org-agenda-files t)))
  16217. (ctf (file-truename
  16218. (or buffer-file-name
  16219. (user-error "Please save the current buffer to a file"))))
  16220. x had)
  16221. (setq x (assoc ctf file-alist) had x)
  16222. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16223. (if to-end
  16224. (setq file-alist (append (delq x file-alist) (list x)))
  16225. (setq file-alist (cons x (delq x file-alist))))
  16226. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16227. (org-install-agenda-files-menu)
  16228. (message "File %s to %s of agenda file list"
  16229. (if had "moved" "added") (if to-end "end" "front"))))
  16230. (defun org-remove-file (&optional file)
  16231. "Remove current file from the list of files in variable `org-agenda-files'.
  16232. These are the files which are being checked for agenda entries.
  16233. Optional argument FILE means use this file instead of the current."
  16234. (interactive)
  16235. (let* ((org-agenda-skip-unavailable-files nil)
  16236. (file (or file buffer-file-name
  16237. (user-error "Current buffer does not visit a file")))
  16238. (true-file (file-truename file))
  16239. (afile (abbreviate-file-name file))
  16240. (files (delq nil (mapcar
  16241. (lambda (x)
  16242. (unless (equal true-file
  16243. (file-truename x))
  16244. x))
  16245. (org-agenda-files t)))))
  16246. (if (not (= (length files) (length (org-agenda-files t))))
  16247. (progn
  16248. (org-store-new-agenda-file-list files)
  16249. (org-install-agenda-files-menu)
  16250. (message "Removed from Org Agenda list: %s" afile))
  16251. (message "File was not in list: %s (not removed)" afile))))
  16252. (defun org-file-menu-entry (file)
  16253. (vector file (list 'find-file file) t))
  16254. (defun org-check-agenda-file (file)
  16255. "Make sure FILE exists. If not, ask user what to do."
  16256. (unless (file-exists-p file)
  16257. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16258. (abbreviate-file-name file))
  16259. (let ((r (downcase (read-char-exclusive))))
  16260. (cond
  16261. ((equal r ?r)
  16262. (org-remove-file file)
  16263. (throw 'nextfile t))
  16264. (t (user-error "Abort"))))))
  16265. (defun org-get-agenda-file-buffer (file)
  16266. "Get an agenda buffer visiting FILE.
  16267. If the buffer needs to be created, add it to the list of buffers
  16268. which might be released later."
  16269. (let ((buf (org-find-base-buffer-visiting file)))
  16270. (if buf
  16271. buf ; just return it
  16272. ;; Make a new buffer and remember it
  16273. (setq buf (find-file-noselect file))
  16274. (when buf (push buf org-agenda-new-buffers))
  16275. buf)))
  16276. (defun org-release-buffers (blist)
  16277. "Release all buffers in list, asking the user for confirmation when needed.
  16278. When a buffer is unmodified, it is just killed. When modified, it is saved
  16279. \(if the user agrees) and then killed."
  16280. (let (file)
  16281. (dolist (buf blist)
  16282. (setq file (buffer-file-name buf))
  16283. (when (and (buffer-modified-p buf)
  16284. file
  16285. (y-or-n-p (format "Save file %s? " file)))
  16286. (with-current-buffer buf (save-buffer)))
  16287. (kill-buffer buf))))
  16288. (defun org-agenda-prepare-buffers (files)
  16289. "Create buffers for all agenda files, protect archived trees and comments."
  16290. (interactive)
  16291. (let ((pa '(:org-archived t))
  16292. (pc '(:org-comment t))
  16293. (pall '(:org-archived t :org-comment t))
  16294. (inhibit-read-only t)
  16295. (org-inhibit-startup org-agenda-inhibit-startup)
  16296. (rea (org-make-tag-string (list org-archive-tag)))
  16297. re pos)
  16298. (setq org-tag-alist-for-agenda nil
  16299. org-tag-groups-alist-for-agenda nil)
  16300. (save-excursion
  16301. (save-restriction
  16302. (dolist (file files)
  16303. (catch 'nextfile
  16304. (if (bufferp file)
  16305. (set-buffer file)
  16306. (org-check-agenda-file file)
  16307. (set-buffer (org-get-agenda-file-buffer file)))
  16308. (widen)
  16309. (org-set-regexps-and-options 'tags-only)
  16310. (setq pos (point))
  16311. (or (memq 'category org-agenda-ignore-properties)
  16312. (org-refresh-category-properties))
  16313. (or (memq 'stats org-agenda-ignore-properties)
  16314. (org-refresh-stats-properties))
  16315. (or (memq 'effort org-agenda-ignore-properties)
  16316. (org-refresh-effort-properties))
  16317. (or (memq 'appt org-agenda-ignore-properties)
  16318. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16319. (setq org-todo-keywords-for-agenda
  16320. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16321. (setq org-done-keywords-for-agenda
  16322. (append org-done-keywords-for-agenda org-done-keywords))
  16323. (setq org-todo-keyword-alist-for-agenda
  16324. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16325. (setq org-tag-alist-for-agenda
  16326. (org--tag-add-to-alist
  16327. org-tag-alist-for-agenda
  16328. org-current-tag-alist))
  16329. ;; Merge current file's tag groups into global
  16330. ;; `org-tag-groups-alist-for-agenda'.
  16331. (when org-group-tags
  16332. (dolist (alist org-tag-groups-alist)
  16333. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16334. (if old
  16335. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16336. (push alist org-tag-groups-alist-for-agenda)))))
  16337. (org-with-silent-modifications
  16338. (save-excursion
  16339. (remove-text-properties (point-min) (point-max) pall)
  16340. (when org-agenda-skip-archived-trees
  16341. (goto-char (point-min))
  16342. (while (re-search-forward rea nil t)
  16343. (when (org-at-heading-p t)
  16344. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16345. (goto-char (point-min))
  16346. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16347. (while (re-search-forward re nil t)
  16348. (when (save-match-data (org-in-commented-heading-p t))
  16349. (add-text-properties
  16350. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16351. (goto-char pos)))))
  16352. (setq org-todo-keywords-for-agenda
  16353. (org-uniquify org-todo-keywords-for-agenda))
  16354. (setq org-todo-keyword-alist-for-agenda
  16355. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16356. ;;;; CDLaTeX minor mode
  16357. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16358. "Keymap for the minor `org-cdlatex-mode'.")
  16359. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  16360. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  16361. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  16362. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  16363. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  16364. (defvar org-cdlatex-texmathp-advice-is-done nil
  16365. "Flag remembering if we have applied the advice to texmathp already.")
  16366. (define-minor-mode org-cdlatex-mode
  16367. "Toggle the minor `org-cdlatex-mode'.
  16368. This mode supports entering LaTeX environment and math in LaTeX fragments
  16369. in Org mode.
  16370. \\{org-cdlatex-mode-map}"
  16371. nil " OCDL" nil
  16372. (when org-cdlatex-mode
  16373. (require 'cdlatex)
  16374. (run-hooks 'cdlatex-mode-hook)
  16375. (cdlatex-compute-tables))
  16376. (unless org-cdlatex-texmathp-advice-is-done
  16377. (setq org-cdlatex-texmathp-advice-is-done t)
  16378. (defadvice texmathp (around org-math-always-on activate)
  16379. "Always return t in Org buffers.
  16380. This is because we want to insert math symbols without dollars even outside
  16381. the LaTeX math segments. If Org mode thinks that point is actually inside
  16382. an embedded LaTeX fragment, let `texmathp' do its job.
  16383. `\\[org-cdlatex-mode-map]'"
  16384. (interactive)
  16385. (let (p)
  16386. (cond
  16387. ((not (derived-mode-p 'org-mode)) ad-do-it)
  16388. ((eq this-command 'cdlatex-math-symbol)
  16389. (setq ad-return-value t
  16390. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  16391. (t
  16392. (let ((p (org-inside-LaTeX-fragment-p)))
  16393. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  16394. (setq ad-return-value t
  16395. texmathp-why '("Org mode embedded math" . 0))
  16396. (when p ad-do-it)))))))))
  16397. (defun turn-on-org-cdlatex ()
  16398. "Unconditionally turn on `org-cdlatex-mode'."
  16399. (org-cdlatex-mode 1))
  16400. (defun org-try-cdlatex-tab ()
  16401. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  16402. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  16403. - inside a LaTeX fragment, or
  16404. - after the first word in a line, where an abbreviation expansion could
  16405. insert a LaTeX environment."
  16406. (when org-cdlatex-mode
  16407. (cond
  16408. ;; Before any word on the line: No expansion possible.
  16409. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  16410. ;; Just after first word on the line: Expand it. Make sure it
  16411. ;; cannot happen on headlines, though.
  16412. ((save-excursion
  16413. (skip-chars-backward "a-zA-Z0-9*")
  16414. (skip-chars-backward " \t")
  16415. (and (bolp) (not (org-at-heading-p))))
  16416. (cdlatex-tab) t)
  16417. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  16418. (defun org-cdlatex-underscore-caret (&optional _arg)
  16419. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  16420. Revert to the normal definition outside of these fragments."
  16421. (interactive "P")
  16422. (if (org-inside-LaTeX-fragment-p)
  16423. (call-interactively 'cdlatex-sub-superscript)
  16424. (let (org-cdlatex-mode)
  16425. (call-interactively (key-binding (vector last-input-event))))))
  16426. (defun org-cdlatex-math-modify (&optional _arg)
  16427. "Execute `cdlatex-math-modify' in LaTeX fragments.
  16428. Revert to the normal definition outside of these fragments."
  16429. (interactive "P")
  16430. (if (org-inside-LaTeX-fragment-p)
  16431. (call-interactively 'cdlatex-math-modify)
  16432. (let (org-cdlatex-mode)
  16433. (call-interactively (key-binding (vector last-input-event))))))
  16434. (defun org-cdlatex-environment-indent (&optional environment item)
  16435. "Execute `cdlatex-environment' and indent the inserted environment.
  16436. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  16437. The inserted environment is indented to current indentation
  16438. unless point is at the beginning of the line, in which the
  16439. environment remains unintended."
  16440. (interactive)
  16441. ;; cdlatex-environment always return nil. Therefore, capture output
  16442. ;; first and determine if an environment was selected.
  16443. (let* ((beg (point-marker))
  16444. (end (copy-marker (point) t))
  16445. (inserted (progn
  16446. (ignore-errors (cdlatex-environment environment item))
  16447. (< beg end)))
  16448. ;; Figure out how many lines to move forward after the
  16449. ;; environment has been inserted.
  16450. (lines (when inserted
  16451. (save-excursion
  16452. (- (cl-loop while (< beg (point))
  16453. with x = 0
  16454. do (forward-line -1)
  16455. (cl-incf x)
  16456. finally return x)
  16457. (if (progn (goto-char beg)
  16458. (and (progn (skip-chars-forward " \t") (eolp))
  16459. (progn (skip-chars-backward " \t") (bolp))))
  16460. 1 0)))))
  16461. (env (org-trim (delete-and-extract-region beg end))))
  16462. (when inserted
  16463. ;; Get indentation of next line unless at column 0.
  16464. (let ((ind (if (bolp) 0
  16465. (save-excursion
  16466. (org-return-indent)
  16467. (prog1 (org-get-indentation)
  16468. (when (progn (skip-chars-forward " \t") (eolp))
  16469. (delete-region beg (point)))))))
  16470. (bol (progn (skip-chars-backward " \t") (bolp))))
  16471. ;; Insert a newline before environment unless at column zero
  16472. ;; to "escape" the current line. Insert a newline if
  16473. ;; something is one the same line as \end{ENVIRONMENT}.
  16474. (insert
  16475. (concat (unless bol "\n") env
  16476. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  16477. (unless (zerop ind)
  16478. (save-excursion
  16479. (goto-char beg)
  16480. (while (< (point) end)
  16481. (unless (eolp) (indent-line-to ind))
  16482. (forward-line))))
  16483. (goto-char beg)
  16484. (forward-line lines)
  16485. (indent-line-to ind)))
  16486. (set-marker beg nil)
  16487. (set-marker end nil)))
  16488. ;;;; LaTeX fragments
  16489. (defun org-inside-LaTeX-fragment-p ()
  16490. "Test if point is inside a LaTeX fragment.
  16491. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  16492. sequence appearing also before point.
  16493. Even though the matchers for math are configurable, this function assumes
  16494. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  16495. delimiters are skipped when they have been removed by customization.
  16496. The return value is nil, or a cons cell with the delimiter and the
  16497. position of this delimiter.
  16498. This function does a reasonably good job, but can locally be fooled by
  16499. for example currency specifications. For example it will assume being in
  16500. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  16501. fragments that are properly closed, but during editing, we have to live
  16502. with the uncertainty caused by missing closing delimiters. This function
  16503. looks only before point, not after."
  16504. (catch 'exit
  16505. (let ((pos (point))
  16506. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  16507. (lim (save-excursion (org-backward-paragraph) (point)))
  16508. dd-on str (start 0) m re)
  16509. (goto-char pos)
  16510. (when dodollar
  16511. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  16512. re (nth 1 (assoc "$" org-latex-regexps)))
  16513. (while (string-match re str start)
  16514. (cond
  16515. ((= (match-end 0) (length str))
  16516. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  16517. ((= (match-end 0) (- (length str) 5))
  16518. (throw 'exit nil))
  16519. (t (setq start (match-end 0))))))
  16520. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  16521. (goto-char pos)
  16522. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  16523. (and (match-beginning 2) (throw 'exit nil))
  16524. ;; count $$
  16525. (while (re-search-backward "\\$\\$" lim t)
  16526. (setq dd-on (not dd-on)))
  16527. (goto-char pos)
  16528. (when dd-on (cons "$$" m))))))
  16529. (defun org-inside-latex-macro-p ()
  16530. "Is point inside a LaTeX macro or its arguments?"
  16531. (save-match-data
  16532. (org-in-regexp
  16533. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  16534. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  16535. "Build an overlay between BEG and END using IMAGE file.
  16536. Argument IMAGETYPE is the extension of the displayed image,
  16537. as a string. It defaults to \"png\"."
  16538. (let ((ov (make-overlay beg end))
  16539. (imagetype (or (intern imagetype) 'png)))
  16540. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  16541. (overlay-put ov 'evaporate t)
  16542. (overlay-put ov
  16543. 'modification-hooks
  16544. (list (lambda (o _flag _beg _end &optional _l)
  16545. (delete-overlay o))))
  16546. (overlay-put ov
  16547. 'display
  16548. (list 'image :type imagetype :file image :ascent 'center))))
  16549. (defun org--list-latex-overlays (&optional beg end)
  16550. "List all Org LaTeX overlays in current buffer.
  16551. Limit to overlays between BEG and END when those are provided."
  16552. (cl-remove-if-not
  16553. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  16554. (overlays-in (or beg (point-min)) (or end (point-max)))))
  16555. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  16556. "Remove all overlays with LaTeX fragment images in current buffer.
  16557. When optional arguments BEG and END are non-nil, remove all
  16558. overlays between them instead. Return a non-nil value when some
  16559. overlays were removed, nil otherwise."
  16560. (let ((overlays (org--list-latex-overlays beg end)))
  16561. (mapc #'delete-overlay overlays)
  16562. overlays))
  16563. (defun org-toggle-latex-fragment (&optional arg)
  16564. "Preview the LaTeX fragment at point, or all locally or globally.
  16565. If the cursor is on a LaTeX fragment, create the image and overlay
  16566. it over the source code, if there is none. Remove it otherwise.
  16567. If there is no fragment at point, display all fragments in the
  16568. current section.
  16569. With prefix ARG, preview or clear image for all fragments in the
  16570. current subtree or in the whole buffer when used before the first
  16571. headline. With a prefix ARG `\\[universal-argument] \
  16572. \\[universal-argument]' preview or clear images
  16573. for all fragments in the buffer."
  16574. (interactive "P")
  16575. (when (display-graphic-p)
  16576. (catch 'exit
  16577. (save-excursion
  16578. (let (beg end msg)
  16579. (cond
  16580. ((or (equal arg '(16))
  16581. (and (equal arg '(4))
  16582. (org-with-limited-levels (org-before-first-heading-p))))
  16583. (if (org-remove-latex-fragment-image-overlays)
  16584. (progn (message "LaTeX fragments images removed from buffer")
  16585. (throw 'exit nil))
  16586. (setq msg "Creating images for buffer...")))
  16587. ((equal arg '(4))
  16588. (org-with-limited-levels (org-back-to-heading t))
  16589. (setq beg (point))
  16590. (setq end (progn (org-end-of-subtree t) (point)))
  16591. (if (org-remove-latex-fragment-image-overlays beg end)
  16592. (progn
  16593. (message "LaTeX fragment images removed from subtree")
  16594. (throw 'exit nil))
  16595. (setq msg "Creating images for subtree...")))
  16596. ((let ((datum (org-element-context)))
  16597. (when (memq (org-element-type datum)
  16598. '(latex-environment latex-fragment))
  16599. (setq beg (org-element-property :begin datum))
  16600. (setq end (org-element-property :end datum))
  16601. (if (org-remove-latex-fragment-image-overlays beg end)
  16602. (progn (message "LaTeX fragment image removed")
  16603. (throw 'exit nil))
  16604. (setq msg "Creating image...")))))
  16605. (t
  16606. (org-with-limited-levels
  16607. (setq beg (if (org-at-heading-p) (line-beginning-position)
  16608. (outline-previous-heading)
  16609. (point)))
  16610. (setq end (progn (outline-next-heading) (point)))
  16611. (if (org-remove-latex-fragment-image-overlays beg end)
  16612. (progn
  16613. (message "LaTeX fragment images removed from section")
  16614. (throw 'exit nil))
  16615. (setq msg "Creating images for section...")))))
  16616. (let ((file (buffer-file-name (buffer-base-buffer))))
  16617. (org-format-latex
  16618. (concat org-preview-latex-image-directory "org-ltximg")
  16619. beg end
  16620. ;; Emacs cannot overlay images from remote hosts. Create
  16621. ;; it in `temporary-file-directory' instead.
  16622. (if (or (not file) (file-remote-p file))
  16623. temporary-file-directory
  16624. default-directory)
  16625. 'overlays msg 'forbuffer org-preview-latex-default-process))
  16626. (message (concat msg "done")))))))
  16627. (defun org-format-latex
  16628. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  16629. "Replace LaTeX fragments with links to an image.
  16630. The function takes care of creating the replacement image.
  16631. Only consider fragments between BEG and END when those are
  16632. provided.
  16633. When optional argument OVERLAYS is non-nil, display the image on
  16634. top of the fragment instead of replacing it.
  16635. PROCESSING-TYPE is the conversion method to use, as a symbol.
  16636. Some of the options can be changed using the variable
  16637. `org-format-latex-options', which see."
  16638. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  16639. (unless (eq processing-type 'verbatim)
  16640. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  16641. (cnt 0)
  16642. checkdir-flag)
  16643. (goto-char (or beg (point-min)))
  16644. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  16645. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  16646. (overlay-recenter (or end (point-max))))
  16647. (while (re-search-forward math-regexp end t)
  16648. (unless (and overlays
  16649. (eq (get-char-property (point) 'org-overlay-type)
  16650. 'org-latex-overlay))
  16651. (let* ((context (org-element-context))
  16652. (type (org-element-type context)))
  16653. (when (memq type '(latex-environment latex-fragment))
  16654. (let ((block-type (eq type 'latex-environment))
  16655. (value (org-element-property :value context))
  16656. (beg (org-element-property :begin context))
  16657. (end (save-excursion
  16658. (goto-char (org-element-property :end context))
  16659. (skip-chars-backward " \r\t\n")
  16660. (point))))
  16661. (cond
  16662. ((eq processing-type 'mathjax)
  16663. ;; Prepare for MathJax processing.
  16664. (if (not (string-match "\\`\\$\\$?" value))
  16665. (goto-char end)
  16666. (delete-region beg end)
  16667. (if (string= (match-string 0 value) "$$")
  16668. (insert "\\[" (substring value 2 -2) "\\]")
  16669. (insert "\\(" (substring value 1 -1) "\\)"))))
  16670. ((assq processing-type org-preview-latex-process-alist)
  16671. ;; Process to an image.
  16672. (cl-incf cnt)
  16673. (goto-char beg)
  16674. (let* ((processing-info
  16675. (cdr (assq processing-type org-preview-latex-process-alist)))
  16676. (face (face-at-point))
  16677. ;; Get the colors from the face at point.
  16678. (fg
  16679. (let ((color (plist-get org-format-latex-options
  16680. :foreground)))
  16681. (if (and forbuffer (eq color 'auto))
  16682. (face-attribute face :foreground nil 'default)
  16683. color)))
  16684. (bg
  16685. (let ((color (plist-get org-format-latex-options
  16686. :background)))
  16687. (if (and forbuffer (eq color 'auto))
  16688. (face-attribute face :background nil 'default)
  16689. color)))
  16690. (hash (sha1 (prin1-to-string
  16691. (list org-format-latex-header
  16692. org-latex-default-packages-alist
  16693. org-latex-packages-alist
  16694. org-format-latex-options
  16695. forbuffer value fg bg))))
  16696. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  16697. (absprefix (expand-file-name prefix dir))
  16698. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  16699. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  16700. (sep (and block-type "\n\n"))
  16701. (link (concat sep "[[file:" linkfile "]]" sep))
  16702. (options
  16703. (org-combine-plists
  16704. org-format-latex-options
  16705. `(:foreground ,fg :background ,bg))))
  16706. (when msg (message msg cnt))
  16707. (unless checkdir-flag ; Ensure the directory exists.
  16708. (setq checkdir-flag t)
  16709. (let ((todir (file-name-directory absprefix)))
  16710. (unless (file-directory-p todir)
  16711. (make-directory todir t))))
  16712. (unless (file-exists-p movefile)
  16713. (org-create-formula-image
  16714. value movefile options forbuffer processing-type))
  16715. (if overlays
  16716. (progn
  16717. (dolist (o (overlays-in beg end))
  16718. (when (eq (overlay-get o 'org-overlay-type)
  16719. 'org-latex-overlay)
  16720. (delete-overlay o)))
  16721. (org--format-latex-make-overlay beg end movefile imagetype)
  16722. (goto-char end))
  16723. (delete-region beg end)
  16724. (insert
  16725. (org-add-props link
  16726. (list 'org-latex-src
  16727. (replace-regexp-in-string "\"" "" value)
  16728. 'org-latex-src-embed-type
  16729. (if block-type 'paragraph 'character)))))))
  16730. ((eq processing-type 'mathml)
  16731. ;; Process to MathML.
  16732. (unless (org-format-latex-mathml-available-p)
  16733. (user-error "LaTeX to MathML converter not configured"))
  16734. (cl-incf cnt)
  16735. (when msg (message msg cnt))
  16736. (goto-char beg)
  16737. (delete-region beg end)
  16738. (insert (org-format-latex-as-mathml
  16739. value block-type prefix dir)))
  16740. (t
  16741. (error "Unknown conversion process %s for LaTeX fragments"
  16742. processing-type)))))))))))
  16743. (defun org-create-math-formula (latex-frag &optional mathml-file)
  16744. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  16745. Use `org-latex-to-mathml-convert-command'. If the conversion is
  16746. sucessful, return the portion between \"<math...> </math>\"
  16747. elements otherwise return nil. When MATHML-FILE is specified,
  16748. write the results in to that file. When invoked as an
  16749. interactive command, prompt for LATEX-FRAG, with initial value
  16750. set to the current active region and echo the results for user
  16751. inspection."
  16752. (interactive (list (let ((frag (when (org-region-active-p)
  16753. (buffer-substring-no-properties
  16754. (region-beginning) (region-end)))))
  16755. (read-string "LaTeX Fragment: " frag nil frag))))
  16756. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  16757. (let* ((tmp-in-file
  16758. (let ((file (file-relative-name
  16759. (make-temp-name (expand-file-name "ltxmathml-in")))))
  16760. (write-region latex-frag nil file)
  16761. file))
  16762. (tmp-out-file (file-relative-name
  16763. (make-temp-name (expand-file-name "ltxmathml-out"))))
  16764. (cmd (format-spec
  16765. org-latex-to-mathml-convert-command
  16766. `((?j . ,(and org-latex-to-mathml-jar-file
  16767. (shell-quote-argument
  16768. (expand-file-name
  16769. org-latex-to-mathml-jar-file))))
  16770. (?I . ,(shell-quote-argument tmp-in-file))
  16771. (?i . ,latex-frag)
  16772. (?o . ,(shell-quote-argument tmp-out-file)))))
  16773. mathml shell-command-output)
  16774. (when (called-interactively-p 'any)
  16775. (unless (org-format-latex-mathml-available-p)
  16776. (user-error "LaTeX to MathML converter not configured")))
  16777. (message "Running %s" cmd)
  16778. (setq shell-command-output (shell-command-to-string cmd))
  16779. (setq mathml
  16780. (when (file-readable-p tmp-out-file)
  16781. (with-current-buffer (find-file-noselect tmp-out-file t)
  16782. (goto-char (point-min))
  16783. (when (re-search-forward
  16784. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  16785. (regexp-quote
  16786. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  16787. nil t)
  16788. (prog1 (match-string 0) (kill-buffer))))))
  16789. (cond
  16790. (mathml
  16791. (setq mathml
  16792. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  16793. (when mathml-file
  16794. (write-region mathml nil mathml-file))
  16795. (when (called-interactively-p 'any)
  16796. (message mathml)))
  16797. ((message "LaTeX to MathML conversion failed")
  16798. (message shell-command-output)))
  16799. (delete-file tmp-in-file)
  16800. (when (file-exists-p tmp-out-file)
  16801. (delete-file tmp-out-file))
  16802. mathml))
  16803. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  16804. prefix &optional dir)
  16805. "Use `org-create-math-formula' but check local cache first."
  16806. (let* ((absprefix (expand-file-name prefix dir))
  16807. (print-length nil) (print-level nil)
  16808. (formula-id (concat
  16809. "formula-"
  16810. (sha1
  16811. (prin1-to-string
  16812. (list latex-frag
  16813. org-latex-to-mathml-convert-command)))))
  16814. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  16815. (formula-cache-dir (file-name-directory formula-cache)))
  16816. (unless (file-directory-p formula-cache-dir)
  16817. (make-directory formula-cache-dir t))
  16818. (unless (file-exists-p formula-cache)
  16819. (org-create-math-formula latex-frag formula-cache))
  16820. (if (file-exists-p formula-cache)
  16821. ;; Successful conversion. Return the link to MathML file.
  16822. (org-add-props
  16823. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  16824. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  16825. 'org-latex-src-embed-type (if latex-frag-type
  16826. 'paragraph 'character)))
  16827. ;; Failed conversion. Return the LaTeX fragment verbatim
  16828. latex-frag)))
  16829. (defun org--get-display-dpi ()
  16830. "Get the DPI of the display.
  16831. The function assumes that the display has the same pixel width in
  16832. the horizontal and vertical directions."
  16833. (if (display-graphic-p)
  16834. (round (/ (display-pixel-height)
  16835. (/ (display-mm-height) 25.4)))
  16836. (error "Attempt to calculate the dpi of a non-graphic display")))
  16837. (defun org-create-formula-image
  16838. (string tofile options buffer &optional processing-type)
  16839. "Create an image from LaTeX source using external processes.
  16840. The LaTeX STRING is saved to a temporary LaTeX file, then
  16841. converted to an image file by process PROCESSING-TYPE defined in
  16842. `org-preview-latex-process-alist'. A nil value defaults to
  16843. `org-preview-latex-default-process'.
  16844. The generated image file is eventually moved to TOFILE.
  16845. The OPTIONS argument controls the size, foreground color and
  16846. background color of the generated image.
  16847. When BUFFER non-nil, this function is used for LaTeX previewing.
  16848. Otherwise, it is used to deal with LaTeX snippets showed in
  16849. a HTML file."
  16850. (let* ((processing-type (or processing-type
  16851. org-preview-latex-default-process))
  16852. (processing-info
  16853. (cdr (assq processing-type org-preview-latex-process-alist)))
  16854. (programs (plist-get processing-info :programs))
  16855. (error-message (or (plist-get processing-info :message) ""))
  16856. (use-xcolor (plist-get processing-info :use-xcolor))
  16857. (image-input-type (plist-get processing-info :image-input-type))
  16858. (image-output-type (plist-get processing-info :image-output-type))
  16859. (post-clean (or (plist-get processing-info :post-clean)
  16860. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  16861. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  16862. (latex-header
  16863. (or (plist-get processing-info :latex-header)
  16864. (org-latex-make-preamble
  16865. (org-export-get-environment (org-export-get-backend 'latex))
  16866. org-format-latex-header
  16867. 'snippet)))
  16868. (latex-compiler (plist-get processing-info :latex-compiler))
  16869. (image-converter (plist-get processing-info :image-converter))
  16870. (tmpdir temporary-file-directory)
  16871. (texfilebase (make-temp-name
  16872. (expand-file-name "orgtex" tmpdir)))
  16873. (texfile (concat texfilebase ".tex"))
  16874. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  16875. '(1.0 . 1.0)))
  16876. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  16877. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  16878. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  16879. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  16880. "Black"))
  16881. (bg (or (plist-get options (if buffer :background :html-background))
  16882. "Transparent"))
  16883. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  16884. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  16885. (dolist (program programs)
  16886. (org-check-external-command program error-message))
  16887. (if use-xcolor
  16888. (progn (if (eq fg 'default)
  16889. (setq fg (org-latex-color :foreground))
  16890. (setq fg (org-latex-color-format fg)))
  16891. (if (eq bg 'default)
  16892. (setq bg (org-latex-color :background))
  16893. (setq bg (org-latex-color-format
  16894. (if (string= bg "Transparent") "white" bg))))
  16895. (with-temp-file texfile
  16896. (insert latex-header)
  16897. (insert "\n\\begin{document}\n"
  16898. "\\definecolor{fg}{rgb}{" fg "}\n"
  16899. "\\definecolor{bg}{rgb}{" bg "}\n"
  16900. "\n\\pagecolor{bg}\n"
  16901. "\n{\\color{fg}\n"
  16902. string
  16903. "\n}\n"
  16904. "\n\\end{document}\n")))
  16905. (if (eq fg 'default)
  16906. (setq fg (org-dvipng-color :foreground))
  16907. (unless (string= fg "Transparent")
  16908. (setq fg (org-dvipng-color-format fg))))
  16909. (if (eq bg 'default)
  16910. (setq bg (org-dvipng-color :background))
  16911. (unless (string= bg "Transparent")
  16912. (setq bg (org-dvipng-color-format bg))))
  16913. (with-temp-file texfile
  16914. (insert latex-header)
  16915. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  16916. (let* ((err-msg (format "Please adjust `%s' part of \
  16917. `org-preview-latex-process-alist'."
  16918. processing-type))
  16919. (image-input-file
  16920. (org-compile-file
  16921. texfile latex-compiler image-input-type err-msg log-buf))
  16922. (image-output-file
  16923. (org-compile-file
  16924. image-input-file image-converter image-output-type err-msg log-buf
  16925. `((?F . ,(shell-quote-argument fg))
  16926. (?B . ,(shell-quote-argument bg))
  16927. (?D . ,(shell-quote-argument (format "%s" dpi)))
  16928. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  16929. (copy-file image-output-file tofile 'replace)
  16930. (dolist (e post-clean)
  16931. (when (file-exists-p (concat texfilebase e))
  16932. (delete-file (concat texfilebase e))))
  16933. image-output-file)))
  16934. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  16935. "Fill a LaTeX header template TPL.
  16936. In the template, the following place holders will be recognized:
  16937. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  16938. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  16939. [PACKAGES] \\usepackage statements for PKG
  16940. [NO-PACKAGES] do not include PKG
  16941. [EXTRA] the string EXTRA
  16942. [NO-EXTRA] do not include EXTRA
  16943. For backward compatibility, if both the positive and the negative place
  16944. holder is missing, the positive one (without the \"NO-\") will be
  16945. assumed to be present at the end of the template.
  16946. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  16947. EXTRA is a string.
  16948. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  16949. (let (rpl (end ""))
  16950. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  16951. (setq rpl (if (or (match-end 1) (not def-pkg))
  16952. "" (org-latex-packages-to-string def-pkg snippets-p t))
  16953. tpl (replace-match rpl t t tpl))
  16954. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  16955. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  16956. (setq rpl (if (or (match-end 1) (not pkg))
  16957. "" (org-latex-packages-to-string pkg snippets-p t))
  16958. tpl (replace-match rpl t t tpl))
  16959. (when pkg (setq end
  16960. (concat end "\n"
  16961. (org-latex-packages-to-string pkg snippets-p)))))
  16962. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  16963. (setq rpl (if (or (match-end 1) (not extra))
  16964. "" (concat extra "\n"))
  16965. tpl (replace-match rpl t t tpl))
  16966. (when (and extra (string-match "\\S-" extra))
  16967. (setq end (concat end "\n" extra))))
  16968. (if (string-match "\\S-" end)
  16969. (concat tpl "\n" end)
  16970. tpl)))
  16971. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  16972. "Turn an alist of packages into a string with the \\usepackage macros."
  16973. (setq pkg (mapconcat (lambda(p)
  16974. (cond
  16975. ((stringp p) p)
  16976. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  16977. (format "%% Package %s omitted" (cadr p)))
  16978. ((equal "" (car p))
  16979. (format "\\usepackage{%s}" (cadr p)))
  16980. (t
  16981. (format "\\usepackage[%s]{%s}"
  16982. (car p) (cadr p)))))
  16983. pkg
  16984. "\n"))
  16985. (if newline (concat pkg "\n") pkg))
  16986. (defun org-dvipng-color (attr)
  16987. "Return a RGB color specification for dvipng."
  16988. (org-dvipng-color-format (face-attribute 'default attr nil)))
  16989. (defun org-dvipng-color-format (color-name)
  16990. "Convert COLOR-NAME to a RGB color value for dvipng."
  16991. (apply #'format "rgb %s %s %s"
  16992. (mapcar 'org-normalize-color
  16993. (color-values color-name))))
  16994. (defun org-latex-color (attr)
  16995. "Return a RGB color for the LaTeX color package."
  16996. (org-latex-color-format (face-attribute 'default attr nil)))
  16997. (defun org-latex-color-format (color-name)
  16998. "Convert COLOR-NAME to a RGB color value."
  16999. (apply #'format "%s,%s,%s"
  17000. (mapcar 'org-normalize-color
  17001. (color-values color-name))))
  17002. (defun org-normalize-color (value)
  17003. "Return string to be used as color value for an RGB component."
  17004. (format "%g" (/ value 65535.0)))
  17005. ;; Image display
  17006. (defvar-local org-inline-image-overlays nil)
  17007. (defun org-toggle-inline-images (&optional include-linked)
  17008. "Toggle the display of inline images.
  17009. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17010. (interactive "P")
  17011. (if org-inline-image-overlays
  17012. (progn
  17013. (org-remove-inline-images)
  17014. (when (called-interactively-p 'interactive)
  17015. (message "Inline image display turned off")))
  17016. (org-display-inline-images include-linked)
  17017. (when (called-interactively-p 'interactive)
  17018. (message (if org-inline-image-overlays
  17019. (format "%d images displayed inline"
  17020. (length org-inline-image-overlays))
  17021. "No images to display inline")))))
  17022. (defun org-redisplay-inline-images ()
  17023. "Refresh the display of inline images."
  17024. (interactive)
  17025. (if (not org-inline-image-overlays)
  17026. (org-toggle-inline-images)
  17027. (org-toggle-inline-images)
  17028. (org-toggle-inline-images)))
  17029. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17030. "Display inline images.
  17031. An inline image is a link which follows either of these
  17032. conventions:
  17033. 1. Its path is a file with an extension matching return value
  17034. from `image-file-name-regexp' and it has no contents.
  17035. 2. Its description consists in a single link of the previous
  17036. type.
  17037. When optional argument INCLUDE-LINKED is non-nil, also links with
  17038. a text description part will be inlined. This can be nice for
  17039. a quick look at those images, but it does not reflect what
  17040. exported files will look like.
  17041. When optional argument REFRESH is non-nil, refresh existing
  17042. images between BEG and END. This will create new image displays
  17043. only if necessary. BEG and END default to the buffer
  17044. boundaries."
  17045. (interactive "P")
  17046. (when (display-graphic-p)
  17047. (unless refresh
  17048. (org-remove-inline-images)
  17049. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17050. (org-with-wide-buffer
  17051. (goto-char (or beg (point-min)))
  17052. (let* ((case-fold-search t)
  17053. (file-extension-re (image-file-name-regexp))
  17054. (link-abbrevs (mapcar #'car
  17055. (append org-link-abbrev-alist-local
  17056. org-link-abbrev-alist)))
  17057. ;; Check absolute, relative file names and explicit
  17058. ;; "file:" links. Also check link abbreviations since
  17059. ;; some might expand to "file" links.
  17060. (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
  17061. (if (not link-abbrevs) ""
  17062. (format "\\|\\(?:%s:\\)"
  17063. (regexp-opt link-abbrevs))))))
  17064. (while (re-search-forward file-types-re end t)
  17065. (let ((link (save-match-data (org-element-context))))
  17066. ;; Check if we're at an inline image, i.e., an image file
  17067. ;; link without a description (unless INCLUDE-LINKED is
  17068. ;; non-nil).
  17069. (when (and (equal "file" (org-element-property :type link))
  17070. (or include-linked
  17071. (null (org-element-contents link)))
  17072. (string-match-p file-extension-re
  17073. (org-element-property :path link)))
  17074. (let ((file (expand-file-name
  17075. (org-link-unescape
  17076. (org-element-property :path link)))))
  17077. (when (file-exists-p file)
  17078. (let ((width
  17079. ;; Apply `org-image-actual-width' specifications.
  17080. (cond
  17081. ((not (image-type-available-p 'imagemagick)) nil)
  17082. ((eq org-image-actual-width t) nil)
  17083. ((listp org-image-actual-width)
  17084. (or
  17085. ;; First try to find a width among
  17086. ;; attributes associated to the paragraph
  17087. ;; containing link.
  17088. (let ((paragraph
  17089. (let ((e link))
  17090. (while (and (setq e (org-element-property
  17091. :parent e))
  17092. (not (eq (org-element-type e)
  17093. 'paragraph))))
  17094. e)))
  17095. (when paragraph
  17096. (save-excursion
  17097. (goto-char (org-element-property :begin paragraph))
  17098. (when
  17099. (re-search-forward
  17100. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17101. (org-element-property
  17102. :post-affiliated paragraph)
  17103. t)
  17104. (string-to-number (match-string 1))))))
  17105. ;; Otherwise, fall-back to provided number.
  17106. (car org-image-actual-width)))
  17107. ((numberp org-image-actual-width)
  17108. org-image-actual-width)))
  17109. (old (get-char-property-and-overlay
  17110. (org-element-property :begin link)
  17111. 'org-image-overlay)))
  17112. (if (and (car-safe old) refresh)
  17113. (image-refresh (overlay-get (cdr old) 'display))
  17114. (let ((image (create-image file
  17115. (and width 'imagemagick)
  17116. nil
  17117. :width width)))
  17118. (when image
  17119. (let ((ov (make-overlay
  17120. (org-element-property :begin link)
  17121. (progn
  17122. (goto-char
  17123. (org-element-property :end link))
  17124. (skip-chars-backward " \t")
  17125. (point)))))
  17126. (overlay-put ov 'display image)
  17127. (overlay-put ov 'face 'default)
  17128. (overlay-put ov 'org-image-overlay t)
  17129. (overlay-put
  17130. ov 'modification-hooks
  17131. (list 'org-display-inline-remove-overlay))
  17132. (push ov org-inline-image-overlays)))))))))))))))
  17133. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17134. "Remove inline-display overlay if a corresponding region is modified."
  17135. (let ((inhibit-modification-hooks t))
  17136. (when (and ov after)
  17137. (delete ov org-inline-image-overlays)
  17138. (delete-overlay ov))))
  17139. (defun org-remove-inline-images ()
  17140. "Remove inline display of images."
  17141. (interactive)
  17142. (mapc #'delete-overlay org-inline-image-overlays)
  17143. (setq org-inline-image-overlays nil))
  17144. ;;; Key bindings
  17145. (defun org-remap (map &rest commands)
  17146. "In MAP, remap the functions given in COMMANDS.
  17147. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  17148. (let (new old)
  17149. (while commands
  17150. (setq old (pop commands) new (pop commands))
  17151. (org-defkey map (vector 'remap old) new))))
  17152. ;;;; Outline functions that can be remapped in Org
  17153. (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
  17154. (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
  17155. (define-key org-mode-map [remap outline-forward-same-level]
  17156. #'org-forward-heading-same-level)
  17157. (define-key org-mode-map [remap outline-backward-same-level]
  17158. #'org-backward-heading-same-level)
  17159. (define-key org-mode-map [remap outline-show-branches]
  17160. #'org-kill-note-or-show-branches)
  17161. (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
  17162. (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
  17163. (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
  17164. (define-key org-mode-map [remap outline-next-visible-heading]
  17165. #'org-next-visible-heading)
  17166. (define-key org-mode-map [remap outline-previous-visible-heading]
  17167. #'org-previous-visible-heading)
  17168. (define-key org-mode-map [remap show-children] #'org-show-children)
  17169. ;;;; Make `C-c C-x' a prefix key
  17170. (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
  17171. ;;;; TAB key with modifiers
  17172. (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
  17173. (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
  17174. (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
  17175. (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
  17176. (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
  17177. (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
  17178. (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
  17179. (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
  17180. ;;;; RET key with modifiers
  17181. (org-defkey org-mode-map (kbd "S-<return>") #'org-table-copy-down)
  17182. (org-defkey org-mode-map (kbd "M-S-<return>") #'org-insert-todo-heading)
  17183. (org-defkey org-mode-map (kbd "ESC S-<return>") #'org-insert-todo-heading)
  17184. (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
  17185. (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
  17186. ;;;; Cursor keys with modifiers
  17187. (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
  17188. (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
  17189. (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
  17190. (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
  17191. (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
  17192. (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
  17193. (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
  17194. (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
  17195. (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
  17196. (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
  17197. (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
  17198. (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
  17199. (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
  17200. (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
  17201. (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
  17202. (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
  17203. (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
  17204. (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
  17205. (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
  17206. (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
  17207. (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
  17208. (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
  17209. (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
  17210. (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
  17211. (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
  17212. ;;;; Babel keys
  17213. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  17214. (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
  17215. (define-key org-babel-map key def))
  17216. ;;;; Extra keys for TTY access.
  17217. ;; We only set them when really needed because otherwise the
  17218. ;; menus don't show the simple keys
  17219. (when (or org-use-extra-keys (not window-system))
  17220. (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
  17221. (org-defkey org-mode-map (kbd "C-c C-x m") #'org-meta-return)
  17222. (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
  17223. (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
  17224. (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
  17225. (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
  17226. (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
  17227. (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
  17228. (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
  17229. (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
  17230. (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
  17231. (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
  17232. (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
  17233. (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
  17234. (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
  17235. (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
  17236. (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
  17237. (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
  17238. (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
  17239. (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
  17240. (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
  17241. ;;;; Narrow map
  17242. (org-defkey narrow-map "s" #'org-narrow-to-subtree)
  17243. (org-defkey narrow-map "b" #'org-narrow-to-block)
  17244. (org-defkey narrow-map "e" #'org-narrow-to-element)
  17245. ;;;; Remap usual Emacs bindings
  17246. (org-remap org-mode-map
  17247. 'self-insert-command 'org-self-insert-command
  17248. 'delete-char 'org-delete-char
  17249. 'delete-backward-char 'org-delete-backward-char
  17250. 'kill-line 'org-kill-line
  17251. 'open-line 'org-open-line
  17252. 'yank 'org-yank
  17253. 'comment-dwim 'org-comment-dwim
  17254. 'move-beginning-of-line 'org-beginning-of-line
  17255. 'move-end-of-line 'org-end-of-line
  17256. 'forward-paragraph 'org-forward-paragraph
  17257. 'backward-paragraph 'org-backward-paragraph
  17258. 'backward-sentence 'org-backward-sentence
  17259. 'forward-sentence 'org-forward-sentence
  17260. 'fill-paragraph 'org-fill-paragraph
  17261. 'delete-indentation 'org-delete-indentation
  17262. 'transpose-words 'org-transpose-words)
  17263. ;;;; All the other keys
  17264. (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
  17265. (org-defkey org-mode-map (kbd "C-c C-a") #'org-show-all)
  17266. (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
  17267. (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
  17268. (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
  17269. (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
  17270. (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
  17271. (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
  17272. (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
  17273. (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
  17274. (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
  17275. (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
  17276. (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
  17277. (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
  17278. (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
  17279. (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
  17280. (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
  17281. (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
  17282. (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
  17283. (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
  17284. (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
  17285. (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
  17286. (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
  17287. (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
  17288. (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
  17289. (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
  17290. (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
  17291. (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
  17292. (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
  17293. (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
  17294. (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
  17295. (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
  17296. (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
  17297. (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
  17298. (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
  17299. (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
  17300. (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
  17301. (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
  17302. (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
  17303. (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
  17304. (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
  17305. (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
  17306. (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
  17307. (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
  17308. (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
  17309. (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
  17310. (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
  17311. (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
  17312. (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
  17313. (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
  17314. (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
  17315. (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
  17316. (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
  17317. (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
  17318. (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
  17319. (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
  17320. (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
  17321. (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
  17322. (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
  17323. (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
  17324. (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
  17325. (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
  17326. (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
  17327. (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
  17328. (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
  17329. (org-defkey org-mode-map (kbd "RET") #'org-return)
  17330. (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
  17331. (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
  17332. (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
  17333. (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
  17334. (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
  17335. (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
  17336. (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
  17337. (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
  17338. (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
  17339. (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
  17340. (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
  17341. (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
  17342. (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
  17343. (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
  17344. (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
  17345. (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
  17346. (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
  17347. (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
  17348. (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
  17349. (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
  17350. (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
  17351. (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
  17352. (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
  17353. (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
  17354. (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
  17355. (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
  17356. (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
  17357. (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
  17358. (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
  17359. (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
  17360. (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
  17361. (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
  17362. (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
  17363. (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
  17364. (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
  17365. (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
  17366. (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
  17367. (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
  17368. (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
  17369. (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
  17370. (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
  17371. (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
  17372. (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
  17373. (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
  17374. (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
  17375. (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
  17376. (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
  17377. (org-defkey org-mode-map (kbd "C-c C-,") #'org-insert-structure-template)
  17378. (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
  17379. (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
  17380. (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
  17381. (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
  17382. (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
  17383. (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
  17384. (define-key org-mode-map (kbd "C-c C-x C-c") #'org-columns)
  17385. (define-key org-mode-map (kbd "C-c C-x !") #'org-reload)
  17386. (define-key org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
  17387. (define-key org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
  17388. (define-key org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
  17389. ;;; Speed commands
  17390. (defconst org-speed-commands-default
  17391. '(
  17392. ("Outline Navigation")
  17393. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  17394. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  17395. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  17396. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  17397. ("F" . org-next-block)
  17398. ("B" . org-previous-block)
  17399. ("u" . (org-speed-move-safe 'outline-up-heading))
  17400. ("j" . org-goto)
  17401. ("g" . (org-refile t))
  17402. ("Outline Visibility")
  17403. ("c" . org-cycle)
  17404. ("C" . org-shifttab)
  17405. (" " . org-display-outline-path)
  17406. ("s" . org-narrow-to-subtree)
  17407. ("=" . org-columns)
  17408. ("Outline Structure Editing")
  17409. ("U" . org-metaup)
  17410. ("D" . org-metadown)
  17411. ("r" . org-metaright)
  17412. ("l" . org-metaleft)
  17413. ("R" . org-shiftmetaright)
  17414. ("L" . org-shiftmetaleft)
  17415. ("i" . (progn (forward-char 1) (call-interactively
  17416. 'org-insert-heading-respect-content)))
  17417. ("^" . org-sort)
  17418. ("w" . org-refile)
  17419. ("a" . org-archive-subtree-default-with-confirmation)
  17420. ("@" . org-mark-subtree)
  17421. ("#" . org-toggle-comment)
  17422. ("Clock Commands")
  17423. ("I" . org-clock-in)
  17424. ("O" . org-clock-out)
  17425. ("Meta Data Editing")
  17426. ("t" . org-todo)
  17427. ("," . (org-priority))
  17428. ("0" . (org-priority ?\ ))
  17429. ("1" . (org-priority ?A))
  17430. ("2" . (org-priority ?B))
  17431. ("3" . (org-priority ?C))
  17432. (":" . org-set-tags-command)
  17433. ("e" . org-set-effort)
  17434. ("E" . org-inc-effort)
  17435. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  17436. (org-entry-put (point) "APPT_WARNTIME" m)))
  17437. ("Agenda Views etc")
  17438. ("v" . org-agenda)
  17439. ("/" . org-sparse-tree)
  17440. ("Misc")
  17441. ("o" . org-open-at-point)
  17442. ("?" . org-speed-command-help)
  17443. ("<" . (org-agenda-set-restriction-lock 'subtree))
  17444. (">" . (org-agenda-remove-restriction-lock))
  17445. )
  17446. "The default speed commands.")
  17447. (defun org-print-speed-command (e)
  17448. (if (> (length (car e)) 1)
  17449. (progn
  17450. (princ "\n")
  17451. (princ (car e))
  17452. (princ "\n")
  17453. (princ (make-string (length (car e)) ?-))
  17454. (princ "\n"))
  17455. (princ (car e))
  17456. (princ " ")
  17457. (if (symbolp (cdr e))
  17458. (princ (symbol-name (cdr e)))
  17459. (prin1 (cdr e)))
  17460. (princ "\n")))
  17461. (defun org-speed-command-help ()
  17462. "Show the available speed commands."
  17463. (interactive)
  17464. (if (not org-use-speed-commands)
  17465. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  17466. (with-output-to-temp-buffer "*Help*"
  17467. (princ "User-defined Speed commands\n===========================\n")
  17468. (mapc #'org-print-speed-command org-speed-commands-user)
  17469. (princ "\n")
  17470. (princ "Built-in Speed commands\n=======================\n")
  17471. (mapc #'org-print-speed-command org-speed-commands-default))
  17472. (with-current-buffer "*Help*"
  17473. (setq truncate-lines t))))
  17474. (defun org-speed-move-safe (cmd)
  17475. "Execute CMD, but make sure that the cursor always ends up in a headline.
  17476. If not, return to the original position and throw an error."
  17477. (interactive)
  17478. (let ((pos (point)))
  17479. (call-interactively cmd)
  17480. (unless (and (bolp) (org-at-heading-p))
  17481. (goto-char pos)
  17482. (error "Boundary reached while executing %s" cmd))))
  17483. (defvar org-self-insert-command-undo-counter 0)
  17484. (defvar org-table-auto-blank-field) ; defined in org-table.el
  17485. (defvar org-speed-command nil)
  17486. (defun org-speed-command-activate (keys)
  17487. "Hook for activating single-letter speed commands.
  17488. `org-speed-commands-default' specifies a minimal command set.
  17489. Use `org-speed-commands-user' for further customization."
  17490. (when (or (and (bolp) (looking-at org-outline-regexp))
  17491. (and (functionp org-use-speed-commands)
  17492. (funcall org-use-speed-commands)))
  17493. (cdr (assoc keys (append org-speed-commands-user
  17494. org-speed-commands-default)))))
  17495. (defun org-babel-speed-command-activate (keys)
  17496. "Hook for activating single-letter code block commands."
  17497. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  17498. (cdr (assoc keys org-babel-key-bindings))))
  17499. (defcustom org-speed-command-hook
  17500. '(org-speed-command-activate org-babel-speed-command-activate)
  17501. "Hook for activating speed commands at strategic locations.
  17502. Hook functions are called in sequence until a valid handler is
  17503. found.
  17504. Each hook takes a single argument, a user-pressed command key
  17505. which is also a `self-insert-command' from the global map.
  17506. Within the hook, examine the cursor position and the command key
  17507. and return nil or a valid handler as appropriate. Handler could
  17508. be one of an interactive command, a function, or a form.
  17509. Set `org-use-speed-commands' to non-nil value to enable this
  17510. hook. The default setting is `org-speed-command-activate'."
  17511. :group 'org-structure
  17512. :version "24.1"
  17513. :type 'hook)
  17514. (defun org-self-insert-command (N)
  17515. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  17516. If the cursor is in a table looking at whitespace, the whitespace is
  17517. overwritten, and the table is not marked as requiring realignment."
  17518. (interactive "p")
  17519. (org-check-before-invisible-edit 'insert)
  17520. (cond
  17521. ((and org-use-speed-commands
  17522. (let ((kv (this-command-keys-vector)))
  17523. (setq org-speed-command
  17524. (run-hook-with-args-until-success
  17525. 'org-speed-command-hook
  17526. (make-string 1 (aref kv (1- (length kv))))))))
  17527. (cond
  17528. ((commandp org-speed-command)
  17529. (setq this-command org-speed-command)
  17530. (call-interactively org-speed-command))
  17531. ((functionp org-speed-command)
  17532. (funcall org-speed-command))
  17533. ((and org-speed-command (listp org-speed-command))
  17534. (eval org-speed-command))
  17535. (t (let (org-use-speed-commands)
  17536. (call-interactively 'org-self-insert-command)))))
  17537. ((and
  17538. (= N 1)
  17539. (not (org-region-active-p))
  17540. (org-at-table-p)
  17541. (progn
  17542. ;; Check if we blank the field, and if that triggers align.
  17543. (and (featurep 'org-table)
  17544. org-table-auto-blank-field
  17545. (memq last-command
  17546. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  17547. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  17548. ;; Got extra space, this field does not determine
  17549. ;; column width.
  17550. (let (org-table-may-need-update) (org-table-blank-field))
  17551. ;; No extra space, this field may determine column
  17552. ;; width.
  17553. (org-table-blank-field)))
  17554. t)
  17555. (looking-at "[^|\n]* |"))
  17556. ;; There is room for insertion without re-aligning the table.
  17557. (self-insert-command N)
  17558. (org-table-with-shrunk-field
  17559. (save-excursion
  17560. (skip-chars-forward "^|")
  17561. ;; Do not delete last space, which is
  17562. ;; `org-table-separator-space', but the regular space before
  17563. ;; it.
  17564. (delete-region (- (point) 2) (1- (point))))))
  17565. (t
  17566. (setq org-table-may-need-update t)
  17567. (self-insert-command N)
  17568. (org-fix-tags-on-the-fly)
  17569. (when org-self-insert-cluster-for-undo
  17570. (if (not (eq last-command 'org-self-insert-command))
  17571. (setq org-self-insert-command-undo-counter 1)
  17572. (if (>= org-self-insert-command-undo-counter 20)
  17573. (setq org-self-insert-command-undo-counter 1)
  17574. (and (> org-self-insert-command-undo-counter 0)
  17575. buffer-undo-list (listp buffer-undo-list)
  17576. (not (cadr buffer-undo-list)) ; remove nil entry
  17577. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  17578. (setq org-self-insert-command-undo-counter
  17579. (1+ org-self-insert-command-undo-counter))))))))
  17580. (defun org-check-before-invisible-edit (kind)
  17581. "Check is editing if kind KIND would be dangerous with invisible text around.
  17582. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  17583. ;; First, try to get out of here as quickly as possible, to reduce overhead
  17584. (when (and org-catch-invisible-edits
  17585. (or (not (boundp 'visible-mode)) (not visible-mode))
  17586. (or (get-char-property (point) 'invisible)
  17587. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  17588. ;; OK, we need to take a closer look. Do not consider
  17589. ;; invisibility obtained through text properties (e.g., link
  17590. ;; fontification), as it cannot be toggled.
  17591. (let* ((invisible-at-point
  17592. (pcase (get-char-property-and-overlay (point) 'invisible)
  17593. (`(,_ . ,(and (pred overlayp) o)) o)))
  17594. ;; Assume that point cannot land in the middle of an
  17595. ;; overlay, or between two overlays.
  17596. (invisible-before-point
  17597. (and (not invisible-at-point)
  17598. (not (bobp))
  17599. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  17600. (`(,_ . ,(and (pred overlayp) o)) o))))
  17601. (border-and-ok-direction
  17602. (or
  17603. ;; Check if we are acting predictably before invisible
  17604. ;; text.
  17605. (and invisible-at-point
  17606. (memq kind '(insert delete-backward)))
  17607. ;; Check if we are acting predictably after invisible text
  17608. ;; This works not well, and I have turned it off. It seems
  17609. ;; better to always show and stop after invisible text.
  17610. ;; (and (not invisible-at-point) invisible-before-point
  17611. ;; (memq kind '(insert delete)))
  17612. )))
  17613. (when (or invisible-at-point invisible-before-point)
  17614. (when (eq org-catch-invisible-edits 'error)
  17615. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  17616. (if (and org-custom-properties-overlays
  17617. (y-or-n-p "Display invisible properties in this buffer? "))
  17618. (org-toggle-custom-properties-visibility)
  17619. ;; Make the area visible
  17620. (save-excursion
  17621. (when invisible-before-point
  17622. (goto-char
  17623. (previous-single-char-property-change (point) 'invisible)))
  17624. ;; Remove whatever overlay is currently making yet-to-be
  17625. ;; edited text invisible. Also remove nested invisibility
  17626. ;; related overlays.
  17627. (delete-overlay (or invisible-at-point invisible-before-point))
  17628. (let ((origin (if invisible-at-point (point) (1- (point)))))
  17629. (while (pcase (get-char-property-and-overlay origin 'invisible)
  17630. (`(,_ . ,(and (pred overlayp) o))
  17631. (delete-overlay o)
  17632. t)))))
  17633. (cond
  17634. ((eq org-catch-invisible-edits 'show)
  17635. ;; That's it, we do the edit after showing
  17636. (message
  17637. "Unfolding invisible region around point before editing")
  17638. (sit-for 1))
  17639. ((and (eq org-catch-invisible-edits 'smart)
  17640. border-and-ok-direction)
  17641. (message "Unfolding invisible region around point before editing"))
  17642. (t
  17643. ;; Don't do the edit, make the user repeat it in full visibility
  17644. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  17645. (defun org-fix-tags-on-the-fly ()
  17646. "Align tags in headline at point.
  17647. Unlike to `org-align-tags', this function does nothing if point
  17648. is not currently on a headline."
  17649. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  17650. (org-at-heading-p))
  17651. (org-align-tags)))
  17652. (defun org-delete-backward-char (N)
  17653. "Like `delete-backward-char', insert whitespace at field end in tables.
  17654. When deleting backwards, in tables this function will insert whitespace in
  17655. front of the next \"|\" separator, to keep the table aligned. The table will
  17656. still be marked for re-alignment if the field did fill the entire column,
  17657. because, in this case the deletion might narrow the column."
  17658. (interactive "p")
  17659. (save-match-data
  17660. (org-check-before-invisible-edit 'delete-backward)
  17661. (if (and (= N 1)
  17662. (not overwrite-mode)
  17663. (not (org-region-active-p))
  17664. (not (eq (char-before) ?|))
  17665. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  17666. (looking-at-p ".*?|")
  17667. (org-at-table-p))
  17668. (progn (forward-char -1) (org-delete-char 1))
  17669. (backward-delete-char N)
  17670. (org-fix-tags-on-the-fly))))
  17671. (defun org-delete-char (N)
  17672. "Like `delete-char', but insert whitespace at field end in tables.
  17673. When deleting characters, in tables this function will insert whitespace in
  17674. front of the next \"|\" separator, to keep the table aligned. The table will
  17675. still be marked for re-alignment if the field did fill the entire column,
  17676. because, in this case the deletion might narrow the column."
  17677. (interactive "p")
  17678. (save-match-data
  17679. (org-check-before-invisible-edit 'delete)
  17680. (cond
  17681. ((or (/= N 1)
  17682. (eq (char-after) ?|)
  17683. (save-excursion (skip-chars-backward " \t") (bolp))
  17684. (not (org-at-table-p)))
  17685. (delete-char N)
  17686. (org-fix-tags-on-the-fly))
  17687. ((looking-at ".\\(.*?\\)|")
  17688. (let* ((update? org-table-may-need-update)
  17689. (noalign (looking-at-p ".*? |")))
  17690. (delete-char 1)
  17691. (org-table-with-shrunk-field
  17692. (save-excursion
  17693. ;; Last space is `org-table-separator-space', so insert
  17694. ;; a regular one before it instead.
  17695. (goto-char (- (match-end 0) 2))
  17696. (insert " ")))
  17697. ;; If there were two spaces at the end, this field does not
  17698. ;; determine the width of the column.
  17699. (when noalign (setq org-table-may-need-update update?))))
  17700. (t
  17701. (delete-char N)))))
  17702. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  17703. (put 'org-self-insert-command 'delete-selection
  17704. (lambda ()
  17705. (not (run-hook-with-args-until-success
  17706. 'self-insert-uses-region-functions))))
  17707. (put 'orgtbl-self-insert-command 'delete-selection
  17708. (lambda ()
  17709. (not (run-hook-with-args-until-success
  17710. 'self-insert-uses-region-functions))))
  17711. (put 'org-delete-char 'delete-selection 'supersede)
  17712. (put 'org-delete-backward-char 'delete-selection 'supersede)
  17713. (put 'org-yank 'delete-selection 'yank)
  17714. ;; Make `flyspell-mode' delay after some commands
  17715. (put 'org-self-insert-command 'flyspell-delayed t)
  17716. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  17717. (put 'org-delete-char 'flyspell-delayed t)
  17718. (put 'org-delete-backward-char 'flyspell-delayed t)
  17719. ;; Make pabbrev-mode expand after Org mode commands
  17720. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  17721. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  17722. (defun org-transpose-words ()
  17723. "Transpose words for Org.
  17724. This uses the `org-mode-transpose-word-syntax-table' syntax
  17725. table, which interprets characters in `org-emphasis-alist' as
  17726. word constituents."
  17727. (interactive)
  17728. (with-syntax-table org-mode-transpose-word-syntax-table
  17729. (call-interactively 'transpose-words)))
  17730. (defvar org-ctrl-c-ctrl-c-hook nil
  17731. "Hook for functions attaching themselves to `C-c C-c'.
  17732. This can be used to add additional functionality to the C-c C-c
  17733. key which executes context-dependent commands. This hook is run
  17734. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  17735. run after the last test.
  17736. Each function will be called with no arguments. The function
  17737. must check if the context is appropriate for it to act. If yes,
  17738. it should do its thing and then return a non-nil value. If the
  17739. context is wrong, just do nothing and return nil.")
  17740. (defvar org-ctrl-c-ctrl-c-final-hook nil
  17741. "Hook for functions attaching themselves to `C-c C-c'.
  17742. This can be used to add additional functionality to the C-c C-c
  17743. key which executes context-dependent commands. This hook is run
  17744. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  17745. before the first test.
  17746. Each function will be called with no arguments. The function
  17747. must check if the context is appropriate for it to act. If yes,
  17748. it should do its thing and then return a non-nil value. If the
  17749. context is wrong, just do nothing and return nil.")
  17750. (defvar org-tab-first-hook nil
  17751. "Hook for functions to attach themselves to TAB.
  17752. See `org-ctrl-c-ctrl-c-hook' for more information.
  17753. This hook runs as the first action when TAB is pressed, even before
  17754. `org-cycle' messes around with the `outline-regexp' to cater for
  17755. inline tasks and plain list item folding.
  17756. If any function in this hook returns t, any other actions that
  17757. would have been caused by TAB (such as table field motion or visibility
  17758. cycling) will not occur.")
  17759. (defvar org-tab-after-check-for-table-hook nil
  17760. "Hook for functions to attach themselves to TAB.
  17761. See `org-ctrl-c-ctrl-c-hook' for more information.
  17762. This hook runs after it has been established that the cursor is not in a
  17763. table, but before checking if the cursor is in a headline or if global cycling
  17764. should be done.
  17765. If any function in this hook returns t, not other actions like visibility
  17766. cycling will be done.")
  17767. (defvar org-tab-after-check-for-cycling-hook nil
  17768. "Hook for functions to attach themselves to TAB.
  17769. See `org-ctrl-c-ctrl-c-hook' for more information.
  17770. This hook runs after it has been established that not table field motion and
  17771. not visibility should be done because of current context. This is probably
  17772. the place where a package like yasnippets can hook in.")
  17773. (defvar org-tab-before-tab-emulation-hook nil
  17774. "Hook for functions to attach themselves to TAB.
  17775. See `org-ctrl-c-ctrl-c-hook' for more information.
  17776. This hook runs after every other options for TAB have been exhausted, but
  17777. before indentation and \t insertion takes place.")
  17778. (defvar org-metaleft-hook nil
  17779. "Hook for functions attaching themselves to `M-left'.
  17780. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17781. (defvar org-metaright-hook nil
  17782. "Hook for functions attaching themselves to `M-right'.
  17783. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17784. (defvar org-metaup-hook nil
  17785. "Hook for functions attaching themselves to `M-up'.
  17786. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17787. (defvar org-metadown-hook nil
  17788. "Hook for functions attaching themselves to `M-down'.
  17789. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17790. (defvar org-shiftmetaleft-hook nil
  17791. "Hook for functions attaching themselves to `M-S-left'.
  17792. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17793. (defvar org-shiftmetaright-hook nil
  17794. "Hook for functions attaching themselves to `M-S-right'.
  17795. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17796. (defvar org-shiftmetaup-hook nil
  17797. "Hook for functions attaching themselves to `M-S-up'.
  17798. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17799. (defvar org-shiftmetadown-hook nil
  17800. "Hook for functions attaching themselves to `M-S-down'.
  17801. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17802. (defvar org-metareturn-hook nil
  17803. "Hook for functions attaching themselves to `M-RET'.
  17804. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17805. (defvar org-shiftup-hook nil
  17806. "Hook for functions attaching themselves to `S-up'.
  17807. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17808. (defvar org-shiftup-final-hook nil
  17809. "Hook for functions attaching themselves to `S-up'.
  17810. This one runs after all other options except shift-select have been excluded.
  17811. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17812. (defvar org-shiftdown-hook nil
  17813. "Hook for functions attaching themselves to `S-down'.
  17814. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17815. (defvar org-shiftdown-final-hook nil
  17816. "Hook for functions attaching themselves to `S-down'.
  17817. This one runs after all other options except shift-select have been excluded.
  17818. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17819. (defvar org-shiftleft-hook nil
  17820. "Hook for functions attaching themselves to `S-left'.
  17821. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17822. (defvar org-shiftleft-final-hook nil
  17823. "Hook for functions attaching themselves to `S-left'.
  17824. This one runs after all other options except shift-select have been excluded.
  17825. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17826. (defvar org-shiftright-hook nil
  17827. "Hook for functions attaching themselves to `S-right'.
  17828. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17829. (defvar org-shiftright-final-hook nil
  17830. "Hook for functions attaching themselves to `S-right'.
  17831. This one runs after all other options except shift-select have been excluded.
  17832. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17833. (defun org-modifier-cursor-error ()
  17834. "Throw an error, a modified cursor command was applied in wrong context."
  17835. (user-error "This command is active in special context like tables, headlines or items"))
  17836. (defun org-shiftselect-error ()
  17837. "Throw an error because Shift-Cursor command was applied in wrong context."
  17838. (if (and (boundp 'shift-select-mode) shift-select-mode)
  17839. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  17840. (user-error "This command works only in special context like headlines or timestamps")))
  17841. (defun org-call-for-shift-select (cmd)
  17842. (let ((this-command-keys-shift-translated t))
  17843. (call-interactively cmd)))
  17844. (defun org-shifttab (&optional arg)
  17845. "Global visibility cycling or move to previous table field.
  17846. Call `org-table-previous-field' within a table.
  17847. When ARG is nil, cycle globally through visibility states.
  17848. When ARG is a numeric prefix, show contents of this level."
  17849. (interactive "P")
  17850. (cond
  17851. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  17852. ((integerp arg)
  17853. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  17854. (message "Content view to level: %d" arg)
  17855. (org-content (prefix-numeric-value arg2))
  17856. (org-cycle-show-empty-lines t)
  17857. (setq org-cycle-global-status 'overview)))
  17858. (t (call-interactively 'org-global-cycle))))
  17859. (defun org-shiftmetaleft ()
  17860. "Promote subtree or delete table column.
  17861. Calls `org-promote-subtree', `org-outdent-item-tree', or
  17862. `org-table-delete-column', depending on context. See the
  17863. individual commands for more information."
  17864. (interactive)
  17865. (cond
  17866. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  17867. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  17868. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  17869. ((if (not (org-region-active-p)) (org-at-item-p)
  17870. (save-excursion (goto-char (region-beginning))
  17871. (org-at-item-p)))
  17872. (call-interactively 'org-outdent-item-tree))
  17873. (t (org-modifier-cursor-error))))
  17874. (defun org-shiftmetaright ()
  17875. "Demote subtree or insert table column.
  17876. Calls `org-demote-subtree', `org-indent-item-tree', or
  17877. `org-table-insert-column', depending on context. See the
  17878. individual commands for more information."
  17879. (interactive)
  17880. (cond
  17881. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  17882. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  17883. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  17884. ((if (not (org-region-active-p)) (org-at-item-p)
  17885. (save-excursion (goto-char (region-beginning))
  17886. (org-at-item-p)))
  17887. (call-interactively 'org-indent-item-tree))
  17888. (t (org-modifier-cursor-error))))
  17889. (defun org-shiftmetaup (&optional _arg)
  17890. "Drag the line at point up.
  17891. In a table, kill the current row.
  17892. On a clock timestamp, update the value of the timestamp like `S-<up>'
  17893. but also adjust the previous clocked item in the clock history.
  17894. Everywhere else, drag the line at point up."
  17895. (interactive "P")
  17896. (cond
  17897. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  17898. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  17899. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17900. (call-interactively 'org-timestamp-up)))
  17901. (t (call-interactively 'org-drag-line-backward))))
  17902. (defun org-shiftmetadown (&optional _arg)
  17903. "Drag the line at point down.
  17904. In a table, insert an empty row at the current line.
  17905. On a clock timestamp, update the value of the timestamp like `S-<down>'
  17906. but also adjust the previous clocked item in the clock history.
  17907. Everywhere else, drag the line at point down."
  17908. (interactive "P")
  17909. (cond
  17910. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  17911. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  17912. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17913. (call-interactively 'org-timestamp-down)))
  17914. (t (call-interactively 'org-drag-line-forward))))
  17915. (defsubst org-hidden-tree-error ()
  17916. (user-error
  17917. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  17918. (defun org-metaleft (&optional _arg)
  17919. "Promote heading, list item at point or move table column left.
  17920. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  17921. depending on context. With no specific context, calls the Emacs
  17922. default `backward-word'. See the individual commands for more
  17923. information.
  17924. This function runs the hook `org-metaleft-hook' as a first step,
  17925. and returns at first non-nil value."
  17926. (interactive "P")
  17927. (cond
  17928. ((run-hook-with-args-until-success 'org-metaleft-hook))
  17929. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  17930. ((org-with-limited-levels
  17931. (or (org-at-heading-p)
  17932. (and (org-region-active-p)
  17933. (save-excursion
  17934. (goto-char (region-beginning))
  17935. (org-at-heading-p)))))
  17936. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  17937. (call-interactively 'org-do-promote))
  17938. ;; At an inline task.
  17939. ((org-at-heading-p)
  17940. (call-interactively 'org-inlinetask-promote))
  17941. ((or (org-at-item-p)
  17942. (and (org-region-active-p)
  17943. (save-excursion
  17944. (goto-char (region-beginning))
  17945. (org-at-item-p))))
  17946. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  17947. (call-interactively 'org-outdent-item))
  17948. (t (call-interactively 'backward-word))))
  17949. (defun org-metaright (&optional _arg)
  17950. "Demote heading, list item at point or move table column right.
  17951. In front of a drawer or a block keyword, indent it correctly.
  17952. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  17953. `org-indent-drawer' or `org-indent-block' depending on context.
  17954. With no specific context, calls the Emacs default `forward-word'.
  17955. See the individual commands for more information.
  17956. This function runs the hook `org-metaright-hook' as a first step,
  17957. and returns at first non-nil value."
  17958. (interactive "P")
  17959. (cond
  17960. ((run-hook-with-args-until-success 'org-metaright-hook))
  17961. ((org-at-table-p) (call-interactively 'org-table-move-column))
  17962. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  17963. ((org-at-block-p) (call-interactively 'org-indent-block))
  17964. ((org-with-limited-levels
  17965. (or (org-at-heading-p)
  17966. (and (org-region-active-p)
  17967. (save-excursion
  17968. (goto-char (region-beginning))
  17969. (org-at-heading-p)))))
  17970. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  17971. (call-interactively 'org-do-demote))
  17972. ;; At an inline task.
  17973. ((org-at-heading-p)
  17974. (call-interactively 'org-inlinetask-demote))
  17975. ((or (org-at-item-p)
  17976. (and (org-region-active-p)
  17977. (save-excursion
  17978. (goto-char (region-beginning))
  17979. (org-at-item-p))))
  17980. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  17981. (call-interactively 'org-indent-item))
  17982. (t (call-interactively 'forward-word))))
  17983. (defun org-check-for-hidden (what)
  17984. "Check if there are hidden headlines/items in the current visual line.
  17985. WHAT can be either `headlines' or `items'. If the current line is
  17986. an outline or item heading and it has a folded subtree below it,
  17987. this function returns t, nil otherwise."
  17988. (let ((re (cond
  17989. ((eq what 'headlines) org-outline-regexp-bol)
  17990. ((eq what 'items) (org-item-beginning-re))
  17991. (t (error "This should not happen"))))
  17992. beg end)
  17993. (save-excursion
  17994. (catch 'exit
  17995. (unless (org-region-active-p)
  17996. (setq beg (point-at-bol))
  17997. (beginning-of-line 2)
  17998. (while (and (not (eobp)) ;; this is like `next-line'
  17999. (get-char-property (1- (point)) 'invisible))
  18000. (beginning-of-line 2))
  18001. (setq end (point))
  18002. (goto-char beg)
  18003. (goto-char (point-at-eol))
  18004. (setq end (max end (point)))
  18005. (while (re-search-forward re end t)
  18006. (when (get-char-property (match-beginning 0) 'invisible)
  18007. (throw 'exit t))))
  18008. nil))))
  18009. (defun org-metaup (&optional _arg)
  18010. "Move subtree up or move table row up.
  18011. Calls `org-move-subtree-up' or `org-table-move-row' or
  18012. `org-move-item-up', depending on context. See the individual commands
  18013. for more information."
  18014. (interactive "P")
  18015. (cond
  18016. ((run-hook-with-args-until-success 'org-metaup-hook))
  18017. ((org-region-active-p)
  18018. (let* ((a (min (region-beginning) (region-end)))
  18019. (b (1- (max (region-beginning) (region-end))))
  18020. (c (save-excursion (goto-char a)
  18021. (move-beginning-of-line 0)))
  18022. (d (save-excursion (goto-char a)
  18023. (move-end-of-line 0) (point))))
  18024. (transpose-regions a b c d)
  18025. (goto-char c)))
  18026. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18027. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18028. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18029. (t (org-drag-element-backward))))
  18030. (defun org-metadown (&optional _arg)
  18031. "Move subtree down or move table row down.
  18032. Calls `org-move-subtree-down' or `org-table-move-row' or
  18033. `org-move-item-down', depending on context. See the individual
  18034. commands for more information."
  18035. (interactive "P")
  18036. (cond
  18037. ((run-hook-with-args-until-success 'org-metadown-hook))
  18038. ((org-region-active-p)
  18039. (let* ((a (min (region-beginning) (region-end)))
  18040. (b (max (region-beginning) (region-end)))
  18041. (c (save-excursion (goto-char b)
  18042. (move-beginning-of-line 1)))
  18043. (d (save-excursion (goto-char b)
  18044. (move-end-of-line 1) (1+ (point)))))
  18045. (transpose-regions a b c d)
  18046. (goto-char d)))
  18047. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18048. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18049. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18050. (t (org-drag-element-forward))))
  18051. (defun org-shiftup (&optional arg)
  18052. "Increase item in timestamp or increase priority of current headline.
  18053. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18054. depending on context. See the individual commands for more information."
  18055. (interactive "P")
  18056. (cond
  18057. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18058. ((and org-support-shift-select (org-region-active-p))
  18059. (org-call-for-shift-select 'previous-line))
  18060. ((org-at-timestamp-p 'lax)
  18061. (call-interactively (if org-edit-timestamp-down-means-later
  18062. 'org-timestamp-down 'org-timestamp-up)))
  18063. ((and (not (eq org-support-shift-select 'always))
  18064. org-enable-priority-commands
  18065. (org-at-heading-p))
  18066. (call-interactively 'org-priority-up))
  18067. ((and (not org-support-shift-select) (org-at-item-p))
  18068. (call-interactively 'org-previous-item))
  18069. ((org-clocktable-try-shift 'up arg))
  18070. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18071. (org-support-shift-select
  18072. (org-call-for-shift-select 'previous-line))
  18073. (t (org-shiftselect-error))))
  18074. (defun org-shiftdown (&optional arg)
  18075. "Decrease item in timestamp or decrease priority of current headline.
  18076. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18077. depending on context. See the individual commands for more information."
  18078. (interactive "P")
  18079. (cond
  18080. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18081. ((and org-support-shift-select (org-region-active-p))
  18082. (org-call-for-shift-select 'next-line))
  18083. ((org-at-timestamp-p 'lax)
  18084. (call-interactively (if org-edit-timestamp-down-means-later
  18085. 'org-timestamp-up 'org-timestamp-down)))
  18086. ((and (not (eq org-support-shift-select 'always))
  18087. org-enable-priority-commands
  18088. (org-at-heading-p))
  18089. (call-interactively 'org-priority-down))
  18090. ((and (not org-support-shift-select) (org-at-item-p))
  18091. (call-interactively 'org-next-item))
  18092. ((org-clocktable-try-shift 'down arg))
  18093. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18094. (org-support-shift-select
  18095. (org-call-for-shift-select 'next-line))
  18096. (t (org-shiftselect-error))))
  18097. (defun org-shiftright (&optional arg)
  18098. "Cycle the thing at point or in the current line, depending on context.
  18099. Depending on context, this does one of the following:
  18100. - switch a timestamp at point one day into the future
  18101. - on a headline, switch to the next TODO keyword.
  18102. - on an item, switch entire list to the next bullet type
  18103. - on a property line, switch to the next allowed value
  18104. - on a clocktable definition line, move time block into the future"
  18105. (interactive "P")
  18106. (cond
  18107. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18108. ((and org-support-shift-select (org-region-active-p))
  18109. (org-call-for-shift-select 'forward-char))
  18110. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  18111. ((and (not (eq org-support-shift-select 'always))
  18112. (org-at-heading-p))
  18113. (let ((org-inhibit-logging
  18114. (not org-treat-S-cursor-todo-selection-as-state-change))
  18115. (org-inhibit-blocking
  18116. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18117. (org-call-with-arg 'org-todo 'right)))
  18118. ((or (and org-support-shift-select
  18119. (not (eq org-support-shift-select 'always))
  18120. (org-at-item-bullet-p))
  18121. (and (not org-support-shift-select) (org-at-item-p)))
  18122. (org-call-with-arg 'org-cycle-list-bullet nil))
  18123. ((and (not (eq org-support-shift-select 'always))
  18124. (org-at-property-p))
  18125. (call-interactively 'org-property-next-allowed-value))
  18126. ((org-clocktable-try-shift 'right arg))
  18127. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18128. (org-support-shift-select
  18129. (org-call-for-shift-select 'forward-char))
  18130. (t (org-shiftselect-error))))
  18131. (defun org-shiftleft (&optional arg)
  18132. "Cycle the thing at point or in the current line, depending on context.
  18133. Depending on context, this does one of the following:
  18134. - switch a timestamp at point one day into the past
  18135. - on a headline, switch to the previous TODO keyword.
  18136. - on an item, switch entire list to the previous bullet type
  18137. - on a property line, switch to the previous allowed value
  18138. - on a clocktable definition line, move time block into the past"
  18139. (interactive "P")
  18140. (cond
  18141. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18142. ((and org-support-shift-select (org-region-active-p))
  18143. (org-call-for-shift-select 'backward-char))
  18144. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  18145. ((and (not (eq org-support-shift-select 'always))
  18146. (org-at-heading-p))
  18147. (let ((org-inhibit-logging
  18148. (not org-treat-S-cursor-todo-selection-as-state-change))
  18149. (org-inhibit-blocking
  18150. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18151. (org-call-with-arg 'org-todo 'left)))
  18152. ((or (and org-support-shift-select
  18153. (not (eq org-support-shift-select 'always))
  18154. (org-at-item-bullet-p))
  18155. (and (not org-support-shift-select) (org-at-item-p)))
  18156. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  18157. ((and (not (eq org-support-shift-select 'always))
  18158. (org-at-property-p))
  18159. (call-interactively 'org-property-previous-allowed-value))
  18160. ((org-clocktable-try-shift 'left arg))
  18161. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  18162. (org-support-shift-select
  18163. (org-call-for-shift-select 'backward-char))
  18164. (t (org-shiftselect-error))))
  18165. (defun org-shiftcontrolright ()
  18166. "Switch to next TODO set."
  18167. (interactive)
  18168. (cond
  18169. ((and org-support-shift-select (org-region-active-p))
  18170. (org-call-for-shift-select 'forward-word))
  18171. ((and (not (eq org-support-shift-select 'always))
  18172. (org-at-heading-p))
  18173. (org-call-with-arg 'org-todo 'nextset))
  18174. (org-support-shift-select
  18175. (org-call-for-shift-select 'forward-word))
  18176. (t (org-shiftselect-error))))
  18177. (defun org-shiftcontrolleft ()
  18178. "Switch to previous TODO set."
  18179. (interactive)
  18180. (cond
  18181. ((and org-support-shift-select (org-region-active-p))
  18182. (org-call-for-shift-select 'backward-word))
  18183. ((and (not (eq org-support-shift-select 'always))
  18184. (org-at-heading-p))
  18185. (org-call-with-arg 'org-todo 'previousset))
  18186. (org-support-shift-select
  18187. (org-call-for-shift-select 'backward-word))
  18188. (t (org-shiftselect-error))))
  18189. (defun org-shiftcontrolup (&optional n)
  18190. "Change timestamps synchronously up in CLOCK log lines.
  18191. Optional argument N tells to change by that many units."
  18192. (interactive "P")
  18193. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18194. (let (org-support-shift-select)
  18195. (org-clock-timestamps-up n))
  18196. (user-error "Not at a clock log")))
  18197. (defun org-shiftcontroldown (&optional n)
  18198. "Change timestamps synchronously down in CLOCK log lines.
  18199. Optional argument N tells to change by that many units."
  18200. (interactive "P")
  18201. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18202. (let (org-support-shift-select)
  18203. (org-clock-timestamps-down n))
  18204. (user-error "Not at a clock log")))
  18205. (defun org-increase-number-at-point (&optional inc)
  18206. "Increment the number at point.
  18207. With an optional prefix numeric argument INC, increment using
  18208. this numeric value."
  18209. (interactive "p")
  18210. (if (not (number-at-point))
  18211. (user-error "Not on a number")
  18212. (unless inc (setq inc 1))
  18213. (let ((pos (point))
  18214. (beg (skip-chars-backward "-+^/*0-9eE."))
  18215. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  18216. (setq nap (buffer-substring-no-properties
  18217. (+ pos beg) (+ pos beg end)))
  18218. (delete-region (+ pos beg) (+ pos beg end))
  18219. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18220. (when (org-at-table-p)
  18221. (org-table-align)
  18222. (org-table-end-of-field 1))))
  18223. (defun org-decrease-number-at-point (&optional inc)
  18224. "Decrement the number at point.
  18225. With an optional prefix numeric argument INC, decrement using
  18226. this numeric value."
  18227. (interactive "p")
  18228. (org-increase-number-at-point (- (or inc 1))))
  18229. (defun org-ctrl-c-ret ()
  18230. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  18231. (interactive)
  18232. (cond
  18233. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18234. (t (call-interactively 'org-insert-heading))))
  18235. (defun org-find-visible ()
  18236. (let ((s (point)))
  18237. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18238. (get-char-property s 'invisible)))
  18239. s))
  18240. (defun org-find-invisible ()
  18241. (let ((s (point)))
  18242. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18243. (not (get-char-property s 'invisible))))
  18244. s))
  18245. (defun org-copy-visible (beg end)
  18246. "Copy the visible parts of the region."
  18247. (interactive "r")
  18248. (let ((result ""))
  18249. (while (/= beg end)
  18250. (when (get-char-property beg 'invisible)
  18251. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  18252. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  18253. (setq result (concat result (buffer-substring beg next)))
  18254. (setq beg next)))
  18255. (kill-new result)))
  18256. (defun org-copy-special ()
  18257. "Copy region in table or copy current subtree.
  18258. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18259. context. See the individual commands for more information."
  18260. (interactive)
  18261. (call-interactively
  18262. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18263. (defun org-cut-special ()
  18264. "Cut region in table or cut current subtree.
  18265. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  18266. context. See the individual commands for more information."
  18267. (interactive)
  18268. (call-interactively
  18269. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  18270. (defun org-paste-special (arg)
  18271. "Paste rectangular region into table, or past subtree relative to level.
  18272. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18273. See the individual commands for more information."
  18274. (interactive "P")
  18275. (if (org-at-table-p)
  18276. (org-table-paste-rectangle)
  18277. (org-paste-subtree arg)))
  18278. (defun org-edit-special (&optional arg)
  18279. "Call a special editor for the element at point.
  18280. When at a table, call the formula editor with `org-table-edit-formulas'.
  18281. When in a source code block, call `org-edit-src-code'.
  18282. When in a fixed-width region, call `org-edit-fixed-width-region'.
  18283. When in an export block, call `org-edit-export-block'.
  18284. When in a LaTeX environment, call `org-edit-latex-environment'.
  18285. When at an #+INCLUDE keyword, visit the included file.
  18286. When at a footnote reference, call `org-edit-footnote-reference'
  18287. On a link, call `ffap' to visit the link at point.
  18288. Otherwise, return a user error."
  18289. (interactive "P")
  18290. (let ((element (org-element-at-point)))
  18291. (barf-if-buffer-read-only)
  18292. (pcase (org-element-type element)
  18293. (`src-block
  18294. (if (not arg) (org-edit-src-code)
  18295. (let* ((info (org-babel-get-src-block-info))
  18296. (lang (nth 0 info))
  18297. (params (nth 2 info))
  18298. (session (cdr (assq :session params))))
  18299. (if (not session) (org-edit-src-code)
  18300. ;; At a src-block with a session and function called with
  18301. ;; an ARG: switch to the buffer related to the inferior
  18302. ;; process.
  18303. (switch-to-buffer
  18304. (funcall (intern (concat "org-babel-prep-session:" lang))
  18305. session params))))))
  18306. (`keyword
  18307. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  18308. (org-open-link-from-string
  18309. (format "[[%s]]"
  18310. (expand-file-name
  18311. (let ((value (org-element-property :value element)))
  18312. (cond ((org-file-url-p value)
  18313. (user-error "The file is specified as a URL, cannot be edited"))
  18314. ((not (org-string-nw-p value))
  18315. (user-error "No file to edit"))
  18316. ((string-match "\\`\"\\(.*?\\)\"" value)
  18317. (match-string 1 value))
  18318. ((string-match "\\`[^ \t\"]\\S-*" value)
  18319. (match-string 0 value))
  18320. (t (user-error "No valid file specified")))))))
  18321. (user-error "No special environment to edit here")))
  18322. (`table
  18323. (if (eq (org-element-property :type element) 'table.el)
  18324. (org-edit-table.el)
  18325. (call-interactively 'org-table-edit-formulas)))
  18326. ;; Only Org tables contain `table-row' type elements.
  18327. (`table-row (call-interactively 'org-table-edit-formulas))
  18328. (`example-block (org-edit-src-code))
  18329. (`export-block (org-edit-export-block))
  18330. (`fixed-width (org-edit-fixed-width-region))
  18331. (`latex-environment (org-edit-latex-environment))
  18332. (_
  18333. ;; No notable element at point. Though, we may be at a link or
  18334. ;; a footnote reference, which are objects. Thus, scan deeper.
  18335. (let ((context (org-element-context element)))
  18336. (pcase (org-element-type context)
  18337. (`footnote-reference (org-edit-footnote-reference))
  18338. (`inline-src-block (org-edit-inline-src-code))
  18339. (`link (call-interactively #'ffap))
  18340. (_ (user-error "No special environment to edit here"))))))))
  18341. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  18342. (defun org-ctrl-c-ctrl-c (&optional arg)
  18343. "Set tags in headline, or update according to changed information at point.
  18344. This command does many different things, depending on context:
  18345. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  18346. this is what we do.
  18347. - If the cursor is on a statistics cookie, update it.
  18348. - If the cursor is in a headline, prompt for tags and insert them
  18349. into the current line, aligned to `org-tags-column'. When called
  18350. with prefix arg, realign all tags in the current buffer.
  18351. - If the cursor is in one of the special #+KEYWORD lines, this
  18352. triggers scanning the buffer for these lines and updating the
  18353. information.
  18354. - If the cursor is inside a table, realign the table. This command
  18355. works even if the automatic table editor has been turned off.
  18356. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  18357. the entire table.
  18358. - If the cursor is at a footnote reference or definition, jump to
  18359. the corresponding definition or references, respectively.
  18360. - If the cursor is a the beginning of a dynamic block, update it.
  18361. - If the current buffer is a capture buffer, close note and file it.
  18362. - If the cursor is on a <<<target>>>, update radio targets and
  18363. corresponding links in this buffer.
  18364. - If the cursor is on a numbered item in a plain list, renumber the
  18365. ordered list.
  18366. - If the cursor is on a checkbox, toggle it.
  18367. - If the cursor is on a code block, evaluate it. The variable
  18368. `org-confirm-babel-evaluate' can be used to control prompting
  18369. before code block evaluation, by default every code block
  18370. evaluation requires confirmation. Code block evaluation can be
  18371. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  18372. (interactive "P")
  18373. (cond
  18374. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  18375. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  18376. (org-remove-occur-highlights)
  18377. (message "Temporary highlights/overlays removed from current buffer"))
  18378. ((and (local-variable-p 'org-finish-function)
  18379. (fboundp org-finish-function))
  18380. (funcall org-finish-function))
  18381. ((org-babel-hash-at-point))
  18382. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  18383. (t
  18384. (let* ((context
  18385. (org-element-lineage
  18386. (org-element-context)
  18387. ;; Limit to supported contexts.
  18388. '(babel-call clock dynamic-block footnote-definition
  18389. footnote-reference inline-babel-call inline-src-block
  18390. inlinetask item keyword node-property paragraph
  18391. plain-list planning property-drawer radio-target
  18392. src-block statistics-cookie table table-cell table-row
  18393. timestamp)
  18394. t))
  18395. (type (org-element-type context)))
  18396. ;; For convenience: at the first line of a paragraph on the same
  18397. ;; line as an item, apply function on that item instead.
  18398. (when (eq type 'paragraph)
  18399. (let ((parent (org-element-property :parent context)))
  18400. (when (and (eq (org-element-type parent) 'item)
  18401. (= (line-beginning-position)
  18402. (org-element-property :begin parent)))
  18403. (setq context parent)
  18404. (setq type 'item))))
  18405. ;; Act according to type of element or object at point.
  18406. ;;
  18407. ;; Do nothing on a blank line, except if it is contained in
  18408. ;; a src block. Hence, we first check if point is in such
  18409. ;; a block and then if it is at a blank line.
  18410. (pcase type
  18411. ((or `inline-src-block `src-block)
  18412. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  18413. (org-babel-eval-wipe-error-buffer)
  18414. (org-babel-execute-src-block
  18415. current-prefix-arg (org-babel-get-src-block-info nil context))))
  18416. ((guard (org-match-line "[ \t]*$"))
  18417. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  18418. (user-error
  18419. (substitute-command-keys
  18420. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  18421. ((or `babel-call `inline-babel-call)
  18422. (let ((info (org-babel-lob-get-info context)))
  18423. (when info (org-babel-execute-src-block nil info))))
  18424. (`clock (org-clock-update-time-maybe))
  18425. (`dynamic-block
  18426. (save-excursion
  18427. (goto-char (org-element-property :post-affiliated context))
  18428. (org-update-dblock)))
  18429. (`footnote-definition
  18430. (goto-char (org-element-property :post-affiliated context))
  18431. (call-interactively 'org-footnote-action))
  18432. (`footnote-reference (call-interactively #'org-footnote-action))
  18433. ((or `headline `inlinetask)
  18434. (save-excursion (goto-char (org-element-property :begin context))
  18435. (call-interactively #'org-set-tags-command)))
  18436. (`item
  18437. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  18438. ;; unconditionally, whereas `C-u' will toggle its presence.
  18439. ;; Without a universal argument, if the item has a checkbox,
  18440. ;; toggle it. Otherwise repair the list.
  18441. (let* ((box (org-element-property :checkbox context))
  18442. (struct (org-element-property :structure context))
  18443. (old-struct (copy-tree struct))
  18444. (parents (org-list-parents-alist struct))
  18445. (prevs (org-list-prevs-alist struct))
  18446. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  18447. (org-list-set-checkbox
  18448. (org-element-property :begin context) struct
  18449. (cond ((equal arg '(16)) "[-]")
  18450. ((and (not box) (equal arg '(4))) "[ ]")
  18451. ((or (not box) (equal arg '(4))) nil)
  18452. ((eq box 'on) "[ ]")
  18453. (t "[X]")))
  18454. ;; Mimic `org-list-write-struct' but with grabbing a return
  18455. ;; value from `org-list-struct-fix-box'.
  18456. (org-list-struct-fix-ind struct parents 2)
  18457. (org-list-struct-fix-item-end struct)
  18458. (org-list-struct-fix-bul struct prevs)
  18459. (org-list-struct-fix-ind struct parents)
  18460. (let ((block-item
  18461. (org-list-struct-fix-box struct parents prevs orderedp)))
  18462. (if (and box (equal struct old-struct))
  18463. (if (equal arg '(16))
  18464. (message "Checkboxes already reset")
  18465. (user-error "Cannot toggle this checkbox: %s"
  18466. (if (eq box 'on)
  18467. "all subitems checked"
  18468. "unchecked subitems")))
  18469. (org-list-struct-apply-struct struct old-struct)
  18470. (org-update-checkbox-count-maybe))
  18471. (when block-item
  18472. (message "Checkboxes were removed due to empty box at line %d"
  18473. (org-current-line block-item))))))
  18474. (`keyword
  18475. (let ((org-inhibit-startup-visibility-stuff t)
  18476. (org-startup-align-all-tables nil))
  18477. (when (boundp 'org-table-coordinate-overlays)
  18478. (mapc #'delete-overlay org-table-coordinate-overlays)
  18479. (setq org-table-coordinate-overlays nil))
  18480. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  18481. (message "Local setup has been refreshed"))
  18482. (`plain-list
  18483. ;; At a plain list, with a double C-u argument, set
  18484. ;; checkboxes of each item to "[-]", whereas a single one
  18485. ;; will toggle their presence according to the state of the
  18486. ;; first item in the list. Without an argument, repair the
  18487. ;; list.
  18488. (let* ((begin (org-element-property :contents-begin context))
  18489. (struct (org-element-property :structure context))
  18490. (old-struct (copy-tree struct))
  18491. (first-box (save-excursion
  18492. (goto-char begin)
  18493. (looking-at org-list-full-item-re)
  18494. (match-string-no-properties 3)))
  18495. (new-box (cond ((equal arg '(16)) "[-]")
  18496. ((equal arg '(4)) (unless first-box "[ ]"))
  18497. ((equal first-box "[X]") "[ ]")
  18498. (t "[X]"))))
  18499. (cond
  18500. (arg
  18501. (dolist (pos
  18502. (org-list-get-all-items
  18503. begin struct (org-list-prevs-alist struct)))
  18504. (org-list-set-checkbox pos struct new-box)))
  18505. ((and first-box (eq (point) begin))
  18506. ;; For convenience, when point is at bol on the first
  18507. ;; item of the list and no argument is provided, simply
  18508. ;; toggle checkbox of that item, if any.
  18509. (org-list-set-checkbox begin struct new-box)))
  18510. (org-list-write-struct
  18511. struct (org-list-parents-alist struct) old-struct)
  18512. (org-update-checkbox-count-maybe)))
  18513. ((or `property-drawer `node-property)
  18514. (call-interactively #'org-property-action))
  18515. (`radio-target
  18516. (call-interactively #'org-update-radio-target-regexp))
  18517. (`statistics-cookie
  18518. (call-interactively #'org-update-statistics-cookies))
  18519. ((or `table `table-cell `table-row)
  18520. ;; At a table, recalculate every field and align it. Also
  18521. ;; send the table if necessary. If the table has
  18522. ;; a `table.el' type, just give up. At a table row or cell,
  18523. ;; maybe recalculate line but always align table.
  18524. (if (eq (org-element-property :type context) 'table.el)
  18525. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  18526. Use `\\[org-edit-special]' to edit table.el tables"))
  18527. (if (or (eq type 'table)
  18528. ;; Check if point is at a TBLFM line.
  18529. (and (eq type 'table-row)
  18530. (= (point) (org-element-property :end context))))
  18531. (save-excursion
  18532. (if (org-at-TBLFM-p)
  18533. (progn (require 'org-table)
  18534. (org-table-calc-current-TBLFM))
  18535. (goto-char (org-element-property :contents-begin context))
  18536. (org-call-with-arg 'org-table-recalculate (or arg t))
  18537. (orgtbl-send-table 'maybe)))
  18538. (org-table-maybe-eval-formula)
  18539. (cond (arg (call-interactively #'org-table-recalculate))
  18540. ((org-table-maybe-recalculate-line))
  18541. (t (org-table-align))))))
  18542. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  18543. (org-timestamp-change 0 'day))
  18544. ((and `nil (guard (org-at-heading-p)))
  18545. ;; When point is on an unsupported object type, we can miss
  18546. ;; the fact that it also is at a heading. Handle it here.
  18547. (call-interactively #'org-set-tags-command))
  18548. ((guard
  18549. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  18550. (_
  18551. (user-error
  18552. (substitute-command-keys
  18553. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  18554. (defun org-mode-restart ()
  18555. (interactive)
  18556. (let ((indent-status (bound-and-true-p org-indent-mode)))
  18557. (funcall major-mode)
  18558. (hack-local-variables)
  18559. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  18560. (org-indent-mode -1))
  18561. (org-reset-file-cache))
  18562. (message "%s restarted" major-mode))
  18563. (defun org-kill-note-or-show-branches ()
  18564. "Abort storing current note, or call `outline-show-branches'."
  18565. (interactive)
  18566. (if (not org-finish-function)
  18567. (save-excursion
  18568. (save-restriction
  18569. (org-narrow-to-subtree)
  18570. (org-flag-subtree t)
  18571. (call-interactively 'outline-show-branches)
  18572. (org-hide-archived-subtrees (point-min) (point-max))))
  18573. (let ((org-note-abort t))
  18574. (funcall org-finish-function))))
  18575. (defun org-delete-indentation (&optional arg)
  18576. "Join current line to previous and fix whitespace at join.
  18577. If previous line is a headline add to headline title. Otherwise
  18578. the function calls `delete-indentation'.
  18579. With a non-nil optional argument, join it to the following one."
  18580. (interactive "*P")
  18581. (if (save-excursion
  18582. (beginning-of-line (if arg 1 0))
  18583. (let ((case-fold-search nil))
  18584. (looking-at org-complex-heading-regexp)))
  18585. ;; At headline.
  18586. (let ((tags-column (when (match-beginning 5)
  18587. (save-excursion (goto-char (match-beginning 5))
  18588. (current-column))))
  18589. (string (concat " " (progn (when arg (forward-line 1))
  18590. (org-trim (delete-and-extract-region
  18591. (line-beginning-position)
  18592. (line-end-position)))))))
  18593. (unless (bobp) (delete-region (point) (1- (point))))
  18594. (goto-char (or (match-end 4)
  18595. (match-beginning 5)
  18596. (match-end 0)))
  18597. (skip-chars-backward " \t")
  18598. (save-excursion (insert string))
  18599. ;; Adjust alignment of tags.
  18600. (cond
  18601. ((not tags-column)) ;no tags
  18602. (org-auto-align-tags (org-align-tags))
  18603. (t (org--align-tags-here tags-column)))) ;preserve tags column
  18604. (delete-indentation arg)))
  18605. (defun org-open-line (n)
  18606. "Insert a new row in tables, call `open-line' elsewhere.
  18607. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  18608. As a special case, when a document starts with a table, allow to
  18609. call `open-line' on the very first character."
  18610. (interactive "*p")
  18611. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  18612. (org-table-insert-row)
  18613. (open-line n)))
  18614. (defun org-return (&optional indent)
  18615. "Goto next table row or insert a newline.
  18616. Calls `org-table-next-row' or `newline', depending on context.
  18617. When optional INDENT argument is non-nil, call
  18618. `newline-and-indent' instead of `newline'.
  18619. When `org-return-follows-link' is non-nil and point is on
  18620. a timestamp or a link, call `org-open-at-point'. However, it
  18621. will not happen if point is in a table or on a \"dead\"
  18622. object (e.g., within a comment). In these case, you need to use
  18623. `org-open-at-point' directly."
  18624. (interactive)
  18625. (let ((context (if org-return-follows-link (org-element-context)
  18626. (org-element-at-point))))
  18627. (cond
  18628. ;; In a table, call `org-table-next-row'. However, before first
  18629. ;; column or after last one, split the table.
  18630. ((or (and (eq (org-element-type context) 'table)
  18631. (>= (point) (org-element-property :contents-begin context))
  18632. (< (point) (org-element-property :contents-end context)))
  18633. (org-element-lineage context '(table-row table-cell) t))
  18634. (if (or (looking-at-p "[ \t]*$")
  18635. (save-excursion (skip-chars-backward " \t") (bolp)))
  18636. (insert "\n")
  18637. (org-table-justify-field-maybe)
  18638. (call-interactively #'org-table-next-row)))
  18639. ;; On a link or a timestamp, call `org-open-at-point' if
  18640. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  18641. ;; locations, e.g., in a comment, as `org-open-at-point'.
  18642. ((and org-return-follows-link
  18643. (or (and (eq 'link (org-element-type context))
  18644. ;; Ensure point is not on the white spaces after
  18645. ;; the link.
  18646. (let ((origin (point)))
  18647. (org-with-point-at (org-element-property :end context)
  18648. (skip-chars-backward " \t")
  18649. (> (point) origin))))
  18650. (org-in-regexp org-ts-regexp-both nil t)
  18651. (org-in-regexp org-tsr-regexp-both nil t)
  18652. (org-in-regexp org-any-link-re nil t)))
  18653. (call-interactively #'org-open-at-point))
  18654. ;; Insert newline in heading, but preserve tags.
  18655. ((and (not (bolp))
  18656. (save-excursion (beginning-of-line)
  18657. (let ((case-fold-search nil))
  18658. (looking-at org-complex-heading-regexp))))
  18659. ;; At headline. Split line. However, if point is on keyword,
  18660. ;; priority cookie or tags, do not break any of them: add
  18661. ;; a newline after the headline instead.
  18662. (let ((tags-column (and (match-beginning 5)
  18663. (save-excursion (goto-char (match-beginning 5))
  18664. (current-column))))
  18665. (string
  18666. (when (and (match-end 4) (org-point-in-group (point) 4))
  18667. (delete-and-extract-region (point) (match-end 4)))))
  18668. ;; Adjust tag alignment.
  18669. (cond
  18670. ((not (and tags-column string)))
  18671. (org-auto-align-tags (org-align-tags))
  18672. (t (org--align-tags-here tags-column))) ;preserve tags column
  18673. (end-of-line)
  18674. (org-show-entry)
  18675. (if indent (newline-and-indent) (newline))
  18676. (when string (save-excursion (insert (org-trim string))))))
  18677. ;; In a list, make sure indenting keeps trailing text within.
  18678. ((and indent
  18679. (not (eolp))
  18680. (org-element-lineage context '(item)))
  18681. (let ((trailing-data
  18682. (delete-and-extract-region (point) (line-end-position))))
  18683. (newline-and-indent)
  18684. (save-excursion (insert trailing-data))))
  18685. (t
  18686. ;; Do not auto-fill when point is in an Org property drawer.
  18687. (let ((auto-fill-function (and (not (org-at-property-p))
  18688. auto-fill-function)))
  18689. (if indent
  18690. (newline-and-indent)
  18691. (newline)))))))
  18692. (defun org-return-indent ()
  18693. "Goto next table row or insert a newline and indent.
  18694. Calls `org-table-next-row' or `newline-and-indent', depending on
  18695. context. See the individual commands for more information."
  18696. (interactive)
  18697. (org-return t))
  18698. (defun org-ctrl-c-tab (&optional _arg)
  18699. "Toggle columns width in a table, or show children.
  18700. Call `org-table-toggle-column-width' if point is in a table.
  18701. Otherwise, call `org-show-children'."
  18702. (interactive "p")
  18703. (call-interactively
  18704. (if (org-at-table-p) #'org-table-toggle-column-width
  18705. #'org-show-children)))
  18706. (defun org-ctrl-c-star ()
  18707. "Compute table, or change heading status of lines.
  18708. Calls `org-table-recalculate' or `org-toggle-heading',
  18709. depending on context."
  18710. (interactive)
  18711. (cond
  18712. ((org-at-table-p)
  18713. (call-interactively 'org-table-recalculate))
  18714. (t
  18715. ;; Convert all lines in region to list items
  18716. (call-interactively 'org-toggle-heading))))
  18717. (defun org-ctrl-c-minus ()
  18718. "Insert separator line in table or modify bullet status of line.
  18719. Also turns a plain line or a region of lines into list items.
  18720. Calls `org-table-insert-hline', `org-toggle-item', or
  18721. `org-cycle-list-bullet', depending on context."
  18722. (interactive)
  18723. (cond
  18724. ((org-at-table-p)
  18725. (call-interactively 'org-table-insert-hline))
  18726. ((org-region-active-p)
  18727. (call-interactively 'org-toggle-item))
  18728. ((org-in-item-p)
  18729. (call-interactively 'org-cycle-list-bullet))
  18730. (t
  18731. (call-interactively 'org-toggle-item))))
  18732. (defun org-toggle-heading (&optional nstars)
  18733. "Convert headings to normal text, or items or text to headings.
  18734. If there is no active region, only convert the current line.
  18735. With a `\\[universal-argument]' prefix, convert the whole list at
  18736. point into heading.
  18737. In a region:
  18738. - If the first non blank line is a headline, remove the stars
  18739. from all headlines in the region.
  18740. - If it is a normal line, turn each and every normal line (i.e.,
  18741. not an heading or an item) in the region into headings. If you
  18742. want to convert only the first line of this region, use one
  18743. universal prefix argument.
  18744. - If it is a plain list item, turn all plain list items into headings.
  18745. When converting a line into a heading, the number of stars is chosen
  18746. such that the lines become children of the current entry. However,
  18747. when a numeric prefix argument is given, its value determines the
  18748. number of stars to add."
  18749. (interactive "P")
  18750. (let ((skip-blanks
  18751. (function
  18752. ;; Return beginning of first non-blank line, starting from
  18753. ;; line at POS.
  18754. (lambda (pos)
  18755. (save-excursion
  18756. (goto-char pos)
  18757. (while (org-at-comment-p) (forward-line))
  18758. (skip-chars-forward " \r\t\n")
  18759. (point-at-bol)))))
  18760. beg end toggled)
  18761. ;; Determine boundaries of changes. If a universal prefix has
  18762. ;; been given, put the list in a region. If region ends at a bol,
  18763. ;; do not consider the last line to be in the region.
  18764. (when (and current-prefix-arg (org-at-item-p))
  18765. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  18766. (org-mark-element))
  18767. (if (org-region-active-p)
  18768. (setq beg (funcall skip-blanks (region-beginning))
  18769. end (copy-marker (save-excursion
  18770. (goto-char (region-end))
  18771. (if (bolp) (point) (point-at-eol)))))
  18772. (setq beg (funcall skip-blanks (point-at-bol))
  18773. end (copy-marker (point-at-eol))))
  18774. ;; Ensure inline tasks don't count as headings.
  18775. (org-with-limited-levels
  18776. (save-excursion
  18777. (goto-char beg)
  18778. (cond
  18779. ;; Case 1. Started at an heading: de-star headings.
  18780. ((org-at-heading-p)
  18781. (while (< (point) end)
  18782. (when (org-at-heading-p t)
  18783. (looking-at org-outline-regexp) (replace-match "")
  18784. (setq toggled t))
  18785. (forward-line)))
  18786. ;; Case 2. Started at an item: change items into headlines.
  18787. ;; One star will be added by `org-list-to-subtree'.
  18788. ((org-at-item-p)
  18789. (while (< (point) end)
  18790. (when (org-at-item-p)
  18791. ;; Pay attention to cases when region ends before list.
  18792. (let* ((struct (org-list-struct))
  18793. (list-end
  18794. (min (org-list-get-bottom-point struct) (1+ end))))
  18795. (save-restriction
  18796. (narrow-to-region (point) list-end)
  18797. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  18798. (setq toggled t))
  18799. (forward-line)))
  18800. ;; Case 3. Started at normal text: make every line an heading,
  18801. ;; skipping headlines and items.
  18802. (t (let* ((stars
  18803. (make-string
  18804. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  18805. (add-stars
  18806. (cond (nstars "") ; stars from prefix only
  18807. ((equal stars "") "*") ; before first heading
  18808. (org-odd-levels-only "**") ; inside heading, odd
  18809. (t "*"))) ; inside heading, oddeven
  18810. (rpl (concat stars add-stars " "))
  18811. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  18812. (while (< (point) (if (equal nstars '(4)) lend end))
  18813. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  18814. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  18815. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  18816. (forward-line)))))))
  18817. (unless toggled (message "Cannot toggle heading from here"))))
  18818. (defun org-meta-return (&optional arg)
  18819. "Insert a new heading or wrap a region in a table.
  18820. Calls `org-insert-heading', `org-insert-item' or
  18821. `org-table-wrap-region', depending on context. When called with
  18822. an argument, unconditionally call `org-insert-heading'."
  18823. (interactive "P")
  18824. (org-check-before-invisible-edit 'insert)
  18825. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  18826. (call-interactively (cond (arg #'org-insert-heading)
  18827. ((org-at-table-p) #'org-table-wrap-region)
  18828. ((org-in-item-p) #'org-insert-item)
  18829. (t #'org-insert-heading)))))
  18830. ;;; Menu entries
  18831. (defsubst org-in-subtree-not-table-p ()
  18832. "Are we in a subtree and not in a table?"
  18833. (and (not (org-before-first-heading-p))
  18834. (not (org-at-table-p))))
  18835. ;; Define the Org mode menus
  18836. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  18837. '("Tbl"
  18838. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  18839. ["Next Field" org-cycle (org-at-table-p)]
  18840. ["Previous Field" org-shifttab (org-at-table-p)]
  18841. ["Next Row" org-return (org-at-table-p)]
  18842. "--"
  18843. ["Blank Field" org-table-blank-field (org-at-table-p)]
  18844. ["Edit Field" org-table-edit-field (org-at-table-p)]
  18845. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  18846. "--"
  18847. ("Column"
  18848. ["Move Column Left" org-metaleft (org-at-table-p)]
  18849. ["Move Column Right" org-metaright (org-at-table-p)]
  18850. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  18851. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  18852. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  18853. ("Row"
  18854. ["Move Row Up" org-metaup (org-at-table-p)]
  18855. ["Move Row Down" org-metadown (org-at-table-p)]
  18856. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  18857. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  18858. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  18859. "--"
  18860. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  18861. ("Rectangle"
  18862. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  18863. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  18864. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  18865. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  18866. "--"
  18867. ("Calculate"
  18868. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  18869. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  18870. ["Edit Formulas" org-edit-special (org-at-table-p)]
  18871. "--"
  18872. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  18873. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  18874. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  18875. "--"
  18876. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  18877. "--"
  18878. ["Sum Column/Rectangle" org-table-sum
  18879. (or (org-at-table-p) (org-region-active-p))]
  18880. ["Which Column?" org-table-current-column (org-at-table-p)])
  18881. ["Debug Formulas"
  18882. org-table-toggle-formula-debugger
  18883. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  18884. ["Show Col/Row Numbers"
  18885. org-table-toggle-coordinate-overlays
  18886. :style toggle
  18887. :selected (bound-and-true-p org-table-overlay-coordinates)]
  18888. "--"
  18889. ["Create" org-table-create (not (org-at-table-p))]
  18890. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  18891. ["Import from File" org-table-import (not (org-at-table-p))]
  18892. ["Export to File" org-table-export (org-at-table-p)]
  18893. "--"
  18894. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  18895. "--"
  18896. ("Plot"
  18897. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  18898. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  18899. (easy-menu-define org-org-menu org-mode-map "Org menu"
  18900. '("Org"
  18901. ("Show/Hide"
  18902. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  18903. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  18904. ["Sparse Tree..." org-sparse-tree t]
  18905. ["Reveal Context" org-reveal t]
  18906. ["Show All" org-show-all t]
  18907. "--"
  18908. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  18909. "--"
  18910. ["New Heading" org-insert-heading t]
  18911. ("Navigate Headings"
  18912. ["Up" outline-up-heading t]
  18913. ["Next" outline-next-visible-heading t]
  18914. ["Previous" outline-previous-visible-heading t]
  18915. ["Next Same Level" outline-forward-same-level t]
  18916. ["Previous Same Level" outline-backward-same-level t]
  18917. "--"
  18918. ["Jump" org-goto t])
  18919. ("Edit Structure"
  18920. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  18921. "--"
  18922. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  18923. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  18924. "--"
  18925. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  18926. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  18927. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  18928. "--"
  18929. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  18930. "--"
  18931. ["Copy visible text" org-copy-visible t]
  18932. "--"
  18933. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  18934. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  18935. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  18936. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  18937. "--"
  18938. ["Sort Region/Children" org-sort t]
  18939. "--"
  18940. ["Convert to odd levels" org-convert-to-odd-levels t]
  18941. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  18942. ("Editing"
  18943. ["Emphasis..." org-emphasize t]
  18944. ["Edit Source Example" org-edit-special t]
  18945. "--"
  18946. ["Footnote new/jump" org-footnote-action t]
  18947. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  18948. ("Archive"
  18949. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  18950. "--"
  18951. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  18952. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  18953. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  18954. )
  18955. "--"
  18956. ("Hyperlinks"
  18957. ["Store Link (Global)" org-store-link t]
  18958. ["Find existing link to here" org-occur-link-in-agenda-files t]
  18959. ["Insert Link" org-insert-link t]
  18960. ["Follow Link" org-open-at-point t]
  18961. "--"
  18962. ["Next link" org-next-link t]
  18963. ["Previous link" org-previous-link t]
  18964. "--"
  18965. ["Descriptive Links"
  18966. org-toggle-link-display
  18967. :style radio
  18968. :selected org-descriptive-links
  18969. ]
  18970. ["Literal Links"
  18971. org-toggle-link-display
  18972. :style radio
  18973. :selected (not org-descriptive-links)])
  18974. "--"
  18975. ("TODO Lists"
  18976. ["TODO/DONE/-" org-todo t]
  18977. ("Select keyword"
  18978. ["Next keyword" org-shiftright (org-at-heading-p)]
  18979. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  18980. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  18981. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  18982. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  18983. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  18984. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  18985. "--"
  18986. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  18987. :selected org-enforce-todo-dependencies :style toggle :active t]
  18988. "Settings for tree at point"
  18989. ["Do Children sequentially" org-toggle-ordered-property :style radio
  18990. :selected (org-entry-get nil "ORDERED")
  18991. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  18992. ["Do Children parallel" org-toggle-ordered-property :style radio
  18993. :selected (not (org-entry-get nil "ORDERED"))
  18994. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  18995. "--"
  18996. ["Set Priority" org-priority t]
  18997. ["Priority Up" org-shiftup t]
  18998. ["Priority Down" org-shiftdown t]
  18999. "--"
  19000. ["Get news from all feeds" org-feed-update-all t]
  19001. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19002. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19003. ("TAGS and Properties"
  19004. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19005. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19006. "--"
  19007. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19008. ["Column view of properties" org-columns t]
  19009. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19010. ("Dates and Scheduling"
  19011. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19012. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19013. ("Change Date"
  19014. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  19015. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  19016. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  19017. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  19018. ["Compute Time Range" org-evaluate-time-range t]
  19019. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19020. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19021. "--"
  19022. ["Custom time format" org-toggle-time-stamp-overlays
  19023. :style radio :selected org-display-custom-times]
  19024. "--"
  19025. ["Goto Calendar" org-goto-calendar t]
  19026. ["Date from Calendar" org-date-from-calendar t]
  19027. "--"
  19028. ["Start/Restart Timer" org-timer-start t]
  19029. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19030. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19031. ["Insert Timer String" org-timer t]
  19032. ["Insert Timer Item" org-timer-item t])
  19033. ("Logging work"
  19034. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19035. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19036. ["Clock out" org-clock-out t]
  19037. ["Clock cancel" org-clock-cancel t]
  19038. "--"
  19039. ["Mark as default task" org-clock-mark-default-task t]
  19040. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19041. ["Goto running clock" org-clock-goto t]
  19042. "--"
  19043. ["Display times" org-clock-display t]
  19044. ["Create clock table" org-clock-report t]
  19045. "--"
  19046. ["Record DONE time"
  19047. (progn (setq org-log-done (not org-log-done))
  19048. (message "Switching to %s will %s record a timestamp"
  19049. (car org-done-keywords)
  19050. (if org-log-done "automatically" "not")))
  19051. :style toggle :selected org-log-done])
  19052. "--"
  19053. ["Agenda Command..." org-agenda t]
  19054. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19055. ("File List for Agenda")
  19056. ("Special views current file"
  19057. ["TODO Tree" org-show-todo-tree t]
  19058. ["Check Deadlines" org-check-deadlines t]
  19059. ["Tags/Property tree" org-match-sparse-tree t])
  19060. "--"
  19061. ["Export/Publish..." org-export-dispatch t]
  19062. ("LaTeX"
  19063. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  19064. :style toggle :selected org-cdlatex-mode]
  19065. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19066. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19067. ["Modify math symbol" org-cdlatex-math-modify
  19068. (org-inside-LaTeX-fragment-p)]
  19069. ["Insert citation" org-reftex-citation t])
  19070. "--"
  19071. ("MobileOrg"
  19072. ["Push Files and Views" org-mobile-push t]
  19073. ["Get Captured and Flagged" org-mobile-pull t]
  19074. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
  19075. "--"
  19076. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19077. "--"
  19078. ("Documentation"
  19079. ["Show Version" org-version t]
  19080. ["Info Documentation" org-info t])
  19081. ("Customize"
  19082. ["Browse Org Group" org-customize t]
  19083. "--"
  19084. ["Expand This Menu" org-create-customize-menu
  19085. (fboundp 'customize-menu-create)])
  19086. ["Send bug report" org-submit-bug-report t]
  19087. "--"
  19088. ("Refresh/Reload"
  19089. ["Refresh setup current buffer" org-mode-restart t]
  19090. ["Reload Org (after update)" org-reload t]
  19091. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  19092. ))
  19093. (defun org-info (&optional node)
  19094. "Read documentation for Org in the info system.
  19095. With optional NODE, go directly to that node."
  19096. (interactive)
  19097. (info (format "(org)%s" (or node ""))))
  19098. ;;;###autoload
  19099. (defun org-submit-bug-report ()
  19100. "Submit a bug report on Org via mail.
  19101. Don't hesitate to report any problems or inaccurate documentation.
  19102. If you don't have setup sending mail from (X)Emacs, please copy the
  19103. output buffer into your mail program, as it gives us important
  19104. information about your Org version and configuration."
  19105. (interactive)
  19106. (require 'reporter)
  19107. (defvar reporter-prompt-for-summary-p)
  19108. (org-load-modules-maybe)
  19109. (org-require-autoloaded-modules)
  19110. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19111. (reporter-submit-bug-report
  19112. "emacs-orgmode@gnu.org"
  19113. (org-version nil 'full)
  19114. (let (list)
  19115. (save-window-excursion
  19116. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19117. (delete-other-windows)
  19118. (erase-buffer)
  19119. (insert "You are about to submit a bug report to the Org mailing list.
  19120. We would like to add your full Org and Outline configuration to the
  19121. bug report. This greatly simplifies the work of the maintainer and
  19122. other experts on the mailing list.
  19123. HOWEVER, some variables you have customized may contain private
  19124. information. The names of customers, colleagues, or friends, might
  19125. appear in the form of file names, tags, todo states, or search strings.
  19126. If you answer yes to the prompt, you might want to check and remove
  19127. such private information before sending the email.")
  19128. (add-text-properties (point-min) (point-max) '(face org-warning))
  19129. (when (yes-or-no-p "Include your Org configuration ")
  19130. (mapatoms
  19131. (lambda (v)
  19132. (and (boundp v)
  19133. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19134. (or (and (symbol-value v)
  19135. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19136. (and
  19137. (get v 'custom-type) (get v 'standard-value)
  19138. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19139. (push v list)))))
  19140. (kill-buffer (get-buffer "*Warn about privacy*"))
  19141. list))
  19142. nil nil
  19143. "Remember to cover the basics, that is, what you expected to happen and
  19144. what in fact did happen. You don't know how to make a good report? See
  19145. https://orgmode.org/manual/Feedback.html#Feedback
  19146. Your bug report will be posted to the Org mailing list.
  19147. ------------------------------------------------------------------------")
  19148. (save-excursion
  19149. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19150. (replace-match "\\1Bug: \\3 [\\2]")))))
  19151. (defun org-install-agenda-files-menu ()
  19152. (let ((bl (buffer-list)))
  19153. (save-excursion
  19154. (while bl
  19155. (set-buffer (pop bl))
  19156. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19157. (when (derived-mode-p 'org-mode)
  19158. (easy-menu-change
  19159. '("Org") "File List for Agenda"
  19160. (append
  19161. (list
  19162. ["Edit File List" (org-edit-agenda-file-list) t]
  19163. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19164. ["Remove Current File from List" org-remove-file t]
  19165. ["Cycle through agenda files" org-cycle-agenda-files t]
  19166. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19167. "--")
  19168. (mapcar 'org-file-menu-entry
  19169. ;; Prevent initialization from failing.
  19170. (ignore-errors (org-agenda-files t)))))))))
  19171. ;;;; Documentation
  19172. (defun org-require-autoloaded-modules ()
  19173. (interactive)
  19174. (mapc #'require
  19175. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19176. org-table org-timer)))
  19177. ;;;###autoload
  19178. (defun org-reload (&optional uncompiled)
  19179. "Reload all Org Lisp files.
  19180. With prefix arg UNCOMPILED, load the uncompiled versions."
  19181. (interactive "P")
  19182. (require 'loadhist)
  19183. (let* ((org-dir (org-find-library-dir "org"))
  19184. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19185. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  19186. (remove-re (format "\\`%s\\'"
  19187. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19188. (feats (delete-dups
  19189. (mapcar 'file-name-sans-extension
  19190. (mapcar 'file-name-nondirectory
  19191. (delq nil
  19192. (mapcar 'feature-file
  19193. features))))))
  19194. (lfeat (append
  19195. (sort
  19196. (setq feats
  19197. (delq nil (mapcar
  19198. (lambda (f)
  19199. (if (and (string-match feature-re f)
  19200. (not (string-match remove-re f)))
  19201. f nil))
  19202. feats)))
  19203. 'string-lessp)
  19204. (list "org-version" "org")))
  19205. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  19206. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19207. load-uncore load-misses)
  19208. (setq load-misses
  19209. (delq 't
  19210. (mapcar (lambda (f)
  19211. (or (org-load-noerror-mustsuffix (concat org-dir f))
  19212. (and (string= org-dir contrib-dir)
  19213. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19214. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19215. (add-to-list 'load-uncore f 'append)
  19216. 't)
  19217. f))
  19218. lfeat)))
  19219. (when load-uncore
  19220. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19221. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  19222. (if load-misses
  19223. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19224. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19225. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19226. ;;;###autoload
  19227. (defun org-customize ()
  19228. "Call the customize function with org as argument."
  19229. (interactive)
  19230. (org-load-modules-maybe)
  19231. (org-require-autoloaded-modules)
  19232. (customize-browse 'org))
  19233. (defun org-create-customize-menu ()
  19234. "Create a full customization menu for Org mode, insert it into the menu."
  19235. (interactive)
  19236. (org-load-modules-maybe)
  19237. (org-require-autoloaded-modules)
  19238. (if (fboundp 'customize-menu-create)
  19239. (progn
  19240. (easy-menu-change
  19241. '("Org") "Customize"
  19242. `(["Browse Org group" org-customize t]
  19243. "--"
  19244. ,(customize-menu-create 'org)
  19245. ["Set" Custom-set t]
  19246. ["Save" Custom-save t]
  19247. ["Reset to Current" Custom-reset-current t]
  19248. ["Reset to Saved" Custom-reset-saved t]
  19249. ["Reset to Standard Settings" Custom-reset-standard t]))
  19250. (message "\"Org\"-menu now contains full customization menu"))
  19251. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  19252. ;;;; Miscellaneous stuff
  19253. ;;; Generally useful functions
  19254. (defun org-link-display-format (s)
  19255. "Replace links in string S with their description.
  19256. If there is no description, use the link target."
  19257. (save-match-data
  19258. (replace-regexp-in-string
  19259. org-bracket-link-analytic-regexp
  19260. (lambda (m)
  19261. (if (match-end 5) (match-string 5 m)
  19262. (concat (match-string 1 m) (match-string 3 m))))
  19263. s nil t)))
  19264. (defun org-toggle-link-display ()
  19265. "Toggle the literal or descriptive display of links."
  19266. (interactive)
  19267. (if org-descriptive-links
  19268. (progn (org-remove-from-invisibility-spec '(org-link))
  19269. (org-restart-font-lock)
  19270. (setq org-descriptive-links nil))
  19271. (progn (add-to-invisibility-spec '(org-link))
  19272. (org-restart-font-lock)
  19273. (setq org-descriptive-links t))))
  19274. (defun org-in-clocktable-p ()
  19275. "Check if the cursor is in a clocktable."
  19276. (let ((pos (point)) start)
  19277. (save-excursion
  19278. (end-of-line 1)
  19279. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19280. (setq start (match-beginning 0))
  19281. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19282. (>= (match-end 0) pos)
  19283. start))))
  19284. (defun org-in-verbatim-emphasis ()
  19285. (save-match-data
  19286. (and (org-in-regexp org-verbatim-re 2)
  19287. (>= (point) (match-beginning 3))
  19288. (<= (point) (match-end 4)))))
  19289. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19290. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  19291. (if (and marker (marker-buffer marker)
  19292. (buffer-live-p (marker-buffer marker)))
  19293. (progn
  19294. (pop-to-buffer-same-window (marker-buffer marker))
  19295. (when (or (> marker (point-max)) (< marker (point-min)))
  19296. (widen))
  19297. (goto-char marker)
  19298. (org-show-context 'org-goto))
  19299. (if bookmark
  19300. (bookmark-jump bookmark)
  19301. (error "Cannot find location"))))
  19302. (defun org-quote-csv-field (s)
  19303. "Quote field for inclusion in CSV material."
  19304. (if (string-match "[\",]" s)
  19305. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19306. s))
  19307. (defun org-force-self-insert (N)
  19308. "Needed to enforce self-insert under remapping."
  19309. (interactive "p")
  19310. (self-insert-command N))
  19311. (defun org-fill-template (template alist)
  19312. "Find each %key of ALIST in TEMPLATE and replace it."
  19313. (let ((case-fold-search nil))
  19314. (dolist (entry (sort (copy-sequence alist)
  19315. (lambda (a b) (< (length (car a)) (length (car b))))))
  19316. (setq template
  19317. (replace-regexp-in-string
  19318. (concat "%" (regexp-quote (car entry)))
  19319. (or (cdr entry) "") template t t)))
  19320. template))
  19321. (defun org-quote-vert (s)
  19322. "Replace \"|\" with \"\\vert\"."
  19323. (while (string-match "|" s)
  19324. (setq s (replace-match "\\vert" t t s)))
  19325. s)
  19326. (defun org-uuidgen-p (s)
  19327. "Is S an ID created by UUIDGEN?"
  19328. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  19329. (defun org-in-src-block-p (&optional inside)
  19330. "Whether point is in a code source block.
  19331. When INSIDE is non-nil, don't consider we are within a src block
  19332. when point is at #+BEGIN_SRC or #+END_SRC."
  19333. (let ((case-fold-search t))
  19334. (or (and (eq (get-char-property (point) 'src-block) t))
  19335. (and (not inside)
  19336. (save-match-data
  19337. (save-excursion
  19338. (beginning-of-line)
  19339. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  19340. (defun org-context ()
  19341. "Return a list of contexts of the current cursor position.
  19342. If several contexts apply, all are returned.
  19343. Each context entry is a list with a symbol naming the context, and
  19344. two positions indicating start and end of the context. Possible
  19345. contexts are:
  19346. :headline anywhere in a headline
  19347. :headline-stars on the leading stars in a headline
  19348. :todo-keyword on a TODO keyword (including DONE) in a headline
  19349. :tags on the TAGS in a headline
  19350. :priority on the priority cookie in a headline
  19351. :item on the first line of a plain list item
  19352. :item-bullet on the bullet/number of a plain list item
  19353. :checkbox on the checkbox in a plain list item
  19354. :table in an Org table
  19355. :table-special on a special filed in a table
  19356. :table-table in a table.el table
  19357. :clocktable in a clocktable
  19358. :src-block in a source block
  19359. :link on a hyperlink
  19360. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  19361. :target on a <<target>>
  19362. :radio-target on a <<<radio-target>>>
  19363. :latex-fragment on a LaTeX fragment
  19364. :latex-preview on a LaTeX fragment with overlaid preview image
  19365. This function expects the position to be visible because it uses font-lock
  19366. faces as a help to recognize the following contexts: :table-special, :link,
  19367. and :keyword."
  19368. (let* ((f (get-text-property (point) 'face))
  19369. (faces (if (listp f) f (list f)))
  19370. (case-fold-search t)
  19371. (p (point)) clist o)
  19372. ;; First the large context
  19373. (cond
  19374. ((org-at-heading-p t)
  19375. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  19376. (when (progn
  19377. (beginning-of-line 1)
  19378. (looking-at org-todo-line-tags-regexp))
  19379. (push (org-point-in-group p 1 :headline-stars) clist)
  19380. (push (org-point-in-group p 2 :todo-keyword) clist)
  19381. (push (org-point-in-group p 4 :tags) clist))
  19382. (goto-char p)
  19383. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  19384. (when (looking-at "\\[#[A-Z0-9]\\]")
  19385. (push (org-point-in-group p 0 :priority) clist)))
  19386. ((org-at-item-p)
  19387. (push (org-point-in-group p 2 :item-bullet) clist)
  19388. (push (list :item (point-at-bol)
  19389. (save-excursion (org-end-of-item) (point)))
  19390. clist)
  19391. (and (org-at-item-checkbox-p)
  19392. (push (org-point-in-group p 0 :checkbox) clist)))
  19393. ((org-at-table-p)
  19394. (push (list :table (org-table-begin) (org-table-end)) clist)
  19395. (when (memq 'org-formula faces)
  19396. (push (list :table-special
  19397. (previous-single-property-change p 'face)
  19398. (next-single-property-change p 'face)) clist)))
  19399. ((org-at-table-p 'any)
  19400. (push (list :table-table) clist)))
  19401. (goto-char p)
  19402. (let ((case-fold-search t))
  19403. ;; New the "medium" contexts: clocktables, source blocks
  19404. (cond ((org-in-clocktable-p)
  19405. (push (list :clocktable
  19406. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  19407. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  19408. (match-beginning 1))
  19409. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  19410. (match-end 0))) clist))
  19411. ((org-in-src-block-p)
  19412. (push (list :src-block
  19413. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  19414. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  19415. (match-beginning 1))
  19416. (and (search-forward "#+END_SRC" nil t)
  19417. (match-beginning 0))) clist))))
  19418. (goto-char p)
  19419. ;; Now the small context
  19420. (cond
  19421. ((org-at-timestamp-p)
  19422. (push (org-point-in-group p 0 :timestamp) clist))
  19423. ((memq 'org-link faces)
  19424. (push (list :link
  19425. (previous-single-property-change p 'face)
  19426. (next-single-property-change p 'face)) clist))
  19427. ((memq 'org-special-keyword faces)
  19428. (push (list :keyword
  19429. (previous-single-property-change p 'face)
  19430. (next-single-property-change p 'face)) clist))
  19431. ((org-at-target-p)
  19432. (push (org-point-in-group p 0 :target) clist)
  19433. (goto-char (1- (match-beginning 0)))
  19434. (when (looking-at org-radio-target-regexp)
  19435. (push (org-point-in-group p 0 :radio-target) clist))
  19436. (goto-char p))
  19437. ((setq o (cl-some
  19438. (lambda (o)
  19439. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  19440. o))
  19441. (overlays-at (point))))
  19442. (push (list :latex-fragment
  19443. (overlay-start o) (overlay-end o)) clist)
  19444. (push (list :latex-preview
  19445. (overlay-start o) (overlay-end o)) clist))
  19446. ((org-inside-LaTeX-fragment-p)
  19447. ;; FIXME: positions wrong.
  19448. (push (list :latex-fragment (point) (point)) clist)))
  19449. (setq clist (nreverse (delq nil clist)))
  19450. clist))
  19451. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  19452. "Non-nil when point is between matches of START-RE and END-RE.
  19453. Also return a non-nil value when point is on one of the matches.
  19454. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  19455. buffer positions. Default values are the positions of headlines
  19456. surrounding the point.
  19457. The functions returns a cons cell whose car (resp. cdr) is the
  19458. position before START-RE (resp. after END-RE)."
  19459. (save-match-data
  19460. (let ((pos (point))
  19461. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  19462. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  19463. beg end)
  19464. (save-excursion
  19465. ;; Point is on a block when on START-RE or if START-RE can be
  19466. ;; found before it...
  19467. (and (or (org-in-regexp start-re)
  19468. (re-search-backward start-re limit-up t))
  19469. (setq beg (match-beginning 0))
  19470. ;; ... and END-RE after it...
  19471. (goto-char (match-end 0))
  19472. (re-search-forward end-re limit-down t)
  19473. (> (setq end (match-end 0)) pos)
  19474. ;; ... without another START-RE in-between.
  19475. (goto-char (match-beginning 0))
  19476. (not (re-search-backward start-re (1+ beg) t))
  19477. ;; Return value.
  19478. (cons beg end))))))
  19479. (defun org-in-block-p (names)
  19480. "Non-nil when point belongs to a block whose name belongs to NAMES.
  19481. NAMES is a list of strings containing names of blocks.
  19482. Return first block name matched, or nil. Beware that in case of
  19483. nested blocks, the returned name may not belong to the closest
  19484. block from point."
  19485. (save-match-data
  19486. (catch 'exit
  19487. (let ((case-fold-search t)
  19488. (lim-up (save-excursion (outline-previous-heading)))
  19489. (lim-down (save-excursion (outline-next-heading))))
  19490. (dolist (name names)
  19491. (let ((n (regexp-quote name)))
  19492. (when (org-between-regexps-p
  19493. (concat "^[ \t]*#\\+begin_" n)
  19494. (concat "^[ \t]*#\\+end_" n)
  19495. lim-up lim-down)
  19496. (throw 'exit n)))))
  19497. nil)))
  19498. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  19499. "Call `multi-occur' with buffers for all agenda files."
  19500. (interactive "sOrg-files matching: ")
  19501. (let* ((files (org-agenda-files))
  19502. (tnames (mapcar #'file-truename files))
  19503. (extra org-agenda-text-search-extra-files))
  19504. (when (eq (car extra) 'agenda-archives)
  19505. (setq extra (cdr extra))
  19506. (setq files (org-add-archive-files files)))
  19507. (dolist (f extra)
  19508. (unless (member (file-truename f) tnames)
  19509. (unless (member f files) (setq files (append files (list f))))
  19510. (setq tnames (append tnames (list (file-truename f))))))
  19511. (multi-occur
  19512. (mapcar (lambda (x)
  19513. (with-current-buffer
  19514. ;; FIXME: Why not just (find-file-noselect x)?
  19515. ;; Is it to avoid the "revert buffer" prompt?
  19516. (or (get-file-buffer x) (find-file-noselect x))
  19517. (widen)
  19518. (current-buffer)))
  19519. files)
  19520. regexp)))
  19521. (add-hook 'occur-mode-find-occurrence-hook
  19522. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  19523. (defun org-occur-link-in-agenda-files ()
  19524. "Create a link and search for it in the agendas.
  19525. The link is not stored in `org-stored-links', it is just created
  19526. for the search purpose."
  19527. (interactive)
  19528. (let ((link (condition-case nil
  19529. (org-store-link nil)
  19530. (error "Unable to create a link to here"))))
  19531. (org-occur-in-agenda-files (regexp-quote link))))
  19532. (defun org-back-over-empty-lines ()
  19533. "Move backwards over whitespace, to the beginning of the first empty line.
  19534. Returns the number of empty lines passed."
  19535. (let ((pos (point)))
  19536. (if (cdr (assq 'heading org-blank-before-new-entry))
  19537. (skip-chars-backward " \t\n\r")
  19538. (unless (eobp)
  19539. (forward-line -1)))
  19540. (beginning-of-line 2)
  19541. (goto-char (min (point) pos))
  19542. (count-lines (point) pos)))
  19543. (defun org-switch-to-buffer-other-window (&rest args)
  19544. "Switch to buffer in a second window on the current frame.
  19545. In particular, do not allow pop-up frames.
  19546. Returns the newly created buffer."
  19547. (org-no-popups
  19548. (apply 'switch-to-buffer-other-window args)))
  19549. (defun org-replace-escapes (string table)
  19550. "Replace %-escapes in STRING with values in TABLE.
  19551. TABLE is an association list with keys like \"%a\" and string values.
  19552. The sequences in STRING may contain normal field width and padding information,
  19553. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  19554. so values can contain further %-escapes if they are define later in TABLE."
  19555. (let ((tbl (copy-alist table))
  19556. (case-fold-search nil)
  19557. (pchg 0)
  19558. re rpl)
  19559. (dolist (e tbl)
  19560. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  19561. (when (and (cdr e) (string-match re (cdr e)))
  19562. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  19563. (safe "SREF"))
  19564. (add-text-properties 0 3 (list 'sref sref) safe)
  19565. (setcdr e (replace-match safe t t (cdr e)))))
  19566. (while (string-match re string)
  19567. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  19568. (cdr e)))
  19569. (setq string (replace-match rpl t t string))))
  19570. (while (setq pchg (next-property-change pchg string))
  19571. (let ((sref (get-text-property pchg 'sref string)))
  19572. (when (and sref (string-match "SREF" string pchg))
  19573. (setq string (replace-match sref t t string)))))
  19574. string))
  19575. ;;; TODO: Only called once, from ox-odt which should probably use
  19576. ;;; org-export-inline-image-p or something.
  19577. (defun org-file-image-p (file)
  19578. "Return non-nil if FILE is an image."
  19579. (save-match-data
  19580. (string-match (image-file-name-regexp) file)))
  19581. (defun org-get-cursor-date (&optional with-time)
  19582. "Return the date at cursor in as a time.
  19583. This works in the calendar and in the agenda, anywhere else it just
  19584. returns the current time.
  19585. If WITH-TIME is non-nil, returns the time of the event at point (in
  19586. the agenda) or the current time of the day."
  19587. (let (date day defd tp hod mod)
  19588. (when with-time
  19589. (setq tp (get-text-property (point) 'time))
  19590. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  19591. (setq hod (string-to-number (match-string 1 tp))
  19592. mod (string-to-number (match-string 2 tp))))
  19593. (or tp (let ((now (decode-time)))
  19594. (setq hod (nth 2 now)
  19595. mod (nth 1 now)))))
  19596. (cond
  19597. ((eq major-mode 'calendar-mode)
  19598. (setq date (calendar-cursor-to-date)
  19599. defd (encode-time 0 (or mod 0) (or hod 0)
  19600. (nth 1 date) (nth 0 date) (nth 2 date))))
  19601. ((eq major-mode 'org-agenda-mode)
  19602. (setq day (get-text-property (point) 'day))
  19603. (when day
  19604. (setq date (calendar-gregorian-from-absolute day)
  19605. defd (encode-time 0 (or mod 0) (or hod 0)
  19606. (nth 1 date) (nth 0 date) (nth 2 date))))))
  19607. (or defd (current-time))))
  19608. (defun org-mark-subtree (&optional up)
  19609. "Mark the current subtree.
  19610. This puts point at the start of the current subtree, and mark at
  19611. the end. If a numeric prefix UP is given, move up into the
  19612. hierarchy of headlines by UP levels before marking the subtree."
  19613. (interactive "P")
  19614. (org-with-limited-levels
  19615. (cond ((org-at-heading-p) (beginning-of-line))
  19616. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  19617. (t (outline-previous-visible-heading 1))))
  19618. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  19619. (if (called-interactively-p 'any)
  19620. (call-interactively 'org-mark-element)
  19621. (org-mark-element)))
  19622. ;;; Indentation
  19623. (defvar org-element-greater-elements)
  19624. (defun org--get-expected-indentation (element contentsp)
  19625. "Expected indentation column for current line, according to ELEMENT.
  19626. ELEMENT is an element containing point. CONTENTSP is non-nil
  19627. when indentation is to be computed according to contents of
  19628. ELEMENT."
  19629. (let ((type (org-element-type element))
  19630. (start (org-element-property :begin element))
  19631. (post-affiliated (org-element-property :post-affiliated element)))
  19632. (org-with-wide-buffer
  19633. (cond
  19634. (contentsp
  19635. (cl-case type
  19636. ((diary-sexp footnote-definition) 0)
  19637. ((headline inlinetask nil)
  19638. (if (not org-adapt-indentation) 0
  19639. (let ((level (org-current-level)))
  19640. (if level (1+ level) 0))))
  19641. ((item plain-list) (org-list-item-body-column post-affiliated))
  19642. (t
  19643. (goto-char start)
  19644. (org-get-indentation))))
  19645. ((memq type '(headline inlinetask nil))
  19646. (if (org-match-line "[ \t]*$")
  19647. (org--get-expected-indentation element t)
  19648. 0))
  19649. ((memq type '(diary-sexp footnote-definition)) 0)
  19650. ;; First paragraph of a footnote definition or an item.
  19651. ;; Indent like parent.
  19652. ((< (line-beginning-position) start)
  19653. (org--get-expected-indentation
  19654. (org-element-property :parent element) t))
  19655. ;; At first line: indent according to previous sibling, if any,
  19656. ;; ignoring footnote definitions and inline tasks, or parent's
  19657. ;; contents.
  19658. ((= (line-beginning-position) start)
  19659. (catch 'exit
  19660. (while t
  19661. (if (= (point-min) start) (throw 'exit 0)
  19662. (goto-char (1- start))
  19663. (let* ((previous (org-element-at-point))
  19664. (parent previous))
  19665. (while (and parent (<= (org-element-property :end parent) start))
  19666. (setq previous parent
  19667. parent (org-element-property :parent parent)))
  19668. (cond
  19669. ((not previous) (throw 'exit 0))
  19670. ((> (org-element-property :end previous) start)
  19671. (throw 'exit (org--get-expected-indentation previous t)))
  19672. ((memq (org-element-type previous)
  19673. '(footnote-definition inlinetask))
  19674. (setq start (org-element-property :begin previous)))
  19675. (t (goto-char (org-element-property :begin previous))
  19676. (throw 'exit
  19677. (if (bolp) (org-get-indentation)
  19678. ;; At first paragraph in an item or
  19679. ;; a footnote definition.
  19680. (org--get-expected-indentation
  19681. (org-element-property :parent previous) t))))))))))
  19682. ;; Otherwise, move to the first non-blank line above.
  19683. (t
  19684. (beginning-of-line)
  19685. (let ((pos (point)))
  19686. (skip-chars-backward " \r\t\n")
  19687. (cond
  19688. ;; Two blank lines end a footnote definition or a plain
  19689. ;; list. When we indent an empty line after them, the
  19690. ;; containing list or footnote definition is over, so it
  19691. ;; qualifies as a previous sibling. Therefore, we indent
  19692. ;; like its first line.
  19693. ((and (memq type '(footnote-definition plain-list))
  19694. (> (count-lines (point) pos) 2))
  19695. (goto-char start)
  19696. (org-get-indentation))
  19697. ;; Line above is the first one of a paragraph at the
  19698. ;; beginning of an item or a footnote definition. Indent
  19699. ;; like parent.
  19700. ((< (line-beginning-position) start)
  19701. (org--get-expected-indentation
  19702. (org-element-property :parent element) t))
  19703. ;; Line above is the beginning of an element, i.e., point
  19704. ;; was originally on the blank lines between element's start
  19705. ;; and contents.
  19706. ((= (line-beginning-position) post-affiliated)
  19707. (org--get-expected-indentation element t))
  19708. ;; POS is after contents in a greater element. Indent like
  19709. ;; the beginning of the element.
  19710. ((and (memq type org-element-greater-elements)
  19711. (let ((cend (org-element-property :contents-end element)))
  19712. (and cend (<= cend pos))))
  19713. ;; As a special case, if point is at the end of a footnote
  19714. ;; definition or an item, indent like the very last element
  19715. ;; within. If that last element is an item, indent like
  19716. ;; its contents.
  19717. (if (memq type '(footnote-definition item plain-list))
  19718. (let ((last (org-element-at-point)))
  19719. (goto-char pos)
  19720. (org--get-expected-indentation
  19721. last (eq (org-element-type last) 'item)))
  19722. (goto-char start)
  19723. (org-get-indentation)))
  19724. ;; In any other case, indent like the current line.
  19725. (t (org-get-indentation)))))))))
  19726. (defun org--align-node-property ()
  19727. "Align node property at point.
  19728. Alignment is done according to `org-property-format', which see."
  19729. (when (save-excursion
  19730. (beginning-of-line)
  19731. (looking-at org-property-re))
  19732. (replace-match
  19733. (concat (match-string 4)
  19734. (org-trim
  19735. (format org-property-format (match-string 1) (match-string 3))))
  19736. t t)))
  19737. (defun org-indent-line ()
  19738. "Indent line depending on context.
  19739. Indentation is done according to the following rules:
  19740. - Footnote definitions, diary sexps, headlines and inline tasks
  19741. have to start at column 0.
  19742. - On the very first line of an element, consider, in order, the
  19743. next rules until one matches:
  19744. 1. If there's a sibling element before, ignoring footnote
  19745. definitions and inline tasks, indent like its first line.
  19746. 2. If element has a parent, indent like its contents. More
  19747. precisely, if parent is an item, indent after the
  19748. description part, if any, or the bullet (see
  19749. `org-list-description-max-indent'). Else, indent like
  19750. parent's first line.
  19751. 3. Otherwise, indent relatively to current level, if
  19752. `org-adapt-indentation' is non-nil, or to left margin.
  19753. - On a blank line at the end of an element, indent according to
  19754. the type of the element. More precisely
  19755. 1. If element is a plain list, an item, or a footnote
  19756. definition, indent like the very last element within.
  19757. 2. If element is a paragraph, indent like its last non blank
  19758. line.
  19759. 3. Otherwise, indent like its very first line.
  19760. - In the code part of a source block, use language major mode
  19761. to indent current line if `org-src-tab-acts-natively' is
  19762. non-nil. If it is nil, do nothing.
  19763. - Otherwise, indent like the first non-blank line above.
  19764. The function doesn't indent an item as it could break the whole
  19765. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  19766. `\\[org-shiftmetaright]'.
  19767. Also align node properties according to `org-property-format'."
  19768. (interactive)
  19769. (cond
  19770. ((org-at-heading-p) 'noindent)
  19771. (t
  19772. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  19773. (type (org-element-type element)))
  19774. (cond ((and (memq type '(plain-list item))
  19775. (= (line-beginning-position)
  19776. (org-element-property :post-affiliated element)))
  19777. 'noindent)
  19778. ((and (eq type 'latex-environment)
  19779. (>= (point) (org-element-property :post-affiliated element))
  19780. (< (point) (org-with-wide-buffer
  19781. (goto-char (org-element-property :end element))
  19782. (skip-chars-backward " \r\t\n")
  19783. (line-beginning-position 2))))
  19784. 'noindent)
  19785. ((and (eq type 'src-block)
  19786. org-src-tab-acts-natively
  19787. (> (line-beginning-position)
  19788. (org-element-property :post-affiliated element))
  19789. (< (line-beginning-position)
  19790. (org-with-wide-buffer
  19791. (goto-char (org-element-property :end element))
  19792. (skip-chars-backward " \r\t\n")
  19793. (line-beginning-position))))
  19794. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  19795. (t
  19796. (let ((column (org--get-expected-indentation element nil)))
  19797. ;; Preserve current column.
  19798. (if (<= (current-column) (current-indentation))
  19799. (indent-line-to column)
  19800. (save-excursion (indent-line-to column))))
  19801. ;; Align node property. Also preserve current column.
  19802. (when (eq type 'node-property)
  19803. (let ((column (current-column)))
  19804. (org--align-node-property)
  19805. (org-move-to-column column)))))))))
  19806. (defun org-indent-region (start end)
  19807. "Indent each non-blank line in the region.
  19808. Called from a program, START and END specify the region to
  19809. indent. The function will not indent contents of example blocks,
  19810. verse blocks and export blocks as leading white spaces are
  19811. assumed to be significant there."
  19812. (interactive "r")
  19813. (save-excursion
  19814. (goto-char start)
  19815. (skip-chars-forward " \r\t\n")
  19816. (unless (eobp) (beginning-of-line))
  19817. (let ((indent-to
  19818. (lambda (ind pos)
  19819. ;; Set IND as indentation for all lines between point and
  19820. ;; POS. Blank lines are ignored. Leave point after POS
  19821. ;; once done.
  19822. (let ((limit (copy-marker pos)))
  19823. (while (< (point) limit)
  19824. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  19825. (forward-line))
  19826. (set-marker limit nil))))
  19827. (end (copy-marker end)))
  19828. (while (< (point) end)
  19829. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  19830. (let* ((element (org-element-at-point))
  19831. (type (org-element-type element))
  19832. (element-end (copy-marker (org-element-property :end element)))
  19833. (ind (org--get-expected-indentation element nil)))
  19834. (cond
  19835. ;; Element indented as a single block. Example blocks
  19836. ;; preserving indentation are a special case since the
  19837. ;; "contents" must not be indented whereas the block
  19838. ;; boundaries can.
  19839. ((or (memq type '(export-block latex-environment))
  19840. (and (eq type 'example-block)
  19841. (not
  19842. (or org-src-preserve-indentation
  19843. (org-element-property :preserve-indent element)))))
  19844. (let ((offset (- ind (org-get-indentation))))
  19845. (unless (zerop offset)
  19846. (indent-rigidly (org-element-property :begin element)
  19847. (org-element-property :end element)
  19848. offset)))
  19849. (goto-char element-end))
  19850. ;; Elements indented line wise. Be sure to exclude
  19851. ;; example blocks (preserving indentation) and source
  19852. ;; blocks from this category as they are treated
  19853. ;; specially later.
  19854. ((or (memq type '(paragraph table table-row))
  19855. (not (or (org-element-property :contents-begin element)
  19856. (memq type '(example-block src-block)))))
  19857. (when (eq type 'node-property)
  19858. (org--align-node-property)
  19859. (beginning-of-line))
  19860. (funcall indent-to ind (min element-end end)))
  19861. ;; Elements consisting of three parts: before the
  19862. ;; contents, the contents, and after the contents. The
  19863. ;; contents are treated specially, according to the
  19864. ;; element type, or not indented at all. Other parts are
  19865. ;; indented as a single block.
  19866. (t
  19867. (let* ((post (copy-marker
  19868. (org-element-property :post-affiliated element)))
  19869. (cbeg
  19870. (copy-marker
  19871. (cond
  19872. ((not (org-element-property :contents-begin element))
  19873. ;; Fake contents for source blocks.
  19874. (org-with-wide-buffer
  19875. (goto-char post)
  19876. (line-beginning-position 2)))
  19877. ((memq type '(footnote-definition item plain-list))
  19878. ;; Contents in these elements could start on
  19879. ;; the same line as the beginning of the
  19880. ;; element. Make sure we start indenting
  19881. ;; from the second line.
  19882. (org-with-wide-buffer
  19883. (goto-char post)
  19884. (end-of-line)
  19885. (skip-chars-forward " \r\t\n")
  19886. (if (eobp) (point) (line-beginning-position))))
  19887. (t (org-element-property :contents-begin element)))))
  19888. (cend (copy-marker
  19889. (or (org-element-property :contents-end element)
  19890. ;; Fake contents for source blocks.
  19891. (org-with-wide-buffer
  19892. (goto-char element-end)
  19893. (skip-chars-backward " \r\t\n")
  19894. (line-beginning-position)))
  19895. t)))
  19896. ;; Do not change items indentation individually as it
  19897. ;; might break the list as a whole. On the other
  19898. ;; hand, when at a plain list, indent it as a whole.
  19899. (cond ((eq type 'plain-list)
  19900. (let ((offset (- ind (org-get-indentation))))
  19901. (unless (zerop offset)
  19902. (indent-rigidly (org-element-property :begin element)
  19903. (org-element-property :end element)
  19904. offset))
  19905. (goto-char cbeg)))
  19906. ((eq type 'item) (goto-char cbeg))
  19907. (t (funcall indent-to ind (min cbeg end))))
  19908. (when (< (point) end)
  19909. (cl-case type
  19910. ((example-block verse-block))
  19911. (src-block
  19912. ;; In a source block, indent source code
  19913. ;; according to language major mode, but only if
  19914. ;; `org-src-tab-acts-natively' is non-nil.
  19915. (when (and (< (point) end) org-src-tab-acts-natively)
  19916. (ignore-errors
  19917. (org-babel-do-in-edit-buffer
  19918. (indent-region (point-min) (point-max))))))
  19919. (t (org-indent-region (point) (min cend end))))
  19920. (goto-char (min cend end))
  19921. (when (< (point) end)
  19922. (funcall indent-to ind (min element-end end))))
  19923. (set-marker post nil)
  19924. (set-marker cbeg nil)
  19925. (set-marker cend nil))))
  19926. (set-marker element-end nil))))
  19927. (set-marker end nil))))
  19928. (defun org-indent-drawer ()
  19929. "Indent the drawer at point."
  19930. (interactive)
  19931. (unless (save-excursion
  19932. (beginning-of-line)
  19933. (looking-at-p org-drawer-regexp))
  19934. (user-error "Not at a drawer"))
  19935. (let ((element (org-element-at-point)))
  19936. (unless (memq (org-element-type element) '(drawer property-drawer))
  19937. (user-error "Not at a drawer"))
  19938. (org-with-wide-buffer
  19939. (org-indent-region (org-element-property :begin element)
  19940. (org-element-property :end element))))
  19941. (message "Drawer at point indented"))
  19942. (defun org-indent-block ()
  19943. "Indent the block at point."
  19944. (interactive)
  19945. (unless (save-excursion
  19946. (beginning-of-line)
  19947. (let ((case-fold-search t))
  19948. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  19949. (user-error "Not at a block"))
  19950. (let ((element (org-element-at-point)))
  19951. (unless (memq (org-element-type element)
  19952. '(comment-block center-block dynamic-block example-block
  19953. export-block quote-block special-block
  19954. src-block verse-block))
  19955. (user-error "Not at a block"))
  19956. (org-with-wide-buffer
  19957. (org-indent-region (org-element-property :begin element)
  19958. (org-element-property :end element))))
  19959. (message "Block at point indented"))
  19960. ;;; Filling
  19961. ;; We use our own fill-paragraph and auto-fill functions.
  19962. ;; `org-fill-paragraph' relies on adaptive filling and context
  19963. ;; checking. Appropriate `fill-prefix' is computed with
  19964. ;; `org-adaptive-fill-function'.
  19965. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  19966. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  19967. ;; `org-adaptive-fill-function' value. Internally,
  19968. ;; `org-comment-line-break-function' breaks the line.
  19969. ;; `org-setup-filling' installs filling and auto-filling related
  19970. ;; variables during `org-mode' initialization.
  19971. (defun org-setup-filling ()
  19972. (require 'org-element)
  19973. ;; Prevent auto-fill from inserting unwanted new items.
  19974. (when (boundp 'fill-nobreak-predicate)
  19975. (setq-local
  19976. fill-nobreak-predicate
  19977. (org-uniquify
  19978. (append fill-nobreak-predicate
  19979. '(org-fill-line-break-nobreak-p
  19980. org-fill-n-macro-as-item-nobreak-p
  19981. org-fill-paragraph-with-timestamp-nobreak-p)))))
  19982. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  19983. (setq-local paragraph-start paragraph-ending)
  19984. (setq-local paragraph-separate paragraph-ending))
  19985. (setq-local fill-paragraph-function 'org-fill-paragraph)
  19986. (setq-local auto-fill-inhibit-regexp nil)
  19987. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  19988. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  19989. (setq-local comment-line-break-function 'org-comment-line-break-function))
  19990. (defun org-fill-line-break-nobreak-p ()
  19991. "Non-nil when a new line at point would create an Org line break."
  19992. (save-excursion
  19993. (skip-chars-backward "[ \t]")
  19994. (skip-chars-backward "\\\\")
  19995. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  19996. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  19997. "Non-nil when a new line at point would split a timestamp."
  19998. (and (org-at-timestamp-p 'lax)
  19999. (not (looking-at org-ts-regexp-both))))
  20000. (defun org-fill-n-macro-as-item-nobreak-p ()
  20001. "Non-nil when a new line at point would create a new list."
  20002. ;; During export, a "n" macro followed by a dot or a closing
  20003. ;; parenthesis can end up being parsed as a new list item.
  20004. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  20005. (defvar orgtbl-line-start-regexp) ; From org-table.el
  20006. (defun org-adaptive-fill-function ()
  20007. "Compute a fill prefix for the current line.
  20008. Return fill prefix, as a string, or nil if current line isn't
  20009. meant to be filled. For convenience, if `adaptive-fill-regexp'
  20010. matches in paragraphs or comments, use it."
  20011. (org-with-wide-buffer
  20012. (unless (org-at-heading-p)
  20013. (let* ((p (line-beginning-position))
  20014. (element (save-excursion
  20015. (beginning-of-line)
  20016. (org-element-at-point)))
  20017. (type (org-element-type element))
  20018. (post-affiliated (org-element-property :post-affiliated element)))
  20019. (unless (< p post-affiliated)
  20020. (cl-case type
  20021. (comment
  20022. (save-excursion
  20023. (beginning-of-line)
  20024. (looking-at "[ \t]*")
  20025. (concat (match-string 0) "# ")))
  20026. (footnote-definition "")
  20027. ((item plain-list)
  20028. (make-string (org-list-item-body-column post-affiliated) ?\s))
  20029. (paragraph
  20030. ;; Fill prefix is usually the same as the current line,
  20031. ;; unless the paragraph is at the beginning of an item.
  20032. (let ((parent (org-element-property :parent element)))
  20033. (save-excursion
  20034. (beginning-of-line)
  20035. (cond ((eq (org-element-type parent) 'item)
  20036. (make-string (org-list-item-body-column
  20037. (org-element-property :begin parent))
  20038. ?\s))
  20039. ((and adaptive-fill-regexp
  20040. ;; Locally disable
  20041. ;; `adaptive-fill-function' to let
  20042. ;; `fill-context-prefix' handle
  20043. ;; `adaptive-fill-regexp' variable.
  20044. (let (adaptive-fill-function)
  20045. (fill-context-prefix
  20046. post-affiliated
  20047. (org-element-property :end element)))))
  20048. ((looking-at "[ \t]+") (match-string 0))
  20049. (t "")))))
  20050. (comment-block
  20051. ;; Only fill contents if P is within block boundaries.
  20052. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  20053. (forward-line)
  20054. (point)))
  20055. (cend (save-excursion
  20056. (goto-char (org-element-property :end element))
  20057. (skip-chars-backward " \r\t\n")
  20058. (line-beginning-position))))
  20059. (when (and (>= p cbeg) (< p cend))
  20060. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  20061. (match-string 0)
  20062. ""))))))))))
  20063. (defun org-fill-element (&optional justify)
  20064. "Fill element at point, when applicable.
  20065. This function only applies to comment blocks, comments, example
  20066. blocks and paragraphs. Also, as a special case, re-align table
  20067. when point is at one.
  20068. If JUSTIFY is non-nil (interactively, with prefix argument),
  20069. justify as well. If `sentence-end-double-space' is non-nil, then
  20070. period followed by one space does not end a sentence, so don't
  20071. break a line there. The variable `fill-column' controls the
  20072. width for filling.
  20073. For convenience, when point is at a plain list, an item or
  20074. a footnote definition, try to fill the first paragraph within."
  20075. (with-syntax-table org-mode-transpose-word-syntax-table
  20076. ;; Move to end of line in order to get the first paragraph within
  20077. ;; a plain list or a footnote definition.
  20078. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  20079. ;; First check if point is in a blank line at the beginning of
  20080. ;; the buffer. In that case, ignore filling.
  20081. (cl-case (org-element-type element)
  20082. ;; Use major mode filling function is src blocks.
  20083. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  20084. ;; Align Org tables, leave table.el tables as-is.
  20085. (table-row (org-table-align) t)
  20086. (table
  20087. (when (eq (org-element-property :type element) 'org)
  20088. (save-excursion
  20089. (goto-char (org-element-property :post-affiliated element))
  20090. (org-table-align)))
  20091. t)
  20092. (paragraph
  20093. ;; Paragraphs may contain `line-break' type objects.
  20094. (let ((beg (max (point-min)
  20095. (org-element-property :contents-begin element)))
  20096. (end (min (point-max)
  20097. (org-element-property :contents-end element))))
  20098. ;; Do nothing if point is at an affiliated keyword.
  20099. (if (< (line-end-position) beg) t
  20100. ;; Fill paragraph, taking line breaks into account.
  20101. (save-excursion
  20102. (goto-char beg)
  20103. (let ((cuts (list beg)))
  20104. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  20105. (when (eq 'line-break
  20106. (org-element-type
  20107. (save-excursion (backward-char)
  20108. (org-element-context))))
  20109. (push (point) cuts)))
  20110. (dolist (c (delq end cuts))
  20111. (fill-region-as-paragraph c end justify)
  20112. (setq end c))))
  20113. t)))
  20114. ;; Contents of `comment-block' type elements should be
  20115. ;; filled as plain text, but only if point is within block
  20116. ;; markers.
  20117. (comment-block
  20118. (let* ((case-fold-search t)
  20119. (beg (save-excursion
  20120. (goto-char (org-element-property :begin element))
  20121. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  20122. (forward-line)
  20123. (point)))
  20124. (end (save-excursion
  20125. (goto-char (org-element-property :end element))
  20126. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  20127. (line-beginning-position))))
  20128. (if (or (< (point) beg) (> (point) end)) t
  20129. (fill-region-as-paragraph
  20130. (save-excursion (end-of-line)
  20131. (re-search-backward "^[ \t]*$" beg 'move)
  20132. (line-beginning-position))
  20133. (save-excursion (beginning-of-line)
  20134. (re-search-forward "^[ \t]*$" end 'move)
  20135. (line-beginning-position))
  20136. justify))))
  20137. ;; Fill comments.
  20138. (comment
  20139. (let ((begin (org-element-property :post-affiliated element))
  20140. (end (org-element-property :end element)))
  20141. (when (and (>= (point) begin) (<= (point) end))
  20142. (let ((begin (save-excursion
  20143. (end-of-line)
  20144. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  20145. (progn (forward-line) (point))
  20146. begin)))
  20147. (end (save-excursion
  20148. (end-of-line)
  20149. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  20150. (1- (line-beginning-position))
  20151. (skip-chars-backward " \r\t\n")
  20152. (line-end-position)))))
  20153. ;; Do not fill comments when at a blank line.
  20154. (when (> end begin)
  20155. (let ((fill-prefix
  20156. (save-excursion
  20157. (beginning-of-line)
  20158. (looking-at "[ \t]*#")
  20159. (let ((comment-prefix (match-string 0)))
  20160. (goto-char (match-end 0))
  20161. (if (looking-at adaptive-fill-regexp)
  20162. (concat comment-prefix (match-string 0))
  20163. (concat comment-prefix " "))))))
  20164. (save-excursion
  20165. (fill-region-as-paragraph begin end justify))))))
  20166. t))
  20167. ;; Ignore every other element.
  20168. (otherwise t)))))
  20169. (defun org-fill-paragraph (&optional justify region)
  20170. "Fill element at point, when applicable.
  20171. This function only applies to comment blocks, comments, example
  20172. blocks and paragraphs. Also, as a special case, re-align table
  20173. when point is at one.
  20174. For convenience, when point is at a plain list, an item or
  20175. a footnote definition, try to fill the first paragraph within.
  20176. If JUSTIFY is non-nil (interactively, with prefix argument),
  20177. justify as well. If `sentence-end-double-space' is non-nil, then
  20178. period followed by one space does not end a sentence, so don't
  20179. break a line there. The variable `fill-column' controls the
  20180. width for filling.
  20181. The REGION argument is non-nil if called interactively; in that
  20182. case, if Transient Mark mode is enabled and the mark is active,
  20183. fill each of the elements in the active region, instead of just
  20184. filling the current element."
  20185. (interactive (progn
  20186. (barf-if-buffer-read-only)
  20187. (list (if current-prefix-arg 'full) t)))
  20188. (cond
  20189. ((and region transient-mark-mode mark-active
  20190. (not (eq (region-beginning) (region-end))))
  20191. (let ((origin (point-marker))
  20192. (start (region-beginning)))
  20193. (unwind-protect
  20194. (progn
  20195. (goto-char (region-end))
  20196. (while (> (point) start)
  20197. (org-backward-paragraph)
  20198. (org-fill-element justify)))
  20199. (goto-char origin)
  20200. (set-marker origin nil))))
  20201. (t (org-fill-element justify))))
  20202. (defun org-auto-fill-function ()
  20203. "Auto-fill function."
  20204. ;; Check if auto-filling is meaningful.
  20205. (let ((fc (current-fill-column)))
  20206. (when (and fc (> (current-column) fc))
  20207. (let* ((fill-prefix (org-adaptive-fill-function))
  20208. ;; Enforce empty fill prefix, if required. Otherwise, it
  20209. ;; will be computed again.
  20210. (adaptive-fill-mode (not (equal fill-prefix ""))))
  20211. (when fill-prefix (do-auto-fill))))))
  20212. (defun org-comment-line-break-function (&optional soft)
  20213. "Break line at point and indent, continuing comment if within one.
  20214. The inserted newline is marked hard if variable
  20215. `use-hard-newlines' is true, unless optional argument SOFT is
  20216. non-nil."
  20217. (if soft (insert-and-inherit ?\n) (newline 1))
  20218. (save-excursion (forward-char -1) (delete-horizontal-space))
  20219. (delete-horizontal-space)
  20220. (indent-to-left-margin)
  20221. (insert-before-markers-and-inherit fill-prefix))
  20222. ;;; Fixed Width Areas
  20223. (defun org-toggle-fixed-width ()
  20224. "Toggle fixed-width markup.
  20225. Add or remove fixed-width markup on current line, whenever it
  20226. makes sense. Return an error otherwise.
  20227. If a region is active and if it contains only fixed-width areas
  20228. or blank lines, remove all fixed-width markup in it. If the
  20229. region contains anything else, convert all non-fixed-width lines
  20230. to fixed-width ones.
  20231. Blank lines at the end of the region are ignored unless the
  20232. region only contains such lines."
  20233. (interactive)
  20234. (if (not (org-region-active-p))
  20235. ;; No region:
  20236. ;;
  20237. ;; Remove fixed width marker only in a fixed-with element.
  20238. ;;
  20239. ;; Add fixed width maker in paragraphs, in blank lines after
  20240. ;; elements or at the beginning of a headline or an inlinetask,
  20241. ;; and before any one-line elements (e.g., a clock).
  20242. (progn
  20243. (beginning-of-line)
  20244. (let* ((element (org-element-at-point))
  20245. (type (org-element-type element)))
  20246. (cond
  20247. ((and (eq type 'fixed-width)
  20248. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  20249. (replace-match
  20250. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  20251. ((and (memq type '(babel-call clock comment diary-sexp headline
  20252. horizontal-rule keyword paragraph
  20253. planning))
  20254. (<= (org-element-property :post-affiliated element) (point)))
  20255. (skip-chars-forward " \t")
  20256. (insert ": "))
  20257. ((and (looking-at-p "[ \t]*$")
  20258. (or (eq type 'inlinetask)
  20259. (save-excursion
  20260. (skip-chars-forward " \r\t\n")
  20261. (<= (org-element-property :end element) (point)))))
  20262. (delete-region (point) (line-end-position))
  20263. (org-indent-line)
  20264. (insert ": "))
  20265. (t (user-error "Cannot insert a fixed-width line here")))))
  20266. ;; Region active.
  20267. (let* ((begin (save-excursion
  20268. (goto-char (region-beginning))
  20269. (line-beginning-position)))
  20270. (end (copy-marker
  20271. (save-excursion
  20272. (goto-char (region-end))
  20273. (unless (eolp) (beginning-of-line))
  20274. (if (save-excursion (re-search-backward "\\S-" begin t))
  20275. (progn (skip-chars-backward " \r\t\n") (point))
  20276. (point)))))
  20277. (all-fixed-width-p
  20278. (catch 'not-all-p
  20279. (save-excursion
  20280. (goto-char begin)
  20281. (skip-chars-forward " \r\t\n")
  20282. (when (eobp) (throw 'not-all-p nil))
  20283. (while (< (point) end)
  20284. (let ((element (org-element-at-point)))
  20285. (if (eq (org-element-type element) 'fixed-width)
  20286. (goto-char (org-element-property :end element))
  20287. (throw 'not-all-p nil))))
  20288. t))))
  20289. (if all-fixed-width-p
  20290. (save-excursion
  20291. (goto-char begin)
  20292. (while (< (point) end)
  20293. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  20294. (replace-match
  20295. "" nil nil nil
  20296. (if (= (line-end-position) (match-end 0)) 0 1)))
  20297. (forward-line)))
  20298. (let ((min-ind (point-max)))
  20299. ;; Find minimum indentation across all lines.
  20300. (save-excursion
  20301. (goto-char begin)
  20302. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  20303. (setq min-ind 0)
  20304. (catch 'zerop
  20305. (while (< (point) end)
  20306. (unless (looking-at-p "[ \t]*$")
  20307. (let ((ind (org-get-indentation)))
  20308. (setq min-ind (min min-ind ind))
  20309. (when (zerop ind) (throw 'zerop t))))
  20310. (forward-line)))))
  20311. ;; Loop over all lines and add fixed-width markup everywhere
  20312. ;; but in fixed-width lines.
  20313. (save-excursion
  20314. (goto-char begin)
  20315. (while (< (point) end)
  20316. (cond
  20317. ((org-at-heading-p)
  20318. (insert ": ")
  20319. (forward-line)
  20320. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  20321. (insert ":")
  20322. (forward-line)))
  20323. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  20324. (let* ((element (org-element-at-point))
  20325. (element-end (org-element-property :end element)))
  20326. (if (eq (org-element-type element) 'fixed-width)
  20327. (progn (goto-char element-end)
  20328. (skip-chars-backward " \r\t\n")
  20329. (forward-line))
  20330. (let ((limit (min end element-end)))
  20331. (while (< (point) limit)
  20332. (org-move-to-column min-ind t)
  20333. (insert ": ")
  20334. (forward-line))))))
  20335. (t
  20336. (org-move-to-column min-ind t)
  20337. (insert ": ")
  20338. (forward-line)))))))
  20339. (set-marker end nil))))
  20340. ;;; Blocks
  20341. (defun org-block-map (function &optional start end)
  20342. "Call FUNCTION at the head of all source blocks in the current buffer.
  20343. Optional arguments START and END can be used to limit the range."
  20344. (let ((start (or start (point-min)))
  20345. (end (or end (point-max))))
  20346. (save-excursion
  20347. (goto-char start)
  20348. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  20349. (save-excursion
  20350. (save-match-data
  20351. (goto-char (match-beginning 0))
  20352. (funcall function)))))))
  20353. (defun org-next-block (arg &optional backward block-regexp)
  20354. "Jump to the next block.
  20355. With a prefix argument ARG, jump forward ARG many blocks.
  20356. When BACKWARD is non-nil, jump to the previous block.
  20357. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  20358. Match data is set according to this regexp when the function
  20359. returns.
  20360. Return point at beginning of the opening line of found block.
  20361. Throw an error if no block is found."
  20362. (interactive "p")
  20363. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  20364. (case-fold-search t)
  20365. (search-fn (if backward #'re-search-backward #'re-search-forward))
  20366. (count (or arg 1))
  20367. (origin (point))
  20368. last-element)
  20369. (if backward (beginning-of-line) (end-of-line))
  20370. (while (and (> count 0) (funcall search-fn re nil t))
  20371. (let ((element (save-excursion
  20372. (goto-char (match-beginning 0))
  20373. (save-match-data (org-element-at-point)))))
  20374. (when (and (memq (org-element-type element)
  20375. '(center-block comment-block dynamic-block
  20376. example-block export-block quote-block
  20377. special-block src-block verse-block))
  20378. (<= (match-beginning 0)
  20379. (org-element-property :post-affiliated element)))
  20380. (setq last-element element)
  20381. (cl-decf count))))
  20382. (if (= count 0)
  20383. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  20384. (save-match-data (org-show-context)))
  20385. (goto-char origin)
  20386. (user-error "No %s code blocks" (if backward "previous" "further")))))
  20387. (defun org-previous-block (arg &optional block-regexp)
  20388. "Jump to the previous block.
  20389. With a prefix argument ARG, jump backward ARG many source blocks.
  20390. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  20391. (interactive "p")
  20392. (org-next-block arg t block-regexp))
  20393. ;;; Comments
  20394. ;; Org comments syntax is quite complex. It requires the entire line
  20395. ;; to be just a comment. Also, even with the right syntax at the
  20396. ;; beginning of line, some elements (e.g., verse-block or
  20397. ;; example-block) don't accept comments. Usual Emacs comment commands
  20398. ;; cannot cope with those requirements. Therefore, Org replaces them.
  20399. ;; Org still relies on `comment-dwim', but cannot trust
  20400. ;; `comment-only-p'. So, `comment-region-function' and
  20401. ;; `uncomment-region-function' both point
  20402. ;; to`org-comment-or-uncomment-region'. Eventually,
  20403. ;; `org-insert-comment' takes care of insertion of comments at the
  20404. ;; beginning of line.
  20405. ;; `org-setup-comments-handling' install comments related variables
  20406. ;; during `org-mode' initialization.
  20407. (defun org-setup-comments-handling ()
  20408. (interactive)
  20409. (setq-local comment-use-syntax nil)
  20410. (setq-local comment-start "# ")
  20411. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  20412. (setq-local comment-insert-comment-function 'org-insert-comment)
  20413. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  20414. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  20415. (defun org-insert-comment ()
  20416. "Insert an empty comment above current line.
  20417. If the line is empty, insert comment at its beginning. When
  20418. point is within a source block, comment according to the related
  20419. major mode."
  20420. (if (let ((element (org-element-at-point)))
  20421. (and (eq (org-element-type element) 'src-block)
  20422. (< (save-excursion
  20423. (goto-char (org-element-property :post-affiliated element))
  20424. (line-end-position))
  20425. (point))
  20426. (> (save-excursion
  20427. (goto-char (org-element-property :end element))
  20428. (skip-chars-backward " \r\t\n")
  20429. (line-beginning-position))
  20430. (point))))
  20431. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  20432. (beginning-of-line)
  20433. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  20434. (open-line 1))
  20435. (org-indent-line)
  20436. (insert "# ")))
  20437. (defvar comment-empty-lines) ; From newcomment.el.
  20438. (defun org-comment-or-uncomment-region (beg end &rest _)
  20439. "Comment or uncomment each non-blank line in the region.
  20440. Uncomment each non-blank line between BEG and END if it only
  20441. contains commented lines. Otherwise, comment them. If region is
  20442. strictly within a source block, use appropriate comment syntax."
  20443. (if (let ((element (org-element-at-point)))
  20444. (and (eq (org-element-type element) 'src-block)
  20445. (< (save-excursion
  20446. (goto-char (org-element-property :post-affiliated element))
  20447. (line-end-position))
  20448. beg)
  20449. (>= (save-excursion
  20450. (goto-char (org-element-property :end element))
  20451. (skip-chars-backward " \r\t\n")
  20452. (line-beginning-position))
  20453. end)))
  20454. ;; Translate region boundaries for the Org buffer to the source
  20455. ;; buffer.
  20456. (let ((offset (- end beg)))
  20457. (save-excursion
  20458. (goto-char beg)
  20459. (org-babel-do-in-edit-buffer
  20460. (comment-or-uncomment-region (point) (+ offset (point))))))
  20461. (save-restriction
  20462. ;; Restrict region
  20463. (narrow-to-region (save-excursion (goto-char beg)
  20464. (skip-chars-forward " \r\t\n" end)
  20465. (line-beginning-position))
  20466. (save-excursion (goto-char end)
  20467. (skip-chars-backward " \r\t\n" beg)
  20468. (line-end-position)))
  20469. (let ((uncommentp
  20470. ;; UNCOMMENTP is non-nil when every non blank line between
  20471. ;; BEG and END is a comment.
  20472. (save-excursion
  20473. (goto-char (point-min))
  20474. (while (and (not (eobp))
  20475. (let ((element (org-element-at-point)))
  20476. (and (eq (org-element-type element) 'comment)
  20477. (goto-char (min (point-max)
  20478. (org-element-property
  20479. :end element)))))))
  20480. (eobp))))
  20481. (if uncommentp
  20482. ;; Only blank lines and comments in region: uncomment it.
  20483. (save-excursion
  20484. (goto-char (point-min))
  20485. (while (not (eobp))
  20486. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  20487. (replace-match "" nil nil nil 1))
  20488. (forward-line)))
  20489. ;; Comment each line in region.
  20490. (let ((min-indent (point-max)))
  20491. ;; First find the minimum indentation across all lines.
  20492. (save-excursion
  20493. (goto-char (point-min))
  20494. (while (and (not (eobp)) (not (zerop min-indent)))
  20495. (unless (looking-at "[ \t]*$")
  20496. (setq min-indent (min min-indent (current-indentation))))
  20497. (forward-line)))
  20498. ;; Then loop over all lines.
  20499. (save-excursion
  20500. (goto-char (point-min))
  20501. (while (not (eobp))
  20502. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  20503. ;; Don't get fooled by invisible text (e.g. link path)
  20504. ;; when moving to column MIN-INDENT.
  20505. (let ((buffer-invisibility-spec nil))
  20506. (org-move-to-column min-indent t))
  20507. (insert comment-start))
  20508. (forward-line)))))))))
  20509. (defun org-comment-dwim (_arg)
  20510. "Call the comment command you mean.
  20511. Call `org-toggle-comment' if on a heading, otherwise call
  20512. `comment-dwim', within a source edit buffer if needed."
  20513. (interactive "*P")
  20514. (cond ((org-at-heading-p)
  20515. (call-interactively #'org-toggle-comment))
  20516. ((org-in-src-block-p)
  20517. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  20518. (t (call-interactively #'comment-dwim))))
  20519. ;;; Timestamps API
  20520. ;; This section contains tools to operate on, or create, timestamp
  20521. ;; objects, as returned by, e.g. `org-element-context'.
  20522. (defun org-timestamp-from-string (s)
  20523. "Convert Org timestamp S, as a string, into a timestamp object.
  20524. Return nil if S is not a valid timestamp string."
  20525. (when (org-string-nw-p s)
  20526. (with-temp-buffer
  20527. (save-excursion (insert s))
  20528. (org-element-timestamp-parser))))
  20529. (defun org-timestamp-from-time (time &optional with-time inactive)
  20530. "Convert a time value into a timestamp object.
  20531. TIME is an Emacs internal time representation, as returned, e.g.,
  20532. by `current-time'.
  20533. When optional argument WITH-TIME is non-nil, return a timestamp
  20534. object with a time part, i.e., with hours and minutes.
  20535. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  20536. return an active timestamp."
  20537. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  20538. (org-element-create 'timestamp
  20539. (list :type (if inactive 'inactive 'active)
  20540. :year-start year
  20541. :month-start month
  20542. :day-start day
  20543. :hour-start (and with-time hour)
  20544. :minute-start (and with-time minute)))))
  20545. (defun org-timestamp-to-time (timestamp &optional end)
  20546. "Convert TIMESTAMP object into an Emacs internal time value.
  20547. Use end of date range or time range when END is non-nil.
  20548. Otherwise, use its start."
  20549. (apply #'encode-time
  20550. (cons 0
  20551. (mapcar
  20552. (lambda (prop) (or (org-element-property prop timestamp) 0))
  20553. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  20554. '(:minute-start :hour-start :day-start :month-start
  20555. :year-start))))))
  20556. (defun org-timestamp-has-time-p (timestamp)
  20557. "Non-nil when TIMESTAMP has a time specified."
  20558. (org-element-property :hour-start timestamp))
  20559. (defun org-timestamp-format (timestamp format &optional end utc)
  20560. "Format a TIMESTAMP object into a string.
  20561. FORMAT is a format specifier to be passed to
  20562. `format-time-string'.
  20563. When optional argument END is non-nil, use end of date-range or
  20564. time-range, if possible.
  20565. When optional argument UTC is non-nil, time is be expressed as
  20566. Universal Time."
  20567. (format-time-string format (org-timestamp-to-time timestamp end)
  20568. (and utc t)))
  20569. (defun org-timestamp-split-range (timestamp &optional end)
  20570. "Extract a TIMESTAMP object from a date or time range.
  20571. END, when non-nil, means extract the end of the range.
  20572. Otherwise, extract its start.
  20573. Return a new timestamp object."
  20574. (let ((type (org-element-property :type timestamp)))
  20575. (if (memq type '(active inactive diary)) timestamp
  20576. (let ((split-ts (org-element-copy timestamp)))
  20577. ;; Set new type.
  20578. (org-element-put-property
  20579. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  20580. ;; Copy start properties over end properties if END is
  20581. ;; non-nil. Otherwise, copy end properties over `start' ones.
  20582. (let ((p-alist '((:minute-start . :minute-end)
  20583. (:hour-start . :hour-end)
  20584. (:day-start . :day-end)
  20585. (:month-start . :month-end)
  20586. (:year-start . :year-end))))
  20587. (dolist (p-cell p-alist)
  20588. (org-element-put-property
  20589. split-ts
  20590. (funcall (if end #'car #'cdr) p-cell)
  20591. (org-element-property
  20592. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  20593. ;; Eventually refresh `:raw-value'.
  20594. (org-element-put-property split-ts :raw-value nil)
  20595. (org-element-put-property
  20596. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  20597. (defun org-timestamp-translate (timestamp &optional boundary)
  20598. "Translate TIMESTAMP object to custom format.
  20599. Format string is defined in `org-time-stamp-custom-formats',
  20600. which see.
  20601. When optional argument BOUNDARY is non-nil, it is either the
  20602. symbol `start' or `end'. In this case, only translate the
  20603. starting or ending part of TIMESTAMP if it is a date or time
  20604. range. Otherwise, translate both parts.
  20605. Return timestamp as-is if `org-display-custom-times' is nil or if
  20606. it has a `diary' type."
  20607. (let ((type (org-element-property :type timestamp)))
  20608. (if (or (not org-display-custom-times) (eq type 'diary))
  20609. (org-element-interpret-data timestamp)
  20610. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  20611. org-time-stamp-custom-formats)))
  20612. (if (and (not boundary) (memq type '(active-range inactive-range)))
  20613. (concat (org-timestamp-format timestamp fmt)
  20614. "--"
  20615. (org-timestamp-format timestamp fmt t))
  20616. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  20617. ;;; Other stuff
  20618. (defvar reftex-docstruct-symbol)
  20619. (defvar org--rds)
  20620. (defun org-reftex-citation ()
  20621. "Use reftex-citation to insert a citation into the buffer.
  20622. This looks for a line like
  20623. #+BIBLIOGRAPHY: foo plain option:-d
  20624. and derives from it that foo.bib is the bibliography file relevant
  20625. for this document. It then installs the necessary environment for RefTeX
  20626. to work in this buffer and calls `reftex-citation' to insert a citation
  20627. into the buffer.
  20628. Export of such citations to both LaTeX and HTML is handled by the contributed
  20629. package ox-bibtex by Taru Karttunen."
  20630. (interactive)
  20631. (let ((reftex-docstruct-symbol 'org--rds)
  20632. org--rds bib)
  20633. (org-with-wide-buffer
  20634. (let ((case-fold-search t)
  20635. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  20636. (if (not (save-excursion
  20637. (or (re-search-forward re nil t)
  20638. (re-search-backward re nil t))))
  20639. (user-error "No bibliography defined in file")
  20640. (setq bib (concat (match-string 1) ".bib")
  20641. org--rds (list (list 'bib bib))))))
  20642. (call-interactively 'reftex-citation)))
  20643. ;;;; Functions extending outline functionality
  20644. (defun org-beginning-of-line (&optional n)
  20645. "Go to the beginning of the current visible line.
  20646. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  20647. symbol `reversed', on the first attempt move to where the
  20648. headline text starts, and only move to beginning of line when the
  20649. cursor is already before the start of the text of the headline.
  20650. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  20651. start of the text on the second attempt.
  20652. With argument N not nil or 1, move forward N - 1 lines first."
  20653. (interactive "^p")
  20654. (let ((origin (point))
  20655. (special (pcase org-special-ctrl-a/e
  20656. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  20657. deactivate-mark)
  20658. ;; First move to a visible line.
  20659. (if (bound-and-true-p visual-line-mode)
  20660. (beginning-of-visual-line n)
  20661. (move-beginning-of-line n)
  20662. ;; `move-beginning-of-line' may leave point after invisible
  20663. ;; characters if line starts with such of these (e.g., with
  20664. ;; a link at column 0). Really move to the beginning of the
  20665. ;; current visible line.
  20666. (beginning-of-line))
  20667. (cond
  20668. ;; No special behavior. Point is already at the beginning of
  20669. ;; a line, logical or visual.
  20670. ((not special))
  20671. ;; `beginning-of-visual-line' left point before logical beginning
  20672. ;; of line: point is at the beginning of a visual line. Bail
  20673. ;; out.
  20674. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  20675. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  20676. ;; At a headline, special position is before the title, but
  20677. ;; after any TODO keyword or priority cookie.
  20678. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  20679. (line-end-position)))
  20680. (bol (point)))
  20681. (if (eq special 'reversed)
  20682. (when (and (= origin bol) (eq last-command this-command))
  20683. (goto-char refpos))
  20684. (when (or (> origin refpos) (= origin bol))
  20685. (goto-char refpos)))))
  20686. ((and (looking-at org-list-full-item-re)
  20687. (memq (org-element-type (save-match-data (org-element-at-point)))
  20688. '(item plain-list)))
  20689. ;; Set special position at first white space character after
  20690. ;; bullet, and check-box, if any.
  20691. (let ((after-bullet
  20692. (let ((box (match-end 3)))
  20693. (cond ((not box) (match-end 1))
  20694. ((eq (char-after box) ?\s) (1+ box))
  20695. (t box)))))
  20696. (if (eq special 'reversed)
  20697. (when (and (= (point) origin) (eq last-command this-command))
  20698. (goto-char after-bullet))
  20699. (when (or (> origin after-bullet) (= (point) origin))
  20700. (goto-char after-bullet)))))
  20701. ;; No special context. Point is already at beginning of line.
  20702. (t nil))))
  20703. (defun org-end-of-line (&optional n)
  20704. "Go to the end of the line, but before ellipsis, if any.
  20705. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  20706. symbol `reversed', ignore tags on the first attempt, and only
  20707. move to after the tags when the cursor is already beyond the end
  20708. of the headline.
  20709. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  20710. on the second attempt.
  20711. With argument N not nil or 1, move forward N - 1 lines first."
  20712. (interactive "^p")
  20713. (let ((origin (point))
  20714. (special (pcase org-special-ctrl-a/e
  20715. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  20716. deactivate-mark)
  20717. ;; First move to a visible line.
  20718. (if (bound-and-true-p visual-line-mode)
  20719. (beginning-of-visual-line n)
  20720. (move-beginning-of-line n))
  20721. (cond
  20722. ;; At a headline, with tags.
  20723. ((and special
  20724. (save-excursion
  20725. (beginning-of-line)
  20726. (let ((case-fold-search nil))
  20727. (looking-at org-complex-heading-regexp)))
  20728. (match-end 5))
  20729. (let ((tags (save-excursion
  20730. (goto-char (match-beginning 5))
  20731. (skip-chars-backward " \t")
  20732. (point)))
  20733. (visual-end (and (bound-and-true-p visual-line-mode)
  20734. (save-excursion
  20735. (end-of-visual-line)
  20736. (point)))))
  20737. ;; If `end-of-visual-line' brings us before end of line or
  20738. ;; even tags, i.e., the headline spans over multiple visual
  20739. ;; lines, move there.
  20740. (cond ((and visual-end
  20741. (< visual-end tags)
  20742. (<= origin visual-end))
  20743. (goto-char visual-end))
  20744. ((eq special 'reversed)
  20745. (if (and (= origin (line-end-position))
  20746. (eq this-command last-command))
  20747. (goto-char tags)
  20748. (end-of-line)))
  20749. (t
  20750. (if (or (< origin tags) (= origin (line-end-position)))
  20751. (goto-char tags)
  20752. (end-of-line))))))
  20753. ((bound-and-true-p visual-line-mode)
  20754. (let ((bol (line-beginning-position)))
  20755. (end-of-visual-line)
  20756. ;; If `end-of-visual-line' gets us past the ellipsis at the
  20757. ;; end of a line, backtrack and use `end-of-line' instead.
  20758. (when (/= bol (line-beginning-position))
  20759. (goto-char bol)
  20760. (end-of-line))))
  20761. (t (end-of-line)))))
  20762. (defun org-backward-sentence (&optional _arg)
  20763. "Go to beginning of sentence, or beginning of table field.
  20764. This will call `backward-sentence' or `org-table-beginning-of-field',
  20765. depending on context."
  20766. (interactive)
  20767. (let* ((element (org-element-at-point))
  20768. (contents-begin (org-element-property :contents-begin element))
  20769. (table (org-element-lineage element '(table) t)))
  20770. (if (and table
  20771. (> (point) contents-begin)
  20772. (<= (point) (org-element-property :contents-end table)))
  20773. (call-interactively #'org-table-beginning-of-field)
  20774. (save-restriction
  20775. (when (and contents-begin
  20776. (< (point-min) contents-begin)
  20777. (> (point) contents-begin))
  20778. (narrow-to-region contents-begin
  20779. (org-element-property :contents-end element)))
  20780. (call-interactively #'backward-sentence)))))
  20781. (defun org-forward-sentence (&optional _arg)
  20782. "Go to end of sentence, or end of table field.
  20783. This will call `forward-sentence' or `org-table-end-of-field',
  20784. depending on context."
  20785. (interactive)
  20786. (if (and (org-at-heading-p)
  20787. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  20788. (save-restriction
  20789. (narrow-to-region (line-beginning-position) (line-end-position))
  20790. (call-interactively #'forward-sentence))
  20791. (let* ((element (org-element-at-point))
  20792. (contents-end (org-element-property :contents-end element))
  20793. (table (org-element-lineage element '(table) t)))
  20794. (if (and table
  20795. (>= (point) (org-element-property :contents-begin table))
  20796. (< (point) contents-end))
  20797. (call-interactively #'org-table-end-of-field)
  20798. (save-restriction
  20799. (when (and contents-end
  20800. (> (point-max) contents-end)
  20801. ;; Skip blank lines between elements.
  20802. (< (org-element-property :end element)
  20803. (save-excursion (goto-char contents-end)
  20804. (skip-chars-forward " \r\t\n"))))
  20805. (narrow-to-region (org-element-property :contents-begin element)
  20806. contents-end))
  20807. ;; End of heading is considered as the end of a sentence.
  20808. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  20809. (call-interactively #'forward-sentence)))))))
  20810. (defun org-kill-line (&optional _arg)
  20811. "Kill line, to tags or end of line."
  20812. (interactive)
  20813. (cond
  20814. ((or (not org-special-ctrl-k)
  20815. (bolp)
  20816. (not (org-at-heading-p)))
  20817. (when (and (get-char-property (line-end-position) 'invisible)
  20818. org-ctrl-k-protect-subtree
  20819. (or (eq org-ctrl-k-protect-subtree 'error)
  20820. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  20821. (user-error
  20822. (substitute-command-keys
  20823. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  20824. (call-interactively
  20825. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  20826. ((looking-at org-tag-line-re)
  20827. (let ((end (save-excursion
  20828. (goto-char (match-beginning 1))
  20829. (skip-chars-backward " \t"))))
  20830. (if (<= end (point)) ;on tags part
  20831. (kill-region (point) (line-end-position))
  20832. (kill-region (point) end)))
  20833. (org-align-tags))
  20834. (t (kill-region (point) (line-end-position)))))
  20835. (defun org-yank (&optional arg)
  20836. "Yank. If the kill is a subtree, treat it specially.
  20837. This command will look at the current kill and check if is a single
  20838. subtree, or a series of subtrees[1]. If it passes the test, and if the
  20839. cursor is at the beginning of a line or after the stars of a currently
  20840. empty headline, then the yank is handled specially. How exactly depends
  20841. on the value of the following variables.
  20842. `org-yank-folded-subtrees'
  20843. By default, this variable is non-nil, which results in
  20844. subtree(s) being folded after insertion, except if doing so
  20845. would swallow text after the yanked text.
  20846. `org-yank-adjusted-subtrees'
  20847. When non-nil (the default value is nil), the subtree will be
  20848. promoted or demoted in order to fit into the local outline tree
  20849. structure, which means that the level will be adjusted so that it
  20850. becomes the smaller one of the two *visible* surrounding headings.
  20851. Any prefix to this command will cause `yank' to be called directly with
  20852. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  20853. will just
  20854. plainly yank the text as it is.
  20855. \[1] The test checks if the first non-white line is a heading
  20856. and if there are no other headings with fewer stars."
  20857. (interactive "P")
  20858. (org-yank-generic 'yank arg))
  20859. (defun org-yank-generic (command arg)
  20860. "Perform some yank-like command.
  20861. This function implements the behavior described in the `org-yank'
  20862. documentation. However, it has been generalized to work for any
  20863. interactive command with similar behavior."
  20864. ;; pretend to be command COMMAND
  20865. (setq this-command command)
  20866. (if arg
  20867. (call-interactively command)
  20868. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  20869. (and (org-kill-is-subtree-p)
  20870. (or (bolp)
  20871. (and (looking-at "[ \t]*$")
  20872. (string-match
  20873. "\\`\\*+\\'"
  20874. (buffer-substring (point-at-bol) (point)))))))
  20875. swallowp)
  20876. (cond
  20877. ((and subtreep org-yank-folded-subtrees)
  20878. (let ((beg (point))
  20879. end)
  20880. (if (and subtreep org-yank-adjusted-subtrees)
  20881. (org-paste-subtree nil nil 'for-yank)
  20882. (call-interactively command))
  20883. (setq end (point))
  20884. (goto-char beg)
  20885. (when (and (bolp) subtreep
  20886. (not (setq swallowp
  20887. (org-yank-folding-would-swallow-text beg end))))
  20888. (org-with-limited-levels
  20889. (or (looking-at org-outline-regexp)
  20890. (re-search-forward org-outline-regexp-bol end t))
  20891. (while (and (< (point) end) (looking-at org-outline-regexp))
  20892. (outline-hide-subtree)
  20893. (org-cycle-show-empty-lines 'folded)
  20894. (condition-case nil
  20895. (outline-forward-same-level 1)
  20896. (error (goto-char end))))))
  20897. (when swallowp
  20898. (message
  20899. "Inserted text not folded because that would swallow text"))
  20900. (goto-char end)
  20901. (skip-chars-forward " \t\n\r")
  20902. (beginning-of-line 1)
  20903. (push-mark beg 'nomsg)))
  20904. ((and subtreep org-yank-adjusted-subtrees)
  20905. (let ((beg (point-at-bol)))
  20906. (org-paste-subtree nil nil 'for-yank)
  20907. (push-mark beg 'nomsg)))
  20908. (t
  20909. (call-interactively command))))))
  20910. (defun org-yank-folding-would-swallow-text (beg end)
  20911. "Would hide-subtree at BEG swallow any text after END?"
  20912. (let (level)
  20913. (org-with-limited-levels
  20914. (save-excursion
  20915. (goto-char beg)
  20916. (when (or (looking-at org-outline-regexp)
  20917. (re-search-forward org-outline-regexp-bol end t))
  20918. (setq level (org-outline-level)))
  20919. (goto-char end)
  20920. (skip-chars-forward " \t\r\n\v\f")
  20921. (not (or (eobp)
  20922. (and (bolp) (looking-at-p org-outline-regexp)
  20923. (<= (org-outline-level) level))))))))
  20924. (defun org-back-to-heading (&optional invisible-ok)
  20925. "Call `outline-back-to-heading', but provide a better error message."
  20926. (condition-case nil
  20927. (outline-back-to-heading invisible-ok)
  20928. (error (error "Before first headline at position %d in buffer %s"
  20929. (point) (current-buffer)))))
  20930. (defun org-before-first-heading-p ()
  20931. "Before first heading?"
  20932. (save-excursion
  20933. (end-of-line)
  20934. (null (re-search-backward org-outline-regexp-bol nil t))))
  20935. (defun org-at-heading-p (&optional ignored)
  20936. (outline-on-heading-p t))
  20937. (defun org-in-commented-heading-p (&optional no-inheritance)
  20938. "Non-nil if point is under a commented heading.
  20939. This function also checks ancestors of the current headline,
  20940. unless optional argument NO-INHERITANCE is non-nil."
  20941. (cond
  20942. ((org-before-first-heading-p) nil)
  20943. ((let ((headline (nth 4 (org-heading-components))))
  20944. (and headline
  20945. (let ((case-fold-search nil))
  20946. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  20947. headline)))))
  20948. (no-inheritance nil)
  20949. (t
  20950. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  20951. (defun org-at-comment-p nil
  20952. "Is cursor in a commented line?"
  20953. (save-excursion
  20954. (save-match-data
  20955. (beginning-of-line)
  20956. (looking-at "^[ \t]*# "))))
  20957. (defun org-at-drawer-p nil
  20958. "Is cursor at a drawer keyword?"
  20959. (save-excursion
  20960. (move-beginning-of-line 1)
  20961. (looking-at org-drawer-regexp)))
  20962. (defun org-at-block-p nil
  20963. "Is cursor at a block keyword?"
  20964. (save-excursion
  20965. (move-beginning-of-line 1)
  20966. (looking-at org-block-regexp)))
  20967. (defun org-point-at-end-of-empty-headline ()
  20968. "If point is at the end of an empty headline, return t, else nil.
  20969. If the heading only contains a TODO keyword, it is still still considered
  20970. empty."
  20971. (let ((case-fold-search nil))
  20972. (and (looking-at "[ \t]*$")
  20973. org-todo-line-regexp
  20974. (save-excursion
  20975. (beginning-of-line)
  20976. (looking-at org-todo-line-regexp)
  20977. (string= (match-string 3) "")))))
  20978. (defun org-at-heading-or-item-p ()
  20979. (or (org-at-heading-p) (org-at-item-p)))
  20980. (defun org-at-target-p ()
  20981. (or (org-in-regexp org-radio-target-regexp)
  20982. (org-in-regexp org-target-regexp)))
  20983. ;; Compatibility alias with Org versions < 7.8.03
  20984. (defalias 'org-on-target-p 'org-at-target-p)
  20985. (defun org-up-heading-all (arg)
  20986. "Move to the heading line of which the present line is a subheading.
  20987. This function considers both visible and invisible heading lines.
  20988. With argument, move up ARG levels."
  20989. (outline-up-heading arg t))
  20990. (defun org-up-heading-safe ()
  20991. "Move to the heading line of which the present line is a subheading.
  20992. This version will not throw an error. It will return the level of the
  20993. headline found, or nil if no higher level is found.
  20994. Also, this function will be a lot faster than `outline-up-heading',
  20995. because it relies on stars being the outline starters. This can really
  20996. make a significant difference in outlines with very many siblings."
  20997. (when (ignore-errors (org-back-to-heading t))
  20998. (let ((level-up (1- (funcall outline-level))))
  20999. (and (> level-up 0)
  21000. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  21001. (funcall outline-level)))))
  21002. (defun org-first-sibling-p ()
  21003. "Is this heading the first child of its parents?"
  21004. (interactive)
  21005. (let ((re org-outline-regexp-bol)
  21006. level l)
  21007. (unless (org-at-heading-p t)
  21008. (user-error "Not at a heading"))
  21009. (setq level (funcall outline-level))
  21010. (save-excursion
  21011. (if (not (re-search-backward re nil t))
  21012. t
  21013. (setq l (funcall outline-level))
  21014. (< l level)))))
  21015. (defun org-goto-sibling (&optional previous)
  21016. "Goto the next sibling, even if it is invisible.
  21017. When PREVIOUS is set, go to the previous sibling instead. Returns t
  21018. when a sibling was found. When none is found, return nil and don't
  21019. move point."
  21020. (let ((fun (if previous 're-search-backward 're-search-forward))
  21021. (pos (point))
  21022. (re org-outline-regexp-bol)
  21023. level l)
  21024. (when (ignore-errors (org-back-to-heading t))
  21025. (setq level (funcall outline-level))
  21026. (catch 'exit
  21027. (or previous (forward-char 1))
  21028. (while (funcall fun re nil t)
  21029. (setq l (funcall outline-level))
  21030. (when (< l level) (goto-char pos) (throw 'exit nil))
  21031. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21032. (goto-char pos)
  21033. nil))))
  21034. (defun org-show-siblings ()
  21035. "Show all siblings of the current headline."
  21036. (save-excursion
  21037. (while (org-goto-sibling) (org-flag-heading nil)))
  21038. (save-excursion
  21039. (while (org-goto-sibling 'previous)
  21040. (org-flag-heading nil))))
  21041. (defun org-goto-first-child ()
  21042. "Goto the first child, even if it is invisible.
  21043. Return t when a child was found. Otherwise don't move point and
  21044. return nil."
  21045. (let (level (pos (point)) (re org-outline-regexp-bol))
  21046. (when (ignore-errors (org-back-to-heading t))
  21047. (setq level (outline-level))
  21048. (forward-char 1)
  21049. (if (and (re-search-forward re nil t) (> (outline-level) level))
  21050. (progn (goto-char (match-beginning 0)) t)
  21051. (goto-char pos) nil))))
  21052. (defun org-show-hidden-entry ()
  21053. "Show an entry where even the heading is hidden."
  21054. (save-excursion
  21055. (org-show-entry)))
  21056. (defun org-flag-heading (flag &optional entry)
  21057. "Flag the current heading. FLAG non-nil means make invisible.
  21058. When ENTRY is non-nil, show the entire entry."
  21059. (save-excursion
  21060. (org-back-to-heading t)
  21061. ;; Check if we should show the entire entry
  21062. (if (not entry)
  21063. (org-flag-region
  21064. (line-end-position 0) (line-end-position) flag 'outline)
  21065. (org-show-entry)
  21066. (save-excursion
  21067. (and (outline-next-heading)
  21068. (org-flag-heading nil))))))
  21069. (defun org-get-next-sibling ()
  21070. "Move to next heading of the same level, and return point.
  21071. If there is no such heading, return nil.
  21072. This is like outline-next-sibling, but invisible headings are ok."
  21073. (let ((level (funcall outline-level)))
  21074. (outline-next-heading)
  21075. (while (and (not (eobp)) (> (funcall outline-level) level))
  21076. (outline-next-heading))
  21077. (unless (or (eobp) (< (funcall outline-level) level))
  21078. (point))))
  21079. (defun org-get-last-sibling ()
  21080. "Move to previous heading of the same level, and return point.
  21081. If there is no such heading, return nil."
  21082. (let ((opoint (point))
  21083. (level (funcall outline-level)))
  21084. (outline-previous-heading)
  21085. (when (and (/= (point) opoint) (outline-on-heading-p t))
  21086. (while (and (> (funcall outline-level) level)
  21087. (not (bobp)))
  21088. (outline-previous-heading))
  21089. (unless (< (funcall outline-level) level)
  21090. (point)))))
  21091. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  21092. "Goto to the end of a subtree."
  21093. ;; This contains an exact copy of the original function, but it uses
  21094. ;; `org-back-to-heading', to make it work also in invisible
  21095. ;; trees. And is uses an invisible-ok argument.
  21096. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  21097. ;; Furthermore, when used inside Org, finding the end of a large subtree
  21098. ;; with many children and grandchildren etc, this can be much faster
  21099. ;; than the outline version.
  21100. (org-back-to-heading invisible-ok)
  21101. (let ((first t)
  21102. (level (funcall outline-level)))
  21103. (if (and (derived-mode-p 'org-mode) (< level 1000))
  21104. ;; A true heading (not a plain list item), in Org
  21105. ;; This means we can easily find the end by looking
  21106. ;; only for the right number of stars. Using a regexp to do
  21107. ;; this is so much faster than using a Lisp loop.
  21108. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  21109. (forward-char 1)
  21110. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  21111. ;; something else, do it the slow way
  21112. (while (and (not (eobp))
  21113. (or first (> (funcall outline-level) level)))
  21114. (setq first nil)
  21115. (outline-next-heading)))
  21116. (unless to-heading
  21117. (when (memq (preceding-char) '(?\n ?\^M))
  21118. ;; Go to end of line before heading
  21119. (forward-char -1)
  21120. (when (memq (preceding-char) '(?\n ?\^M))
  21121. ;; leave blank line before heading
  21122. (forward-char -1)))))
  21123. (point))
  21124. (defun org-end-of-meta-data (&optional full)
  21125. "Skip planning line and properties drawer in current entry.
  21126. When optional argument FULL is non-nil, also skip empty lines,
  21127. clocking lines and regular drawers at the beginning of the
  21128. entry."
  21129. (org-back-to-heading t)
  21130. (forward-line)
  21131. (when (looking-at-p org-planning-line-re) (forward-line))
  21132. (when (looking-at org-property-drawer-re)
  21133. (goto-char (match-end 0))
  21134. (forward-line))
  21135. (when (and full (not (org-at-heading-p)))
  21136. (catch 'exit
  21137. (let ((end (save-excursion (outline-next-heading) (point)))
  21138. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  21139. (while (not (eobp))
  21140. (cond ((looking-at-p org-drawer-regexp)
  21141. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21142. (forward-line)
  21143. (throw 'exit t)))
  21144. ((looking-at-p re) (forward-line))
  21145. (t (throw 'exit t))))))))
  21146. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  21147. "Move forward to the ARG'th subheading at same level as this one.
  21148. Stop at the first and last subheadings of a superior heading.
  21149. Normally this only looks at visible headings, but when INVISIBLE-OK is
  21150. non-nil it will also look at invisible ones."
  21151. (interactive "p")
  21152. (let ((backward? (and arg (< arg 0))))
  21153. (if (org-before-first-heading-p)
  21154. (if backward? (goto-char (point-min)) (outline-next-heading))
  21155. (org-back-to-heading invisible-ok)
  21156. (unless backward? (end-of-line)) ;do not match current headline
  21157. (let ((level (- (match-end 0) (match-beginning 0) 1))
  21158. (f (if backward? #'re-search-backward #'re-search-forward))
  21159. (count (if arg (abs arg) 1))
  21160. (result (point)))
  21161. (while (and (> count 0)
  21162. (funcall f org-outline-regexp-bol nil 'move))
  21163. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  21164. (cond ((< l level) (setq count 0))
  21165. ((and (= l level)
  21166. (or invisible-ok
  21167. (not (org-invisible-p
  21168. (line-beginning-position)))))
  21169. (cl-decf count)
  21170. (when (= l level) (setq result (point)))))))
  21171. (goto-char result))
  21172. (beginning-of-line))))
  21173. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  21174. "Move backward to the ARG'th subheading at same level as this one.
  21175. Stop at the first and last subheadings of a superior heading."
  21176. (interactive "p")
  21177. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  21178. (defun org-next-visible-heading (arg)
  21179. "Move to the next visible heading.
  21180. This function wraps `outline-next-visible-heading' with
  21181. `org-with-limited-levels' in order to skip over inline tasks and
  21182. respect customization of `org-odd-levels-only'."
  21183. (interactive "p")
  21184. (org-with-limited-levels
  21185. (outline-next-visible-heading arg)))
  21186. (defun org-previous-visible-heading (arg)
  21187. "Move to the previous visible heading.
  21188. This function wraps `outline-previous-visible-heading' with
  21189. `org-with-limited-levels' in order to skip over inline tasks and
  21190. respect customization of `org-odd-levels-only'."
  21191. (interactive "p")
  21192. (org-with-limited-levels
  21193. (outline-previous-visible-heading arg)))
  21194. (defun org-forward-paragraph ()
  21195. "Move forward to beginning of next paragraph or equivalent.
  21196. The function moves point to the beginning of the next visible
  21197. structural element, which can be a paragraph, a table, a list
  21198. item, etc. It also provides some special moves for convenience:
  21199. - On an affiliated keyword, jump to the beginning of the
  21200. relative element.
  21201. - On an item or a footnote definition, move to the second
  21202. element inside, if any.
  21203. - On a table or a property drawer, jump after it.
  21204. - On a verse or source block, stop after blank lines."
  21205. (interactive)
  21206. (unless (eobp)
  21207. (let* ((deactivate-mark nil)
  21208. (element (org-element-at-point))
  21209. (type (org-element-type element))
  21210. (post-affiliated (org-element-property :post-affiliated element))
  21211. (contents-begin (org-element-property :contents-begin element))
  21212. (contents-end (org-element-property :contents-end element))
  21213. (end (let ((end (org-element-property :end element)) (parent element))
  21214. (while (and (setq parent (org-element-property :parent parent))
  21215. (= (org-element-property :contents-end parent) end))
  21216. (setq end (org-element-property :end parent)))
  21217. end)))
  21218. (cond ((not element)
  21219. (skip-chars-forward " \r\t\n")
  21220. (or (eobp) (beginning-of-line)))
  21221. ;; On affiliated keywords, move to element's beginning.
  21222. ((< (point) post-affiliated)
  21223. (goto-char post-affiliated))
  21224. ;; At a table row, move to the end of the table. Similarly,
  21225. ;; at a node property, move to the end of the property
  21226. ;; drawer.
  21227. ((memq type '(node-property table-row))
  21228. (goto-char (org-element-property
  21229. :end (org-element-property :parent element))))
  21230. ((memq type '(property-drawer table)) (goto-char end))
  21231. ;; Consider blank lines as separators in verse and source
  21232. ;; blocks to ease editing.
  21233. ((memq type '(src-block verse-block))
  21234. (when (eq type 'src-block)
  21235. (setq contents-end
  21236. (save-excursion (goto-char end)
  21237. (skip-chars-backward " \r\t\n")
  21238. (line-beginning-position))))
  21239. (beginning-of-line)
  21240. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  21241. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  21242. (goto-char end)
  21243. (skip-chars-forward " \r\t\n")
  21244. (if (= (point) contents-end) (goto-char end)
  21245. (beginning-of-line))))
  21246. ;; With no contents, just skip element.
  21247. ((not contents-begin) (goto-char end))
  21248. ;; If contents are invisible, skip the element altogether.
  21249. ((org-invisible-p (line-end-position))
  21250. (cl-case type
  21251. (headline
  21252. (org-with-limited-levels (outline-next-visible-heading 1)))
  21253. ;; At a plain list, make sure we move to the next item
  21254. ;; instead of skipping the whole list.
  21255. (plain-list (forward-char)
  21256. (org-forward-paragraph))
  21257. (otherwise (goto-char end))))
  21258. ((>= (point) contents-end) (goto-char end))
  21259. ((>= (point) contents-begin)
  21260. ;; This can only happen on paragraphs and plain lists.
  21261. (cl-case type
  21262. (paragraph (goto-char end))
  21263. ;; At a plain list, try to move to second element in
  21264. ;; first item, if possible.
  21265. (plain-list (end-of-line)
  21266. (org-forward-paragraph))))
  21267. ;; When contents start on the middle of a line (e.g. in
  21268. ;; items and footnote definitions), try to reach first
  21269. ;; element starting after current line.
  21270. ((> (line-end-position) contents-begin)
  21271. (end-of-line)
  21272. (org-forward-paragraph))
  21273. (t (goto-char contents-begin))))))
  21274. (defun org-backward-paragraph ()
  21275. "Move backward to start of previous paragraph or equivalent.
  21276. The function moves point to the beginning of the current
  21277. structural element, which can be a paragraph, a table, a list
  21278. item, etc., or to the beginning of the previous visible one if
  21279. point is already there. It also provides some special moves for
  21280. convenience:
  21281. - On an affiliated keyword, jump to the first one.
  21282. - On a table or a property drawer, move to its beginning.
  21283. - On comment, example, export, src and verse blocks, stop
  21284. before blank lines."
  21285. (interactive)
  21286. (unless (bobp)
  21287. (let* ((deactivate-mark nil)
  21288. (element (org-element-at-point))
  21289. (type (org-element-type element))
  21290. (contents-end (org-element-property :contents-end element))
  21291. (post-affiliated (org-element-property :post-affiliated element))
  21292. (begin (org-element-property :begin element))
  21293. (special? ;blocks handled specially
  21294. (memq type '(comment-block example-block export-block src-block
  21295. verse-block)))
  21296. (contents-begin
  21297. (if special?
  21298. ;; These types have no proper contents. Fake line
  21299. ;; below the block opening line as contents beginning.
  21300. (save-excursion (goto-char begin) (line-beginning-position 2))
  21301. (org-element-property :contents-begin element))))
  21302. (cond
  21303. ((not element) (goto-char (point-min)))
  21304. ((= (point) begin)
  21305. (backward-char)
  21306. (org-backward-paragraph))
  21307. ((<= (point) post-affiliated) (goto-char begin))
  21308. ;; Special behavior: on a table or a property drawer, move to
  21309. ;; its beginning.
  21310. ((memq type '(node-property table-row))
  21311. (goto-char (org-element-property
  21312. :post-affiliated (org-element-property :parent element))))
  21313. (special?
  21314. (if (<= (point) contents-begin) (goto-char post-affiliated)
  21315. ;; Inside a verse block, see blank lines as paragraph
  21316. ;; separators.
  21317. (let ((origin (point)))
  21318. (skip-chars-backward " \r\t\n" contents-begin)
  21319. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  21320. (skip-chars-forward " \r\t\n" origin)
  21321. (if (= (point) origin) (goto-char contents-begin)
  21322. (beginning-of-line))))))
  21323. ((eq type 'paragraph) (goto-char contents-begin)
  21324. ;; When at first paragraph in an item or a footnote definition,
  21325. ;; move directly to beginning of line.
  21326. (let ((parent-contents
  21327. (org-element-property
  21328. :contents-begin (org-element-property :parent element))))
  21329. (when (and parent-contents (= parent-contents contents-begin))
  21330. (beginning-of-line))))
  21331. ;; At the end of a greater element, move to the beginning of
  21332. ;; the last element within.
  21333. ((and contents-end (>= (point) contents-end))
  21334. (goto-char (1- contents-end))
  21335. (org-backward-paragraph))
  21336. (t (goto-char (or post-affiliated begin))))
  21337. ;; Ensure we never leave point invisible.
  21338. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  21339. (defun org-forward-element ()
  21340. "Move forward by one element.
  21341. Move to the next element at the same level, when possible."
  21342. (interactive)
  21343. (cond ((eobp) (user-error "Cannot move further down"))
  21344. ((org-with-limited-levels (org-at-heading-p))
  21345. (let ((origin (point)))
  21346. (goto-char (org-end-of-subtree nil t))
  21347. (unless (org-with-limited-levels (org-at-heading-p))
  21348. (goto-char origin)
  21349. (user-error "Cannot move further down"))))
  21350. (t
  21351. (let* ((elem (org-element-at-point))
  21352. (end (org-element-property :end elem))
  21353. (parent (org-element-property :parent elem)))
  21354. (cond ((and parent (= (org-element-property :contents-end parent) end))
  21355. (goto-char (org-element-property :end parent)))
  21356. ((integer-or-marker-p end) (goto-char end))
  21357. (t (message "No element at point")))))))
  21358. (defun org-backward-element ()
  21359. "Move backward by one element.
  21360. Move to the previous element at the same level, when possible."
  21361. (interactive)
  21362. (cond ((bobp) (user-error "Cannot move further up"))
  21363. ((org-with-limited-levels (org-at-heading-p))
  21364. ;; At a headline, move to the previous one, if any, or stay
  21365. ;; here.
  21366. (let ((origin (point)))
  21367. (org-with-limited-levels (org-backward-heading-same-level 1))
  21368. ;; When current headline has no sibling above, move to its
  21369. ;; parent.
  21370. (when (= (point) origin)
  21371. (or (org-with-limited-levels (org-up-heading-safe))
  21372. (progn (goto-char origin)
  21373. (user-error "Cannot move further up"))))))
  21374. (t
  21375. (let* ((elem (org-element-at-point))
  21376. (beg (org-element-property :begin elem)))
  21377. (cond
  21378. ;; Move to beginning of current element if point isn't
  21379. ;; there already.
  21380. ((null beg) (message "No element at point"))
  21381. ((/= (point) beg) (goto-char beg))
  21382. (t (goto-char beg)
  21383. (skip-chars-backward " \r\t\n")
  21384. (unless (bobp)
  21385. (let ((prev (org-element-at-point)))
  21386. (goto-char (org-element-property :begin prev))
  21387. (while (and (setq prev (org-element-property :parent prev))
  21388. (<= (org-element-property :end prev) beg))
  21389. (goto-char (org-element-property :begin prev)))))))))))
  21390. (defun org-up-element ()
  21391. "Move to upper element."
  21392. (interactive)
  21393. (if (org-with-limited-levels (org-at-heading-p))
  21394. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  21395. (let* ((elem (org-element-at-point))
  21396. (parent (org-element-property :parent elem)))
  21397. (if parent (goto-char (org-element-property :begin parent))
  21398. (if (org-with-limited-levels (org-before-first-heading-p))
  21399. (user-error "No surrounding element")
  21400. (org-with-limited-levels (org-back-to-heading)))))))
  21401. (defun org-down-element ()
  21402. "Move to inner element."
  21403. (interactive)
  21404. (let ((element (org-element-at-point)))
  21405. (cond
  21406. ((memq (org-element-type element) '(plain-list table))
  21407. (goto-char (org-element-property :contents-begin element))
  21408. (forward-char))
  21409. ((memq (org-element-type element) org-element-greater-elements)
  21410. ;; If contents are hidden, first disclose them.
  21411. (when (org-invisible-p (line-end-position)) (org-cycle))
  21412. (goto-char (or (org-element-property :contents-begin element)
  21413. (user-error "No content for this element"))))
  21414. (t (user-error "No inner element")))))
  21415. (defun org-drag-element-backward ()
  21416. "Move backward element at point."
  21417. (interactive)
  21418. (let ((elem (or (org-element-at-point)
  21419. (user-error "No element at point"))))
  21420. (if (eq (org-element-type elem) 'headline)
  21421. ;; Preserve point when moving a whole tree, even if point was
  21422. ;; on blank lines below the headline.
  21423. (let ((offset (skip-chars-backward " \t\n")))
  21424. (unwind-protect (org-move-subtree-up)
  21425. (forward-char (- offset))))
  21426. (let ((prev-elem
  21427. (save-excursion
  21428. (goto-char (org-element-property :begin elem))
  21429. (skip-chars-backward " \r\t\n")
  21430. (unless (bobp)
  21431. (let* ((beg (org-element-property :begin elem))
  21432. (prev (org-element-at-point))
  21433. (up prev))
  21434. (while (and (setq up (org-element-property :parent up))
  21435. (<= (org-element-property :end up) beg))
  21436. (setq prev up))
  21437. prev)))))
  21438. ;; Error out if no previous element or previous element is
  21439. ;; a parent of the current one.
  21440. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  21441. (user-error "Cannot drag element backward")
  21442. (let ((pos (point)))
  21443. (org-element-swap-A-B prev-elem elem)
  21444. (goto-char (+ (org-element-property :begin prev-elem)
  21445. (- pos (org-element-property :begin elem))))))))))
  21446. (defun org-drag-element-forward ()
  21447. "Move forward element at point."
  21448. (interactive)
  21449. (let* ((pos (point))
  21450. (elem (or (org-element-at-point)
  21451. (user-error "No element at point"))))
  21452. (when (= (point-max) (org-element-property :end elem))
  21453. (user-error "Cannot drag element forward"))
  21454. (goto-char (org-element-property :end elem))
  21455. (let ((next-elem (org-element-at-point)))
  21456. (when (or (org-element-nested-p elem next-elem)
  21457. (and (eq (org-element-type next-elem) 'headline)
  21458. (not (eq (org-element-type elem) 'headline))))
  21459. (goto-char pos)
  21460. (user-error "Cannot drag element forward"))
  21461. ;; Compute new position of point: it's shifted by NEXT-ELEM
  21462. ;; body's length (without final blanks) and by the length of
  21463. ;; blanks between ELEM and NEXT-ELEM.
  21464. (let ((size-next (- (save-excursion
  21465. (goto-char (org-element-property :end next-elem))
  21466. (skip-chars-backward " \r\t\n")
  21467. (forward-line)
  21468. ;; Small correction if buffer doesn't end
  21469. ;; with a newline character.
  21470. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  21471. (org-element-property :begin next-elem)))
  21472. (size-blank (- (org-element-property :end elem)
  21473. (save-excursion
  21474. (goto-char (org-element-property :end elem))
  21475. (skip-chars-backward " \r\t\n")
  21476. (forward-line)
  21477. (point)))))
  21478. (org-element-swap-A-B elem next-elem)
  21479. (goto-char (+ pos size-next size-blank))))))
  21480. (defun org-drag-line-forward (arg)
  21481. "Drag the line at point ARG lines forward."
  21482. (interactive "p")
  21483. (dotimes (_ (abs arg))
  21484. (let ((c (current-column)))
  21485. (if (< 0 arg)
  21486. (progn
  21487. (beginning-of-line 2)
  21488. (transpose-lines 1)
  21489. (beginning-of-line 0))
  21490. (transpose-lines 1)
  21491. (beginning-of-line -1))
  21492. (org-move-to-column c))))
  21493. (defun org-drag-line-backward (arg)
  21494. "Drag the line at point ARG lines backward."
  21495. (interactive "p")
  21496. (org-drag-line-forward (- arg)))
  21497. (defun org-mark-element ()
  21498. "Put point at beginning of this element, mark at end.
  21499. Interactively, if this command is repeated or (in Transient Mark
  21500. mode) if the mark is active, it marks the next element after the
  21501. ones already marked."
  21502. (interactive)
  21503. (let (deactivate-mark)
  21504. (if (and (called-interactively-p 'any)
  21505. (or (and (eq last-command this-command) (mark t))
  21506. (and transient-mark-mode mark-active)))
  21507. (set-mark
  21508. (save-excursion
  21509. (goto-char (mark))
  21510. (goto-char (org-element-property :end (org-element-at-point)))))
  21511. (let ((element (org-element-at-point)))
  21512. (end-of-line)
  21513. (push-mark (org-element-property :end element) t t)
  21514. (goto-char (org-element-property :begin element))))))
  21515. (defun org-narrow-to-element ()
  21516. "Narrow buffer to current element."
  21517. (interactive)
  21518. (let ((elem (org-element-at-point)))
  21519. (cond
  21520. ((eq (car elem) 'headline)
  21521. (narrow-to-region
  21522. (org-element-property :begin elem)
  21523. (org-element-property :end elem)))
  21524. ((memq (car elem) org-element-greater-elements)
  21525. (narrow-to-region
  21526. (org-element-property :contents-begin elem)
  21527. (org-element-property :contents-end elem)))
  21528. (t
  21529. (narrow-to-region
  21530. (org-element-property :begin elem)
  21531. (org-element-property :end elem))))))
  21532. (defun org-transpose-element ()
  21533. "Transpose current and previous elements, keeping blank lines between.
  21534. Point is moved after both elements."
  21535. (interactive)
  21536. (org-skip-whitespace)
  21537. (let ((end (org-element-property :end (org-element-at-point))))
  21538. (org-drag-element-backward)
  21539. (goto-char end)))
  21540. (defun org-unindent-buffer ()
  21541. "Un-indent the visible part of the buffer.
  21542. Relative indentation (between items, inside blocks, etc.) isn't
  21543. modified."
  21544. (interactive)
  21545. (unless (eq major-mode 'org-mode)
  21546. (user-error "Cannot un-indent a buffer not in Org mode"))
  21547. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  21548. (unindent-tree
  21549. (lambda (contents)
  21550. (dolist (element (reverse contents))
  21551. (if (memq (org-element-type element) '(headline section))
  21552. (funcall unindent-tree (org-element-contents element))
  21553. (save-excursion
  21554. (save-restriction
  21555. (narrow-to-region
  21556. (org-element-property :begin element)
  21557. (org-element-property :end element))
  21558. (org-do-remove-indentation))))))))
  21559. (funcall unindent-tree (org-element-contents parse-tree))))
  21560. (defun org-make-options-regexp (kwds &optional extra)
  21561. "Make a regular expression for keyword lines.
  21562. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  21563. when non-nil, is a regexp matching keywords names."
  21564. (concat "^[ \t]*#\\+\\("
  21565. (regexp-opt kwds)
  21566. (and extra (concat (and kwds "\\|") extra))
  21567. "\\):[ \t]*\\(.*\\)"))
  21568. ;;; Finish up
  21569. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  21570. (lambda () (add-hook 'change-major-mode-hook
  21571. 'org-show-all 'append 'local)))
  21572. (provide 'org)
  21573. (run-hooks 'org-load-hook)
  21574. ;;; org.el ends here