org.el 910 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: http://orgmode.org
  9. ;;
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org mode develops organizational tasks around NOTES files that
  29. ;; contain information about projects as plain text. Org mode is
  30. ;; implemented on top of outline-mode, which makes it possible to keep
  31. ;; the content of large files well structured. Visibility cycling and
  32. ;; structure editing help to work with the tree. Tables are easily
  33. ;; created with a built-in table editor. Org mode supports ToDo
  34. ;; items, deadlines, time stamps, and scheduling. It dynamically
  35. ;; compiles entries into an agenda that utilizes and smoothly
  36. ;; integrates much of the Emacs calendar and diary. Plain text
  37. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  38. ;; entries, and any files related to the projects. For printing and
  39. ;; sharing of notes, an Org file can be exported as a structured ASCII
  40. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  41. ;; file. It can also serve as a publishing tool for a set of linked
  42. ;; webpages.
  43. ;;
  44. ;; Installation and Activation
  45. ;; ---------------------------
  46. ;; See the corresponding sections in the manual at
  47. ;;
  48. ;; http://orgmode.org/org.html#Installation
  49. ;;
  50. ;; Documentation
  51. ;; -------------
  52. ;; The documentation of Org mode can be found in the TeXInfo file. The
  53. ;; distribution also contains a PDF version of it. At the homepage of
  54. ;; Org mode, you can read the same text online as HTML. There is also an
  55. ;; excellent reference card made by Philip Rooke. This card can be found
  56. ;; in the doc/ directory.
  57. ;;
  58. ;; A list of recent changes can be found at
  59. ;; http://orgmode.org/Changes.html
  60. ;;
  61. ;;; Code:
  62. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  63. (defvar-local org-table-formula-constants-local nil
  64. "Local version of `org-table-formula-constants'.")
  65. ;;;; Require other packages
  66. (require 'cl-lib)
  67. (eval-when-compile (require 'gnus-sum))
  68. (require 'calendar)
  69. (require 'find-func)
  70. (require 'format-spec)
  71. (or (eq this-command 'eval-buffer)
  72. (condition-case nil
  73. (load (concat (file-name-directory load-file-name)
  74. "org-loaddefs.el")
  75. nil t t t)
  76. (error
  77. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  78. (sit-for 3)
  79. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  80. (sit-for 3))))
  81. (require 'org-macs)
  82. (require 'org-compat)
  83. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  84. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  85. ;;
  86. ;; In Org buffers, the value of `outline-regexp' is that of
  87. ;; `org-outline-regexp'. The only function still directly relying on
  88. ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
  89. ;; job when `orgstruct-mode' is active.
  90. (defvar org-outline-regexp "\\*+ "
  91. "Regexp to match Org headlines.")
  92. (defvar org-outline-regexp-bol "^\\*+ "
  93. "Regexp to match Org headlines.
  94. This is similar to `org-outline-regexp' but additionally makes
  95. sure that we are at the beginning of the line.")
  96. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  97. "Matches a headline, putting stars and text into groups.
  98. Stars are put in group 1 and the trimmed body in group 2.")
  99. (declare-function calendar-check-holidays "holidays" (date))
  100. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  101. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  102. (declare-function org-add-archive-files "org-archive" (files))
  103. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  104. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  105. (declare-function org-agenda-redo "org-agenda" (&optional all))
  106. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  107. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  108. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  109. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  110. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  111. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  112. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  113. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  114. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  115. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  116. (declare-function org-clock-update-time-maybe "org-clock" ())
  117. (declare-function org-clocking-buffer "org-clock" ())
  118. (declare-function org-clocktable-shift "org-clock" (dir n))
  119. (declare-function
  120. org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  121. (declare-function org-element-at-point "org-element" ())
  122. (declare-function org-element-cache-refresh "org-element" (pos))
  123. (declare-function org-element-cache-reset "org-element" (&optional all))
  124. (declare-function org-element-contents "org-element" (element))
  125. (declare-function org-element-context "org-element" (&optional element))
  126. (declare-function org-element-copy "org-element" (datum))
  127. (declare-function org-element-interpret-data "org-element" (data))
  128. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  129. (declare-function org-element-link-parser "org-element" ())
  130. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  131. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  132. (declare-function org-element-property "org-element" (property element))
  133. (declare-function org-element-put-property "org-element" (element property value))
  134. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  135. (declare-function org-element-type "org-element" (element))
  136. (declare-function org-element-update-syntax "org-element" ())
  137. (declare-function org-id-find-id-file "org-id" (id))
  138. (declare-function org-id-get-create "org-id" (&optional force))
  139. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  140. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  141. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  142. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  143. (declare-function org-table-align "org-table" ())
  144. (declare-function org-table-begin "org-table" (&optional table-type))
  145. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  146. (declare-function org-table-blank-field "org-table" ())
  147. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  148. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  149. (declare-function org-table-cut-region "org-table" (beg end))
  150. (declare-function org-table-edit-field "org-table" (arg))
  151. (declare-function org-table-end "org-table" (&optional table-type))
  152. (declare-function org-table-end-of-field "org-table" (&optional n))
  153. (declare-function org-table-insert-row "org-table" (&optional arg))
  154. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  155. (declare-function org-table-maybe-eval-formula "org-table" ())
  156. (declare-function org-table-maybe-recalculate-line "org-table" ())
  157. (declare-function org-table-next-row "org-table" ())
  158. (declare-function org-table-paste-rectangle "org-table" ())
  159. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  160. (declare-function
  161. org-table-sort-lines "org-table"
  162. (&optional with-case sorting-type getkey-func compare-func interactive?))
  163. (declare-function org-table-shrink "org-table" (&optional begin end))
  164. (declare-function org-table-toggle-column-width "org-table" (&optional arg))
  165. (declare-function org-table-wrap-region "org-table" (arg))
  166. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  167. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  168. (declare-function orgtbl-mode "org-table" (&optional arg))
  169. (declare-function org-export-get-backend "ox" (name))
  170. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  171. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  172. (defvar ffap-url-regexp)
  173. (defvar org-element-paragraph-separate)
  174. ;; load languages based on value of `org-babel-load-languages'
  175. (defvar org-babel-load-languages)
  176. ;;;###autoload
  177. (defun org-babel-do-load-languages (sym value)
  178. "Load the languages defined in `org-babel-load-languages'."
  179. (set-default sym value)
  180. (dolist (pair org-babel-load-languages)
  181. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  182. (if active
  183. (require (intern (concat "ob-" lang)))
  184. (funcall 'fmakunbound
  185. (intern (concat "org-babel-execute:" lang)))
  186. (funcall 'fmakunbound
  187. (intern (concat "org-babel-expand-body:" lang)))))))
  188. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  189. ;;;###autoload
  190. (defun org-babel-load-file (file &optional compile)
  191. "Load Emacs Lisp source code blocks in the Org FILE.
  192. This function exports the source code using `org-babel-tangle'
  193. and then loads the resulting file using `load-file'. With prefix
  194. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  195. file to byte-code before it is loaded."
  196. (interactive "fFile to load: \nP")
  197. (let* ((age (lambda (file)
  198. (float-time
  199. (time-subtract (current-time)
  200. (nth 5 (or (file-attributes (file-truename file))
  201. (file-attributes file)))))))
  202. (base-name (file-name-sans-extension file))
  203. (exported-file (concat base-name ".el")))
  204. ;; tangle if the Org file is newer than the elisp file
  205. (unless (and (file-exists-p exported-file)
  206. (> (funcall age file) (funcall age exported-file)))
  207. ;; Tangle-file traversal returns reversed list of tangled files
  208. ;; and we want to evaluate the first target.
  209. (setq exported-file
  210. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  211. (message "%s %s"
  212. (if compile
  213. (progn (byte-compile-file exported-file 'load)
  214. "Compiled and loaded")
  215. (progn (load-file exported-file) "Loaded"))
  216. exported-file)))
  217. (defcustom org-babel-load-languages '((emacs-lisp . t))
  218. "Languages which can be evaluated in Org buffers.
  219. This list can be used to load support for any of the languages
  220. below, note that each language will depend on a different set of
  221. system executables and/or Emacs modes. When a language is
  222. \"loaded\", then code blocks in that language can be evaluated
  223. with `org-babel-execute-src-block' bound by default to C-c
  224. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  225. be set to remove code block evaluation from the C-c C-c
  226. keybinding. By default only Emacs Lisp (which has no
  227. requirements) is loaded."
  228. :group 'org-babel
  229. :set 'org-babel-do-load-languages
  230. :version "24.1"
  231. :type '(alist :tag "Babel Languages"
  232. :key-type
  233. (choice
  234. (const :tag "Awk" awk)
  235. (const :tag "C" C)
  236. (const :tag "R" R)
  237. (const :tag "Asymptote" asymptote)
  238. (const :tag "Calc" calc)
  239. (const :tag "Clojure" clojure)
  240. (const :tag "CSS" css)
  241. (const :tag "Ditaa" ditaa)
  242. (const :tag "Dot" dot)
  243. (const :tag "Ebnf2ps" ebnf2ps)
  244. (const :tag "Emacs Lisp" emacs-lisp)
  245. (const :tag "Forth" forth)
  246. (const :tag "Fortran" fortran)
  247. (const :tag "Gnuplot" gnuplot)
  248. (const :tag "Haskell" haskell)
  249. (const :tag "hledger" hledger)
  250. (const :tag "IO" io)
  251. (const :tag "J" J)
  252. (const :tag "Java" java)
  253. (const :tag "Javascript" js)
  254. (const :tag "LaTeX" latex)
  255. (const :tag "Ledger" ledger)
  256. (const :tag "Lilypond" lilypond)
  257. (const :tag "Lisp" lisp)
  258. (const :tag "Makefile" makefile)
  259. (const :tag "Maxima" maxima)
  260. (const :tag "Matlab" matlab)
  261. (const :tag "Mscgen" mscgen)
  262. (const :tag "Ocaml" ocaml)
  263. (const :tag "Octave" octave)
  264. (const :tag "Org" org)
  265. (const :tag "Perl" perl)
  266. (const :tag "Pico Lisp" picolisp)
  267. (const :tag "PlantUML" plantuml)
  268. (const :tag "Python" python)
  269. (const :tag "Ruby" ruby)
  270. (const :tag "Sass" sass)
  271. (const :tag "Scala" scala)
  272. (const :tag "Scheme" scheme)
  273. (const :tag "Screen" screen)
  274. (const :tag "Shell Script" shell)
  275. (const :tag "Shen" shen)
  276. (const :tag "Sql" sql)
  277. (const :tag "Sqlite" sqlite)
  278. (const :tag "Stan" stan)
  279. (const :tag "Vala" vala))
  280. :value-type (boolean :tag "Activate" :value t)))
  281. ;;;; Customization variables
  282. (defcustom org-clone-delete-id nil
  283. "Remove ID property of clones of a subtree.
  284. When non-nil, clones of a subtree don't inherit the ID property.
  285. Otherwise they inherit the ID property with a new unique
  286. identifier."
  287. :type 'boolean
  288. :version "24.1"
  289. :group 'org-id)
  290. ;;; Version
  291. (org-check-version)
  292. ;;;###autoload
  293. (defun org-version (&optional here full message)
  294. "Show the Org version.
  295. Interactively, or when MESSAGE is non-nil, show it in echo area.
  296. With prefix argument, or when HERE is non-nil, insert it at point.
  297. In non-interactive uses, a reduced version string is output unless
  298. FULL is given."
  299. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  300. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  301. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  302. (load-suffixes (list ".el"))
  303. (org-install-dir
  304. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  305. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  306. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  307. (let* ((load-suffixes save-load-suffixes)
  308. (release (org-release))
  309. (git-version (org-git-version))
  310. (version (format "Org mode version %s (%s @ %s)"
  311. release
  312. git-version
  313. (if org-install-dir
  314. (if (string= org-dir org-install-dir)
  315. org-install-dir
  316. (concat "mixed installation! "
  317. org-install-dir
  318. " and "
  319. org-dir))
  320. "org-loaddefs.el can not be found!")))
  321. (version1 (if full version release)))
  322. (when here (insert version1))
  323. (when message (message "%s" version1))
  324. version1)))
  325. (defconst org-version (org-version))
  326. ;;; Syntax Constants
  327. ;;;; Block
  328. (defconst org-block-regexp
  329. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  330. "Regular expression for hiding blocks.")
  331. (defconst org-dblock-start-re
  332. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  333. "Matches the start line of a dynamic block, with parameters.")
  334. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  335. "Matches the end of a dynamic block.")
  336. ;;;; Clock and Planning
  337. (defconst org-clock-string "CLOCK:"
  338. "String used as prefix for timestamps clocking work hours on an item.")
  339. (defvar org-closed-string "CLOSED:"
  340. "String used as the prefix for timestamps logging closing a TODO entry.")
  341. (defvar org-deadline-string "DEADLINE:"
  342. "String to mark deadline entries.
  343. \\<org-mode-map>
  344. A deadline is this string, followed by a time stamp. It must be
  345. a word, terminated by a colon. You can insert a schedule keyword
  346. and a timestamp with `\\[org-deadline]'.")
  347. (defvar org-scheduled-string "SCHEDULED:"
  348. "String to mark scheduled TODO entries.
  349. \\<org-mode-map>
  350. A schedule is this string, followed by a time stamp. It must be
  351. a word, terminated by a colon. You can insert a schedule keyword
  352. and a timestamp with `\\[org-schedule]'.")
  353. (defconst org-ds-keyword-length
  354. (+ 2
  355. (apply #'max
  356. (mapcar #'length
  357. (list org-deadline-string org-scheduled-string
  358. org-clock-string org-closed-string))))
  359. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  360. (defconst org-planning-line-re
  361. (concat "^[ \t]*"
  362. (regexp-opt
  363. (list org-closed-string org-deadline-string org-scheduled-string)
  364. t))
  365. "Matches a line with planning info.
  366. Matched keyword is in group 1.")
  367. (defconst org-clock-line-re
  368. (concat "^[ \t]*" org-clock-string)
  369. "Matches a line with clock info.")
  370. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  371. "Matches the DEADLINE keyword.")
  372. (defconst org-deadline-time-regexp
  373. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  374. "Matches the DEADLINE keyword together with a time stamp.")
  375. (defconst org-deadline-time-hour-regexp
  376. (concat "\\<" org-deadline-string
  377. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  378. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  379. (defconst org-deadline-line-regexp
  380. (concat "\\<\\(" org-deadline-string "\\).*")
  381. "Matches the DEADLINE keyword and the rest of the line.")
  382. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  383. "Matches the SCHEDULED keyword.")
  384. (defconst org-scheduled-time-regexp
  385. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  386. "Matches the SCHEDULED keyword together with a time stamp.")
  387. (defconst org-scheduled-time-hour-regexp
  388. (concat "\\<" org-scheduled-string
  389. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  390. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  391. (defconst org-closed-time-regexp
  392. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  393. "Matches the CLOSED keyword together with a time stamp.")
  394. (defconst org-keyword-time-regexp
  395. (concat "\\<"
  396. (regexp-opt
  397. (list org-scheduled-string org-deadline-string org-closed-string
  398. org-clock-string)
  399. t)
  400. " *[[<]\\([^]>]+\\)[]>]")
  401. "Matches any of the 4 keywords, together with the time stamp.")
  402. (defconst org-keyword-time-not-clock-regexp
  403. (concat
  404. "\\<"
  405. (regexp-opt
  406. (list org-scheduled-string org-deadline-string org-closed-string) t)
  407. " *[[<]\\([^]>]+\\)[]>]")
  408. "Matches any of the 3 keywords, together with the time stamp.")
  409. (defconst org-maybe-keyword-time-regexp
  410. (concat "\\(\\<"
  411. (regexp-opt
  412. (list org-scheduled-string org-deadline-string org-closed-string
  413. org-clock-string)
  414. t)
  415. "\\)?"
  416. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  417. "\\|"
  418. "<%%([^\r\n>]*>\\)")
  419. "Matches a timestamp, possibly preceded by a keyword.")
  420. (defconst org-all-time-keywords
  421. (mapcar (lambda (w) (substring w 0 -1))
  422. (list org-scheduled-string org-deadline-string
  423. org-clock-string org-closed-string))
  424. "List of time keywords.")
  425. ;;;; Drawer
  426. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  427. "Matches first or last line of a hidden block.
  428. Group 1 contains drawer's name or \"END\".")
  429. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  430. "Regular expression matching the first line of a property drawer.")
  431. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  432. "Regular expression matching the last line of a property drawer.")
  433. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  434. "Regular expression matching the first line of a clock drawer.")
  435. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  436. "Regular expression matching the last line of a clock drawer.")
  437. (defconst org-property-drawer-re
  438. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  439. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  440. "[ \t]*:END:[ \t]*$")
  441. "Matches an entire property drawer.")
  442. (defconst org-clock-drawer-re
  443. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  444. org-clock-drawer-end-re "\\)\n?")
  445. "Matches an entire clock drawer.")
  446. ;;;; Headline
  447. (defconst org-heading-keyword-regexp-format
  448. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  449. "Printf format for a regexp matching a headline with some keyword.
  450. This regexp will match the headline of any node which has the
  451. exact keyword that is put into the format. The keyword isn't in
  452. any group by default, but the stars and the body are.")
  453. (defconst org-heading-keyword-maybe-regexp-format
  454. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  455. "Printf format for a regexp matching a headline, possibly with some keyword.
  456. This regexp can match any headline with the specified keyword, or
  457. without a keyword. The keyword isn't in any group by default,
  458. but the stars and the body are.")
  459. (defconst org-archive-tag "ARCHIVE"
  460. "The tag that marks a subtree as archived.
  461. An archived subtree does not open during visibility cycling, and does
  462. not contribute to the agenda listings.")
  463. (eval-and-compile
  464. (defconst org-comment-string "COMMENT"
  465. "Entries starting with this keyword will never be exported.
  466. \\<org-mode-map>
  467. An entry can be toggled between COMMENT and normal with
  468. `\\[org-toggle-comment]'."))
  469. ;;;; LaTeX Environments and Fragments
  470. (defconst org-latex-regexps
  471. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  472. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  473. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  474. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  475. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  476. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  477. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  478. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  479. "Regular expressions for matching embedded LaTeX.")
  480. ;;;; Node Property
  481. (defconst org-effort-property "Effort"
  482. "The property that is being used to keep track of effort estimates.
  483. Effort estimates given in this property need to have the format H:MM.")
  484. ;;;; Table
  485. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  486. "Detect an org-type or table-type table.")
  487. (defconst org-table-line-regexp "^[ \t]*|"
  488. "Detect an org-type table line.")
  489. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  490. "Detect an org-type table line.")
  491. (defconst org-table-hline-regexp "^[ \t]*|-"
  492. "Detect an org-type table hline.")
  493. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  494. "Detect a table-type table hline.")
  495. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  496. "Detect the first line outside a table when searching from within it.
  497. This works for both table types.")
  498. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  499. "Detect a #+TBLFM line.")
  500. ;;;; Timestamp
  501. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  502. "Regular expression for fast time stamp matching.")
  503. (defconst org-ts-regexp-inactive
  504. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  505. "Regular expression for fast inactive time stamp matching.")
  506. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  507. "Regular expression for fast time stamp matching.")
  508. (defconst org-ts-regexp0
  509. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  510. "Regular expression matching time strings for analysis.
  511. This one does not require the space after the date, so it can be used
  512. on a string that terminates immediately after the date.")
  513. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  514. "Regular expression matching time strings for analysis.")
  515. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  516. "Regular expression matching time stamps, with groups.")
  517. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  518. "Regular expression matching time stamps (also [..]), with groups.")
  519. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  520. "Regular expression matching a time stamp range.")
  521. (defconst org-tr-regexp-both
  522. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  523. "Regular expression matching a time stamp range.")
  524. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  525. org-ts-regexp "\\)?")
  526. "Regular expression matching a time stamp or time stamp range.")
  527. (defconst org-tsr-regexp-both
  528. (concat org-ts-regexp-both "\\(--?-?"
  529. org-ts-regexp-both "\\)?")
  530. "Regular expression matching a time stamp or time stamp range.
  531. The time stamps may be either active or inactive.")
  532. (defconst org-repeat-re
  533. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  534. "Regular expression for specifying repeated events.
  535. After a match, group 1 contains the repeat expression.")
  536. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  537. "Formats for `format-time-string' which are used for time stamps.")
  538. ;;; The custom variables
  539. (defgroup org nil
  540. "Outline-based notes management and organizer."
  541. :tag "Org"
  542. :group 'outlines
  543. :group 'calendar)
  544. (defcustom org-mode-hook nil
  545. "Mode hook for Org mode, run after the mode was turned on."
  546. :group 'org
  547. :type 'hook)
  548. (defcustom org-load-hook nil
  549. "Hook that is run after org.el has been loaded."
  550. :group 'org
  551. :type 'hook)
  552. (defcustom org-log-buffer-setup-hook nil
  553. "Hook that is run after an Org log buffer is created."
  554. :group 'org
  555. :version "24.1"
  556. :type 'hook)
  557. (defvar org-modules) ; defined below
  558. (defvar org-modules-loaded nil
  559. "Have the modules been loaded already?")
  560. (defun org-load-modules-maybe (&optional force)
  561. "Load all extensions listed in `org-modules'."
  562. (when (or force (not org-modules-loaded))
  563. (dolist (ext org-modules)
  564. (condition-case nil (require ext)
  565. (error (message "Problems while trying to load feature `%s'" ext))))
  566. (setq org-modules-loaded t)))
  567. (defun org-set-modules (var value)
  568. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  569. (set var value)
  570. (when (featurep 'org)
  571. (org-load-modules-maybe 'force)
  572. (org-element-cache-reset 'all)))
  573. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  574. "Modules that should always be loaded together with org.el.
  575. If a description starts with <C>, the file is not part of Emacs
  576. and loading it will require that you have downloaded and properly
  577. installed the Org mode distribution.
  578. You can also use this system to load external packages (i.e. neither Org
  579. core modules, nor modules from the CONTRIB directory). Just add symbols
  580. to the end of the list. If the package is called org-xyz.el, then you need
  581. to add the symbol `xyz', and the package must have a call to:
  582. (provide \\='org-xyz)
  583. For export specific modules, see also `org-export-backends'."
  584. :group 'org
  585. :set 'org-set-modules
  586. :version "24.4"
  587. :package-version '(Org . "8.0")
  588. :type
  589. '(set :greedy t
  590. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  591. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  592. (const :tag " crypt: Encryption of subtrees" org-crypt)
  593. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  594. (const :tag " docview: Links to doc-view buffers" org-docview)
  595. (const :tag " eww: Store link to url of eww" org-eww)
  596. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  597. (const :tag " habit: Track your consistency with habits" org-habit)
  598. (const :tag " id: Global IDs for identifying entries" org-id)
  599. (const :tag " info: Links to Info nodes" org-info)
  600. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  601. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  602. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  603. (const :tag " mouse: Additional mouse support" org-mouse)
  604. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  605. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  606. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  607. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  608. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  609. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  610. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  611. (const :tag "C collector: Collect properties into tables" org-collector)
  612. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  613. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  614. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  615. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  616. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  617. (const :tag "C eval: Include command output as text" org-eval)
  618. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  619. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  620. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  621. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  622. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  623. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  624. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  625. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  626. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  627. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  628. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  629. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  630. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  631. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  632. (const :tag "C registry: A registry for Org links" org-registry)
  633. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  634. (const :tag "C secretary: Team management with org-mode" org-secretary)
  635. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  636. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  637. (const :tag "C track: Keep up with Org mode development" org-track)
  638. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  639. (const :tag "C vm: Links to VM folders/messages" org-vm)
  640. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  641. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  642. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  643. (defvar org-export-registered-backends) ; From ox.el.
  644. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  645. (declare-function org-export-backend-name "ox" (backend) t)
  646. (defcustom org-export-backends '(ascii html icalendar latex odt)
  647. "List of export back-ends that should be always available.
  648. If a description starts with <C>, the file is not part of Emacs
  649. and loading it will require that you have downloaded and properly
  650. installed the Org mode distribution.
  651. Unlike to `org-modules', libraries in this list will not be
  652. loaded along with Org, but only once the export framework is
  653. needed.
  654. This variable needs to be set before org.el is loaded. If you
  655. need to make a change while Emacs is running, use the customize
  656. interface or run the following code, where VAL stands for the new
  657. value of the variable, after updating it:
  658. (progn
  659. (setq org-export-registered-backends
  660. (cl-remove-if-not
  661. (lambda (backend)
  662. (let ((name (org-export-backend-name backend)))
  663. (or (memq name val)
  664. (catch \\='parentp
  665. (dolist (b val)
  666. (and (org-export-derived-backend-p b name)
  667. (throw \\='parentp t)))))))
  668. org-export-registered-backends))
  669. (let ((new-list (mapcar #\\='org-export-backend-name
  670. org-export-registered-backends)))
  671. (dolist (backend val)
  672. (cond
  673. ((not (load (format \"ox-%s\" backend) t t))
  674. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  675. backend))
  676. ((not (memq backend new-list)) (push backend new-list))))
  677. (set-default \\='org-export-backends new-list)))
  678. Adding a back-end to this list will also pull the back-end it
  679. depends on, if any."
  680. :group 'org
  681. :group 'org-export
  682. :version "26.1"
  683. :package-version '(Org . "9.0")
  684. :initialize 'custom-initialize-set
  685. :set (lambda (var val)
  686. (if (not (featurep 'ox)) (set-default var val)
  687. ;; Any back-end not required anymore (not present in VAL and not
  688. ;; a parent of any back-end in the new value) is removed from the
  689. ;; list of registered back-ends.
  690. (setq org-export-registered-backends
  691. (cl-remove-if-not
  692. (lambda (backend)
  693. (let ((name (org-export-backend-name backend)))
  694. (or (memq name val)
  695. (catch 'parentp
  696. (dolist (b val)
  697. (and (org-export-derived-backend-p b name)
  698. (throw 'parentp t)))))))
  699. org-export-registered-backends))
  700. ;; Now build NEW-LIST of both new back-ends and required
  701. ;; parents.
  702. (let ((new-list (mapcar #'org-export-backend-name
  703. org-export-registered-backends)))
  704. (dolist (backend val)
  705. (cond
  706. ((not (load (format "ox-%s" backend) t t))
  707. (message "Problems while trying to load export back-end `%s'"
  708. backend))
  709. ((not (memq backend new-list)) (push backend new-list))))
  710. ;; Set VAR to that list with fixed dependencies.
  711. (set-default var new-list))))
  712. :type '(set :greedy t
  713. (const :tag " ascii Export buffer to ASCII format" ascii)
  714. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  715. (const :tag " html Export buffer to HTML format" html)
  716. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  717. (const :tag " latex Export buffer to LaTeX format" latex)
  718. (const :tag " man Export buffer to MAN format" man)
  719. (const :tag " md Export buffer to Markdown format" md)
  720. (const :tag " odt Export buffer to ODT format" odt)
  721. (const :tag " org Export buffer to Org format" org)
  722. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  723. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  724. (const :tag "C deck Export buffer to deck.js presentations" deck)
  725. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  726. (const :tag "C groff Export buffer to Groff format" groff)
  727. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  728. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  729. (const :tag "C s5 Export buffer to s5 presentations" s5)
  730. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  731. (eval-after-load 'ox
  732. '(dolist (backend org-export-backends)
  733. (condition-case nil (require (intern (format "ox-%s" backend)))
  734. (error (message "Problems while trying to load export back-end `%s'"
  735. backend)))))
  736. (defcustom org-support-shift-select nil
  737. "Non-nil means make shift-cursor commands select text when possible.
  738. \\<org-mode-map>\
  739. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  740. start selecting a region, or enlarge regions started in this way.
  741. In Org mode, in special contexts, these same keys are used for
  742. other purposes, important enough to compete with shift selection.
  743. Org tries to balance these needs by supporting `shift-select-mode'
  744. outside these special contexts, under control of this variable.
  745. The default of this variable is nil, to avoid confusing behavior. Shifted
  746. cursor keys will then execute Org commands in the following contexts:
  747. - on a headline, changing TODO state (left/right) and priority (up/down)
  748. - on a time stamp, changing the time
  749. - in a plain list item, changing the bullet type
  750. - in a property definition line, switching between allowed values
  751. - in the BEGIN line of a clock table (changing the time block).
  752. Outside these contexts, the commands will throw an error.
  753. When this variable is t and the cursor is not in a special
  754. context, Org mode will support shift-selection for making and
  755. enlarging regions. To make this more effective, the bullet
  756. cycling will no longer happen anywhere in an item line, but only
  757. if the cursor is exactly on the bullet.
  758. If you set this variable to the symbol `always', then the keys
  759. will not be special in headlines, property lines, and item lines,
  760. to make shift selection work there as well. If this is what you
  761. want, you can use the following alternative commands:
  762. `\\[org-todo]' and `\\[org-priority]' \
  763. to change TODO state and priority,
  764. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  765. can be used to switch TODO sets,
  766. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  767. and properties can be edited by hand or in column view.
  768. However, when the cursor is on a timestamp, shift-cursor commands
  769. will still edit the time stamp - this is just too good to give up."
  770. :group 'org
  771. :type '(choice
  772. (const :tag "Never" nil)
  773. (const :tag "When outside special context" t)
  774. (const :tag "Everywhere except timestamps" always)))
  775. (defcustom org-loop-over-headlines-in-active-region nil
  776. "Shall some commands act upon headlines in the active region?
  777. When set to t, some commands will be performed in all headlines
  778. within the active region.
  779. When set to `start-level', some commands will be performed in all
  780. headlines within the active region, provided that these headlines
  781. are of the same level than the first one.
  782. When set to a string, those commands will be performed on the
  783. matching headlines within the active region. Such string must be
  784. a tags/property/todo match as it is used in the agenda tags view.
  785. The list of commands is: `org-schedule', `org-deadline',
  786. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  787. `org-archive-to-archive-sibling'. The archiving commands skip
  788. already archived entries."
  789. :type '(choice (const :tag "Don't loop" nil)
  790. (const :tag "All headlines in active region" t)
  791. (const :tag "In active region, headlines at the same level than the first one" start-level)
  792. (string :tag "Tags/Property/Todo matcher"))
  793. :version "24.1"
  794. :group 'org-todo
  795. :group 'org-archive)
  796. (defcustom org-startup-folded t
  797. "Non-nil means entering Org mode will switch to OVERVIEW.
  798. This can also be configured on a per-file basis by adding one of
  799. the following lines anywhere in the buffer:
  800. #+STARTUP: fold (or `overview', this is equivalent)
  801. #+STARTUP: nofold (or `showall', this is equivalent)
  802. #+STARTUP: content
  803. #+STARTUP: showeverything
  804. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  805. to ignore this option when Org opens agenda files for the first
  806. time."
  807. :group 'org-startup
  808. :type '(choice
  809. (const :tag "nofold: show all" nil)
  810. (const :tag "fold: overview" t)
  811. (const :tag "content: all headlines" content)
  812. (const :tag "show everything, even drawers" showeverything)))
  813. (defcustom org-startup-truncated t
  814. "Non-nil means entering Org mode will set `truncate-lines'.
  815. This is useful since some lines containing links can be very long and
  816. uninteresting. Also tables look terrible when wrapped.
  817. The variable `org-startup-truncated' allows to configure
  818. truncation for Org mode different to the other modes that use the
  819. variable `truncate-lines' and as a shortcut instead of putting
  820. the variable `truncate-lines' into the `org-mode-hook'. If one
  821. wants to configure truncation for Org mode not statically but
  822. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  823. the variable `truncate-lines' has to be used because in such a
  824. case it is too late to set the variable `org-startup-truncated'."
  825. :group 'org-startup
  826. :type 'boolean)
  827. (defcustom org-startup-indented nil
  828. "Non-nil means turn on `org-indent-mode' on startup.
  829. This can also be configured on a per-file basis by adding one of
  830. the following lines anywhere in the buffer:
  831. #+STARTUP: indent
  832. #+STARTUP: noindent"
  833. :group 'org-structure
  834. :type '(choice
  835. (const :tag "Not" nil)
  836. (const :tag "Globally (slow on startup in large files)" t)))
  837. (defcustom org-use-sub-superscripts t
  838. "Non-nil means interpret \"_\" and \"^\" for display.
  839. If you want to control how Org exports those characters, see
  840. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  841. used to be an alias for `org-export-with-sub-superscripts' in
  842. Org <8.0, it is not anymore.
  843. When this option is turned on, you can use TeX-like syntax for
  844. sub- and superscripts within the buffer. Several characters after
  845. \"_\" or \"^\" will be considered as a single item - so grouping
  846. with {} is normally not needed. For example, the following things
  847. will be parsed as single sub- or superscripts:
  848. 10^24 or 10^tau several digits will be considered 1 item.
  849. 10^-12 or 10^-tau a leading sign with digits or a word
  850. x^2-y^3 will be read as x^2 - y^3, because items are
  851. terminated by almost any nonword/nondigit char.
  852. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  853. Still, ambiguity is possible. So when in doubt, use {} to enclose
  854. the sub/superscript. If you set this variable to the symbol `{}',
  855. the braces are *required* in order to trigger interpretations as
  856. sub/superscript. This can be helpful in documents that need \"_\"
  857. frequently in plain text."
  858. :group 'org-startup
  859. :version "24.4"
  860. :package-version '(Org . "8.0")
  861. :type '(choice
  862. (const :tag "Always interpret" t)
  863. (const :tag "Only with braces" {})
  864. (const :tag "Never interpret" nil)))
  865. (defcustom org-startup-with-beamer-mode nil
  866. "Non-nil means turn on `org-beamer-mode' on startup.
  867. This can also be configured on a per-file basis by adding one of
  868. the following lines anywhere in the buffer:
  869. #+STARTUP: beamer"
  870. :group 'org-startup
  871. :version "24.1"
  872. :type 'boolean)
  873. (defcustom org-startup-align-all-tables nil
  874. "Non-nil means align all tables when visiting a file.
  875. This can also be configured on a per-file basis by adding one of
  876. the following lines anywhere in the buffer:
  877. #+STARTUP: align
  878. #+STARTUP: noalign"
  879. :group 'org-startup
  880. :type 'boolean)
  881. (defcustom org-startup-shrink-all-tables nil
  882. "Non-nil means shrink all table columns with a width cookie.
  883. This can also be configured on a per-file basis by adding one of
  884. the following lines anywhere in the buffer:
  885. #+STARTUP: shrink"
  886. :group 'org-startup
  887. :type 'boolean
  888. :version "27.1"
  889. :package-version '(Org . "9.2")
  890. :safe #'booleanp)
  891. (defcustom org-startup-with-inline-images nil
  892. "Non-nil means show inline images when loading a new Org file.
  893. This can also be configured on a per-file basis by adding one of
  894. the following lines anywhere in the buffer:
  895. #+STARTUP: inlineimages
  896. #+STARTUP: noinlineimages"
  897. :group 'org-startup
  898. :version "24.1"
  899. :type 'boolean)
  900. (defcustom org-startup-with-latex-preview nil
  901. "Non-nil means preview LaTeX fragments when loading a new Org file.
  902. This can also be configured on a per-file basis by adding one of
  903. the following lines anywhere in the buffer:
  904. #+STARTUP: latexpreview
  905. #+STARTUP: nolatexpreview"
  906. :group 'org-startup
  907. :version "24.4"
  908. :package-version '(Org . "8.0")
  909. :type 'boolean)
  910. (defcustom org-insert-mode-line-in-empty-file nil
  911. "Non-nil means insert the first line setting Org mode in empty files.
  912. When the function `org-mode' is called interactively in an empty file, this
  913. normally means that the file name does not automatically trigger Org mode.
  914. To ensure that the file will always be in Org mode in the future, a
  915. line enforcing Org mode will be inserted into the buffer, if this option
  916. has been set."
  917. :group 'org-startup
  918. :type 'boolean)
  919. (defcustom org-replace-disputed-keys nil
  920. "Non-nil means use alternative key bindings for some keys.
  921. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  922. These keys are also used by other packages like shift-selection-mode'
  923. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  924. If you want to use Org mode together with one of these other modes,
  925. or more generally if you would like to move some Org mode commands to
  926. other keys, set this variable and configure the keys with the variable
  927. `org-disputed-keys'.
  928. This option is only relevant at load-time of Org mode, and must be set
  929. *before* org.el is loaded. Changing it requires a restart of Emacs to
  930. become effective."
  931. :group 'org-startup
  932. :type 'boolean)
  933. (defcustom org-use-extra-keys nil
  934. "Non-nil means use extra key sequence definitions for certain commands.
  935. This happens automatically if `window-system' is nil. This
  936. variable lets you do the same manually. You must set it before
  937. loading Org."
  938. :group 'org-startup
  939. :type 'boolean)
  940. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  941. (defcustom org-disputed-keys
  942. '(([(shift up)] . [(meta p)])
  943. ([(shift down)] . [(meta n)])
  944. ([(shift left)] . [(meta -)])
  945. ([(shift right)] . [(meta +)])
  946. ([(control shift right)] . [(meta shift +)])
  947. ([(control shift left)] . [(meta shift -)]))
  948. "Keys for which Org mode and other modes compete.
  949. This is an alist, cars are the default keys, second element specifies
  950. the alternative to use when `org-replace-disputed-keys' is t.
  951. Keys can be specified in any syntax supported by `define-key'.
  952. The value of this option takes effect only at Org mode startup,
  953. therefore you'll have to restart Emacs to apply it after changing."
  954. :group 'org-startup
  955. :type 'alist)
  956. (defun org-key (key)
  957. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  958. Or return the original if not disputed."
  959. (when org-replace-disputed-keys
  960. (let* ((nkey (key-description key))
  961. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  962. org-disputed-keys)))
  963. (setq key (if x (cdr x) key))))
  964. key)
  965. (defun org-defkey (keymap key def)
  966. "Define a key, possibly translated, as returned by `org-key'."
  967. (define-key keymap (org-key key) def))
  968. (defcustom org-ellipsis nil
  969. "The ellipsis to use in the Org mode outline.
  970. When nil, just use the standard three dots. When a non-empty string,
  971. use that string instead.
  972. The change affects only Org mode (which will then use its own display table).
  973. Changing this requires executing `\\[org-mode]' in a buffer to become
  974. effective."
  975. :group 'org-startup
  976. :type '(choice (const :tag "Default" nil)
  977. (string :tag "String" :value "...#"))
  978. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  979. (defvar org-display-table nil
  980. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  981. (defgroup org-keywords nil
  982. "Keywords in Org mode."
  983. :tag "Org Keywords"
  984. :group 'org)
  985. (defcustom org-closed-keep-when-no-todo nil
  986. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  987. :group 'org-todo
  988. :group 'org-keywords
  989. :version "24.4"
  990. :package-version '(Org . "8.0")
  991. :type 'boolean)
  992. (defgroup org-structure nil
  993. "Options concerning the general structure of Org files."
  994. :tag "Org Structure"
  995. :group 'org)
  996. (defgroup org-reveal-location nil
  997. "Options about how to make context of a location visible."
  998. :tag "Org Reveal Location"
  999. :group 'org-structure)
  1000. (defcustom org-show-context-detail '((agenda . local)
  1001. (bookmark-jump . lineage)
  1002. (isearch . lineage)
  1003. (default . ancestors))
  1004. "Alist between context and visibility span when revealing a location.
  1005. \\<org-mode-map>Some actions may move point into invisible
  1006. locations. As a consequence, Org always expose a neighborhood
  1007. around point. How much is shown depends on the initial action,
  1008. or context. Valid contexts are
  1009. agenda when exposing an entry from the agenda
  1010. org-goto when using the command `org-goto' (`\\[org-goto]')
  1011. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1012. tags-tree when constructing a sparse tree based on tags matches
  1013. link-search when exposing search matches associated with a link
  1014. mark-goto when exposing the jump goal of a mark
  1015. bookmark-jump when exposing a bookmark location
  1016. isearch when exiting from an incremental search
  1017. default default for all contexts not set explicitly
  1018. Allowed visibility spans are
  1019. minimal show current headline; if point is not on headline,
  1020. also show entry
  1021. local show current headline, entry and next headline
  1022. ancestors show current headline and its direct ancestors; if
  1023. point is not on headline, also show entry
  1024. lineage show current headline, its direct ancestors and all
  1025. their children; if point is not on headline, also show
  1026. entry and first child
  1027. tree show current headline, its direct ancestors and all
  1028. their children; if point is not on headline, also show
  1029. entry and all children
  1030. canonical show current headline, its direct ancestors along with
  1031. their entries and children; if point is not located on
  1032. the headline, also show current entry and all children
  1033. As special cases, a nil or t value means show all contexts in
  1034. `minimal' or `canonical' view, respectively.
  1035. Some views can make displayed information very compact, but also
  1036. make it harder to edit the location of the match. In such
  1037. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1038. more context."
  1039. :group 'org-reveal-location
  1040. :version "26.1"
  1041. :package-version '(Org . "9.0")
  1042. :type '(choice
  1043. (const :tag "Canonical" t)
  1044. (const :tag "Minimal" nil)
  1045. (repeat :greedy t :tag "Individual contexts"
  1046. (cons
  1047. (choice :tag "Context"
  1048. (const agenda)
  1049. (const org-goto)
  1050. (const occur-tree)
  1051. (const tags-tree)
  1052. (const link-search)
  1053. (const mark-goto)
  1054. (const bookmark-jump)
  1055. (const isearch)
  1056. (const default))
  1057. (choice :tag "Detail level"
  1058. (const minimal)
  1059. (const local)
  1060. (const ancestors)
  1061. (const lineage)
  1062. (const tree)
  1063. (const canonical))))))
  1064. (defcustom org-indirect-buffer-display 'other-window
  1065. "How should indirect tree buffers be displayed?
  1066. This applies to indirect buffers created with the commands
  1067. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1068. Valid values are:
  1069. current-window Display in the current window
  1070. other-window Just display in another window.
  1071. dedicated-frame Create one new frame, and re-use it each time.
  1072. new-frame Make a new frame each time. Note that in this case
  1073. previously-made indirect buffers are kept, and you need to
  1074. kill these buffers yourself."
  1075. :group 'org-structure
  1076. :group 'org-agenda-windows
  1077. :type '(choice
  1078. (const :tag "In current window" current-window)
  1079. (const :tag "In current frame, other window" other-window)
  1080. (const :tag "Each time a new frame" new-frame)
  1081. (const :tag "One dedicated frame" dedicated-frame)))
  1082. (defcustom org-use-speed-commands nil
  1083. "Non-nil means activate single letter commands at beginning of a headline.
  1084. This may also be a function to test for appropriate locations where speed
  1085. commands should be active.
  1086. For example, to activate speed commands when the point is on any
  1087. star at the beginning of the headline, you can do this:
  1088. (setq org-use-speed-commands
  1089. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1090. :group 'org-structure
  1091. :type '(choice
  1092. (const :tag "Never" nil)
  1093. (const :tag "At beginning of headline stars" t)
  1094. (function)))
  1095. (defcustom org-speed-commands-user nil
  1096. "Alist of additional speed commands.
  1097. This list will be checked before `org-speed-commands-default'
  1098. when the variable `org-use-speed-commands' is non-nil
  1099. and when the cursor is at the beginning of a headline.
  1100. The car of each entry is a string with a single letter, which must
  1101. be assigned to `self-insert-command' in the global map.
  1102. The cdr is either a command to be called interactively, a function
  1103. to be called, or a form to be evaluated.
  1104. An entry that is just a list with a single string will be interpreted
  1105. as a descriptive headline that will be added when listing the speed
  1106. commands in the Help buffer using the `?' speed command."
  1107. :group 'org-structure
  1108. :type '(repeat :value ("k" . ignore)
  1109. (choice :value ("k" . ignore)
  1110. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1111. (cons :tag "Letter and Command"
  1112. (string :tag "Command letter")
  1113. (choice
  1114. (function)
  1115. (sexp))))))
  1116. (defcustom org-bookmark-names-plist
  1117. '(:last-capture "org-capture-last-stored"
  1118. :last-refile "org-refile-last-stored"
  1119. :last-capture-marker "org-capture-last-stored-marker")
  1120. "Names for bookmarks automatically set by some Org commands.
  1121. This can provide strings as names for a number of bookmarks Org sets
  1122. automatically. The following keys are currently implemented:
  1123. :last-capture
  1124. :last-capture-marker
  1125. :last-refile
  1126. When a key does not show up in the property list, the corresponding bookmark
  1127. is not set."
  1128. :group 'org-structure
  1129. :type 'plist)
  1130. (defgroup org-cycle nil
  1131. "Options concerning visibility cycling in Org mode."
  1132. :tag "Org Cycle"
  1133. :group 'org-structure)
  1134. (defcustom org-cycle-skip-children-state-if-no-children t
  1135. "Non-nil means skip CHILDREN state in entries that don't have any."
  1136. :group 'org-cycle
  1137. :type 'boolean)
  1138. (defcustom org-cycle-max-level nil
  1139. "Maximum level which should still be subject to visibility cycling.
  1140. Levels higher than this will, for cycling, be treated as text, not a headline.
  1141. When `org-odd-levels-only' is set, a value of N in this variable actually
  1142. means 2N-1 stars as the limiting headline.
  1143. When nil, cycle all levels.
  1144. Note that the limiting level of cycling is also influenced by
  1145. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1146. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1147. than its value."
  1148. :group 'org-cycle
  1149. :type '(choice
  1150. (const :tag "No limit" nil)
  1151. (integer :tag "Maximum level")))
  1152. (defcustom org-hide-block-startup nil
  1153. "Non-nil means entering Org mode will fold all blocks.
  1154. This can also be set in on a per-file basis with
  1155. #+STARTUP: hideblocks
  1156. #+STARTUP: showblocks"
  1157. :group 'org-startup
  1158. :group 'org-cycle
  1159. :type 'boolean)
  1160. (defcustom org-cycle-global-at-bob nil
  1161. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1162. This makes it possible to do global cycling without having to use `S-TAB'
  1163. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1164. line of the buffer
  1165. must not be a headline -- it may be empty or some other text.
  1166. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1167. sure the cursor stays at the beginning of the buffer.
  1168. When this option is nil, don't do anything special at the beginning of
  1169. the buffer."
  1170. :group 'org-cycle
  1171. :type 'boolean)
  1172. (defcustom org-cycle-level-after-item/entry-creation t
  1173. "Non-nil means cycle entry level or item indentation in new empty entries.
  1174. When the cursor is at the end of an empty headline, i.e., with only stars
  1175. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1176. and then all possible ancestor states, before returning to the original state.
  1177. This makes data entry extremely fast: M-RET to create a new headline,
  1178. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1179. When the cursor is at the end of an empty plain list item, one TAB will
  1180. make it a subitem, two or more tabs will back up to make this an item
  1181. higher up in the item hierarchy."
  1182. :group 'org-cycle
  1183. :type 'boolean)
  1184. (defcustom org-cycle-emulate-tab t
  1185. "Where should `org-cycle' emulate TAB.
  1186. nil Never
  1187. white Only in completely white lines
  1188. whitestart Only at the beginning of lines, before the first non-white char
  1189. t Everywhere except in headlines
  1190. exc-hl-bol Everywhere except at the start of a headline
  1191. If TAB is used in a place where it does not emulate TAB, the current subtree
  1192. visibility is cycled."
  1193. :group 'org-cycle
  1194. :type '(choice (const :tag "Never" nil)
  1195. (const :tag "Only in completely white lines" white)
  1196. (const :tag "Before first char in a line" whitestart)
  1197. (const :tag "Everywhere except in headlines" t)
  1198. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1199. (defcustom org-cycle-separator-lines 2
  1200. "Number of empty lines needed to keep an empty line between collapsed trees.
  1201. If you leave an empty line between the end of a subtree and the following
  1202. headline, this empty line is hidden when the subtree is folded.
  1203. Org mode will leave (exactly) one empty line visible if the number of
  1204. empty lines is equal or larger to the number given in this variable.
  1205. So the default 2 means at least 2 empty lines after the end of a subtree
  1206. are needed to produce free space between a collapsed subtree and the
  1207. following headline.
  1208. If the number is negative, and the number of empty lines is at least -N,
  1209. all empty lines are shown.
  1210. Special case: when 0, never leave empty lines in collapsed view."
  1211. :group 'org-cycle
  1212. :type 'integer)
  1213. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1214. (defcustom org-pre-cycle-hook nil
  1215. "Hook that is run before visibility cycling is happening.
  1216. The function(s) in this hook must accept a single argument which indicates
  1217. the new state that will be set right after running this hook. The
  1218. argument is a symbol. Before a global state change, it can have the values
  1219. `overview', `content', or `all'. Before a local state change, it can have
  1220. the values `folded', `children', or `subtree'."
  1221. :group 'org-cycle
  1222. :type 'hook)
  1223. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1224. org-cycle-hide-drawers
  1225. org-cycle-show-empty-lines
  1226. org-optimize-window-after-visibility-change)
  1227. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1228. The function(s) in this hook must accept a single argument which indicates
  1229. the new state that was set by the most recent `org-cycle' command. The
  1230. argument is a symbol. After a global state change, it can have the values
  1231. `overview', `contents', or `all'. After a local state change, it can have
  1232. the values `folded', `children', or `subtree'."
  1233. :group 'org-cycle
  1234. :type 'hook
  1235. :version "26.1"
  1236. :package-version '(Org . "8.3"))
  1237. (defgroup org-edit-structure nil
  1238. "Options concerning structure editing in Org mode."
  1239. :tag "Org Edit Structure"
  1240. :group 'org-structure)
  1241. (defcustom org-odd-levels-only nil
  1242. "Non-nil means skip even levels and only use odd levels for the outline.
  1243. This has the effect that two stars are being added/taken away in
  1244. promotion/demotion commands. It also influences how levels are
  1245. handled by the exporters.
  1246. Changing it requires restart of `font-lock-mode' to become effective
  1247. for fontification also in regions already fontified.
  1248. You may also set this on a per-file basis by adding one of the following
  1249. lines to the buffer:
  1250. #+STARTUP: odd
  1251. #+STARTUP: oddeven"
  1252. :group 'org-edit-structure
  1253. :group 'org-appearance
  1254. :type 'boolean)
  1255. (defcustom org-adapt-indentation t
  1256. "Non-nil means adapt indentation to outline node level.
  1257. When this variable is set, Org assumes that you write outlines by
  1258. indenting text in each node to align with the headline (after the
  1259. stars). The following issues are influenced by this variable:
  1260. - The indentation is increased by one space in a demotion
  1261. command, and decreased by one in a promotion command. However,
  1262. in the latter case, if shifting some line in the entry body
  1263. would alter document structure (e.g., insert a new headline),
  1264. indentation is not changed at all.
  1265. - Property drawers and planning information is inserted indented
  1266. when this variable is set. When nil, they will not be indented.
  1267. - TAB indents a line relative to current level. The lines below
  1268. a headline will be indented when this variable is set.
  1269. Note that this is all about true indentation, by adding and
  1270. removing space characters. See also `org-indent.el' which does
  1271. level-dependent indentation in a virtual way, i.e. at display
  1272. time in Emacs."
  1273. :group 'org-edit-structure
  1274. :type 'boolean)
  1275. (defcustom org-special-ctrl-a/e nil
  1276. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1277. When t, `C-a' will bring back the cursor to the beginning of the
  1278. headline text, i.e. after the stars and after a possible TODO
  1279. keyword. In an item, this will be the position after bullet and
  1280. check-box, if any. When the cursor is already at that position,
  1281. another `C-a' will bring it to the beginning of the line.
  1282. `C-e' will jump to the end of the headline, ignoring the presence
  1283. of tags in the headline. A second `C-e' will then jump to the
  1284. true end of the line, after any tags. This also means that, when
  1285. this variable is non-nil, `C-e' also will never jump beyond the
  1286. end of the heading of a folded section, i.e. not after the
  1287. ellipses.
  1288. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1289. normally, going to the true line boundary first. Only a directly
  1290. following, identical keypress will bring the cursor to the
  1291. special positions.
  1292. This may also be a cons cell where the behavior for `C-a' and
  1293. `C-e' is set separately."
  1294. :group 'org-edit-structure
  1295. :type '(choice
  1296. (const :tag "off" nil)
  1297. (const :tag "on: after stars/bullet and before tags first" t)
  1298. (const :tag "reversed: true line boundary first" reversed)
  1299. (cons :tag "Set C-a and C-e separately"
  1300. (choice :tag "Special C-a"
  1301. (const :tag "off" nil)
  1302. (const :tag "on: after stars/bullet first" t)
  1303. (const :tag "reversed: before stars/bullet first" reversed))
  1304. (choice :tag "Special C-e"
  1305. (const :tag "off" nil)
  1306. (const :tag "on: before tags first" t)
  1307. (const :tag "reversed: after tags first" reversed)))))
  1308. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1309. (defcustom org-special-ctrl-k nil
  1310. "Non-nil means `C-k' will behave specially in headlines.
  1311. When nil, `C-k' will call the default `kill-line' command.
  1312. When t, the following will happen while the cursor is in the headline:
  1313. - When the cursor is at the beginning of a headline, kill the entire
  1314. line and possible the folded subtree below the line.
  1315. - When in the middle of the headline text, kill the headline up to the tags.
  1316. - When after the headline text, kill the tags."
  1317. :group 'org-edit-structure
  1318. :type 'boolean)
  1319. (defcustom org-ctrl-k-protect-subtree nil
  1320. "Non-nil means, do not delete a hidden subtree with C-k.
  1321. When set to the symbol `error', simply throw an error when C-k is
  1322. used to kill (part-of) a headline that has hidden text behind it.
  1323. Any other non-nil value will result in a query to the user, if it is
  1324. OK to kill that hidden subtree. When nil, kill without remorse."
  1325. :group 'org-edit-structure
  1326. :version "24.1"
  1327. :type '(choice
  1328. (const :tag "Do not protect hidden subtrees" nil)
  1329. (const :tag "Protect hidden subtrees with a security query" t)
  1330. (const :tag "Never kill a hidden subtree with C-k" error)))
  1331. (defcustom org-special-ctrl-o t
  1332. "Non-nil means, make `C-o' insert a row in tables."
  1333. :group 'org-edit-structure
  1334. :type 'boolean)
  1335. (defcustom org-catch-invisible-edits nil
  1336. "Check if in invisible region before inserting or deleting a character.
  1337. Valid values are:
  1338. nil Do not check, so just do invisible edits.
  1339. error Throw an error and do nothing.
  1340. show Make point visible, and do the requested edit.
  1341. show-and-error Make point visible, then throw an error and abort the edit.
  1342. smart Make point visible, and do insertion/deletion if it is
  1343. adjacent to visible text and the change feels predictable.
  1344. Never delete a previously invisible character or add in the
  1345. middle or right after an invisible region. Basically, this
  1346. allows insertion and backward-delete right before ellipses.
  1347. FIXME: maybe in this case we should not even show?"
  1348. :group 'org-edit-structure
  1349. :version "24.1"
  1350. :type '(choice
  1351. (const :tag "Do not check" nil)
  1352. (const :tag "Throw error when trying to edit" error)
  1353. (const :tag "Unhide, but do not do the edit" show-and-error)
  1354. (const :tag "Show invisible part and do the edit" show)
  1355. (const :tag "Be smart and do the right thing" smart)))
  1356. (defcustom org-yank-folded-subtrees t
  1357. "Non-nil means when yanking subtrees, fold them.
  1358. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1359. it starts with a heading and all other headings in it are either children
  1360. or siblings, then fold all the subtrees. However, do this only if no
  1361. text after the yank would be swallowed into a folded tree by this action."
  1362. :group 'org-edit-structure
  1363. :type 'boolean)
  1364. (defcustom org-yank-adjusted-subtrees nil
  1365. "Non-nil means when yanking subtrees, adjust the level.
  1366. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1367. this function for details."
  1368. :group 'org-edit-structure
  1369. :type 'boolean)
  1370. (defcustom org-M-RET-may-split-line '((default . t))
  1371. "Non-nil means M-RET will split the line at the cursor position.
  1372. When nil, it will go to the end of the line before making a
  1373. new line.
  1374. You may also set this option in a different way for different
  1375. contexts. Valid contexts are:
  1376. headline when creating a new headline
  1377. item when creating a new item
  1378. table in a table field
  1379. default the value to be used for all contexts not explicitly
  1380. customized"
  1381. :group 'org-structure
  1382. :group 'org-table
  1383. :type '(choice
  1384. (const :tag "Always" t)
  1385. (const :tag "Never" nil)
  1386. (repeat :greedy t :tag "Individual contexts"
  1387. (cons
  1388. (choice :tag "Context"
  1389. (const headline)
  1390. (const item)
  1391. (const table)
  1392. (const default))
  1393. (boolean)))))
  1394. (defcustom org-insert-heading-respect-content nil
  1395. "Non-nil means insert new headings after the current subtree.
  1396. \\<org-mode-map>
  1397. When nil, the new heading is created directly after the current line.
  1398. The commands `\\[org-insert-heading-respect-content]' and \
  1399. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1400. for the duration of the command."
  1401. :group 'org-structure
  1402. :type 'boolean)
  1403. (defcustom org-blank-before-new-entry '((heading . auto)
  1404. (plain-list-item . auto))
  1405. "Should `org-insert-heading' leave a blank line before new heading/item?
  1406. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1407. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1408. which case Org will look at the surrounding headings/items and try to
  1409. make an intelligent decision whether to insert a blank line or not."
  1410. :group 'org-edit-structure
  1411. :type '(list
  1412. (cons (const heading)
  1413. (choice (const :tag "Never" nil)
  1414. (const :tag "Always" t)
  1415. (const :tag "Auto" auto)))
  1416. (cons (const plain-list-item)
  1417. (choice (const :tag "Never" nil)
  1418. (const :tag "Always" t)
  1419. (const :tag "Auto" auto)))))
  1420. (defcustom org-insert-heading-hook nil
  1421. "Hook being run after inserting a new heading."
  1422. :group 'org-edit-structure
  1423. :type 'hook)
  1424. (defcustom org-enable-fixed-width-editor t
  1425. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1426. This currently only means they are never auto-wrapped.
  1427. When nil, such lines will be treated like ordinary lines."
  1428. :group 'org-edit-structure
  1429. :type 'boolean)
  1430. (defgroup org-sparse-trees nil
  1431. "Options concerning sparse trees in Org mode."
  1432. :tag "Org Sparse Trees"
  1433. :group 'org-structure)
  1434. (defcustom org-highlight-sparse-tree-matches t
  1435. "Non-nil means highlight all matches that define a sparse tree.
  1436. The highlights will automatically disappear the next time the buffer is
  1437. changed by an edit command."
  1438. :group 'org-sparse-trees
  1439. :type 'boolean)
  1440. (defcustom org-remove-highlights-with-change t
  1441. "Non-nil means any change to the buffer will remove temporary highlights.
  1442. \\<org-mode-map>\
  1443. Such highlights are created by `org-occur' and `org-clock-display'.
  1444. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1445. to get rid of the highlights.
  1446. The highlights created by `org-toggle-latex-fragment' always need
  1447. `\\[org-toggle-latex-fragment]' to be removed."
  1448. :group 'org-sparse-trees
  1449. :group 'org-time
  1450. :type 'boolean)
  1451. (defcustom org-occur-case-fold-search t
  1452. "Non-nil means `org-occur' should be case-insensitive.
  1453. If set to `smart' the search will be case-insensitive only if it
  1454. doesn't specify any upper case character."
  1455. :group 'org-sparse-trees
  1456. :version "26.1"
  1457. :type '(choice
  1458. (const :tag "Case-sensitive" nil)
  1459. (const :tag "Case-insensitive" t)
  1460. (const :tag "Case-insensitive for lower case searches only" 'smart)))
  1461. (defcustom org-occur-hook '(org-first-headline-recenter)
  1462. "Hook that is run after `org-occur' has constructed a sparse tree.
  1463. This can be used to recenter the window to show as much of the structure
  1464. as possible."
  1465. :group 'org-sparse-trees
  1466. :type 'hook)
  1467. (defgroup org-table nil
  1468. "Options concerning tables in Org mode."
  1469. :tag "Org Table"
  1470. :group 'org)
  1471. (defcustom org-self-insert-cluster-for-undo nil
  1472. "Non-nil means cluster self-insert commands for undo when possible.
  1473. If this is set, then, like in the Emacs command loop, 20 consecutive
  1474. characters will be undone together.
  1475. This is configurable, because there is some impact on typing performance."
  1476. :group 'org-table
  1477. :type 'boolean)
  1478. (defcustom org-table-tab-recognizes-table.el t
  1479. "Non-nil means TAB will automatically notice a table.el table.
  1480. When it sees such a table, it moves point into it and - if necessary -
  1481. calls `table-recognize-table'."
  1482. :group 'org-table-editing
  1483. :type 'boolean)
  1484. (defgroup org-link nil
  1485. "Options concerning links in Org mode."
  1486. :tag "Org Link"
  1487. :group 'org)
  1488. (defvar-local org-link-abbrev-alist-local nil
  1489. "Buffer-local version of `org-link-abbrev-alist', which see.
  1490. The value of this is taken from the #+LINK lines.")
  1491. (defcustom org-link-parameters
  1492. '(("doi" :follow org--open-doi-link)
  1493. ("elisp" :follow org--open-elisp-link)
  1494. ("file" :complete org-file-complete-link)
  1495. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1496. ("help" :follow org--open-help-link)
  1497. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1498. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1499. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1500. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1501. ("shell" :follow org--open-shell-link))
  1502. "An alist of properties that defines all the links in Org mode.
  1503. The key in each association is a string of the link type.
  1504. Subsequent optional elements make up a p-list of link properties.
  1505. :follow - A function that takes the link path as an argument.
  1506. :export - A function that takes the link path, description and
  1507. export-backend as arguments.
  1508. :store - A function responsible for storing the link. See the
  1509. function `org-store-link-functions'.
  1510. :complete - A function that inserts a link with completion. The
  1511. function takes one optional prefix arg.
  1512. :face - A face for the link, or a function that returns a face.
  1513. The function takes one argument which is the link path. The
  1514. default face is `org-link'.
  1515. :mouse-face - The mouse-face. The default is `highlight'.
  1516. :display - `full' will not fold the link in descriptive
  1517. display. Default is `org-link'.
  1518. :help-echo - A string or function that takes (window object position)
  1519. as arguments and returns a string.
  1520. :keymap - A keymap that is active on the link. The default is
  1521. `org-mouse-map'.
  1522. :htmlize-link - A function for the htmlize-link. Defaults
  1523. to (list :uri \"type:path\")
  1524. :activate-func - A function to run at the end of font-lock
  1525. activation. The function must accept (link-start link-end path bracketp)
  1526. as arguments."
  1527. :group 'org-link
  1528. :type '(alist :tag "Link display parameters"
  1529. :value-type plist)
  1530. :version "26.1"
  1531. :package-version '(Org . "9.1"))
  1532. (defun org-link-get-parameter (type key)
  1533. "Get TYPE link property for KEY.
  1534. TYPE is a string and KEY is a plist keyword."
  1535. (plist-get
  1536. (cdr (assoc type org-link-parameters))
  1537. key))
  1538. (defun org-link-set-parameters (type &rest parameters)
  1539. "Set link TYPE properties to PARAMETERS.
  1540. PARAMETERS should be :key val pairs."
  1541. (let ((data (assoc type org-link-parameters)))
  1542. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1543. (push (cons type parameters) org-link-parameters)
  1544. (org-make-link-regexps)
  1545. (org-element-update-syntax))))
  1546. (defun org-link-types ()
  1547. "Return a list of known link types."
  1548. (mapcar #'car org-link-parameters))
  1549. (defcustom org-link-abbrev-alist nil
  1550. "Alist of link abbreviations.
  1551. The car of each element is a string, to be replaced at the start of a link.
  1552. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1553. links in Org buffers can have an optional tag after a double colon, e.g.,
  1554. [[linkkey:tag][description]]
  1555. The `linkkey' must be a single word, starting with a letter, followed
  1556. by letters, numbers, `-' or `_'.
  1557. If REPLACE is a string, the tag will simply be appended to create the link.
  1558. If the string contains \"%s\", the tag will be inserted there. If the string
  1559. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1560. at that point (see the function `url-hexify-string'). If the string contains
  1561. the specifier \"%(my-function)\", then the custom function `my-function' will
  1562. be invoked: this function takes the tag as its only argument and must return
  1563. a string.
  1564. REPLACE may also be a function that will be called with the tag as the
  1565. only argument to create the link, which should be returned as a string.
  1566. See the manual for examples."
  1567. :group 'org-link
  1568. :type '(repeat
  1569. (cons
  1570. (string :tag "Protocol")
  1571. (choice
  1572. (string :tag "Format")
  1573. (function)))))
  1574. (defcustom org-descriptive-links t
  1575. "Non-nil means Org will display descriptive links.
  1576. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1577. \"Org Website\", hiding the link itself and just displaying its
  1578. description. When set to nil, Org will display the full links
  1579. literally.
  1580. You can interactively set the value of this variable by calling
  1581. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1582. :group 'org-link
  1583. :type 'boolean)
  1584. (defcustom org-link-file-path-type 'adaptive
  1585. "How the path name in file links should be stored.
  1586. Valid values are:
  1587. relative Relative to the current directory, i.e. the directory of the file
  1588. into which the link is being inserted.
  1589. absolute Absolute path, if possible with ~ for home directory.
  1590. noabbrev Absolute path, no abbreviation of home directory.
  1591. adaptive Use relative path for files in the current directory and sub-
  1592. directories of it. For other files, use an absolute path."
  1593. :group 'org-link
  1594. :type '(choice
  1595. (const relative)
  1596. (const absolute)
  1597. (const noabbrev)
  1598. (const adaptive)))
  1599. (defvaralias 'org-activate-links 'org-highlight-links)
  1600. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1601. "Types of links that should be highlighted in Org files.
  1602. This is a list of symbols, each one of them leading to the
  1603. highlighting of a certain link type.
  1604. You can still open links that are not highlighted.
  1605. In principle, it does not hurt to turn on highlighting for all
  1606. link types. There may be a small gain when turning off unused
  1607. link types. The types are:
  1608. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1609. angle Links in angular brackets that may contain whitespace like
  1610. <bbdb:Carsten Dominik>.
  1611. plain Plain links in normal text, no whitespace, like http://google.com.
  1612. radio Text that is matched by a radio target, see manual for details.
  1613. tag Tag settings in a headline (link to tag search).
  1614. date Time stamps (link to calendar).
  1615. footnote Footnote labels.
  1616. If you set this variable during an Emacs session, use `org-mode-restart'
  1617. in the Org buffer so that the change takes effect."
  1618. :group 'org-link
  1619. :group 'org-appearance
  1620. :type '(set :greedy t
  1621. (const :tag "Double bracket links" bracket)
  1622. (const :tag "Angular bracket links" angle)
  1623. (const :tag "Plain text links" plain)
  1624. (const :tag "Radio target matches" radio)
  1625. (const :tag "Tags" tag)
  1626. (const :tag "Timestamps" date)
  1627. (const :tag "Footnotes" footnote)))
  1628. (defcustom org-make-link-description-function nil
  1629. "Function to use for generating link descriptions from links.
  1630. This function must take two parameters: the first one is the
  1631. link, the second one is the description generated by
  1632. `org-insert-link'. The function should return the description to
  1633. use."
  1634. :group 'org-link
  1635. :type '(choice (const nil) (function)))
  1636. (defgroup org-link-store nil
  1637. "Options concerning storing links in Org mode."
  1638. :tag "Org Store Link"
  1639. :group 'org-link)
  1640. (defcustom org-url-hexify-p t
  1641. "When non-nil, hexify URL when creating a link."
  1642. :type 'boolean
  1643. :version "24.3"
  1644. :group 'org-link-store)
  1645. (defcustom org-email-link-description-format "Email %c: %.30s"
  1646. "Format of the description part of a link to an email or usenet message.
  1647. The following %-escapes will be replaced by corresponding information:
  1648. %F full \"From\" field
  1649. %f name, taken from \"From\" field, address if no name
  1650. %T full \"To\" field
  1651. %t first name in \"To\" field, address if no name
  1652. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1653. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1654. %s subject
  1655. %d date
  1656. %m message-id.
  1657. You may use normal field width specification between the % and the letter.
  1658. This is for example useful to limit the length of the subject.
  1659. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1660. :group 'org-link-store
  1661. :type 'string)
  1662. (defcustom org-from-is-user-regexp
  1663. (let (r1 r2)
  1664. (when (and user-mail-address (not (string= user-mail-address "")))
  1665. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1666. (when (and user-full-name (not (string= user-full-name "")))
  1667. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1668. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1669. "Regexp matched against the \"From:\" header of an email or usenet message.
  1670. It should match if the message is from the user him/herself."
  1671. :group 'org-link-store
  1672. :type 'regexp)
  1673. (defcustom org-context-in-file-links t
  1674. "Non-nil means file links from `org-store-link' contain context.
  1675. \\<org-mode-map>
  1676. A search string will be added to the file name with :: as separator
  1677. and used to find the context when the link is activated by the command
  1678. `org-open-at-point'. When this option is t, the entire active region
  1679. will be placed in the search string of the file link. If set to a
  1680. positive integer, only the first n lines of context will be stored.
  1681. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1682. \\[org-store-link]')
  1683. negates this setting for the duration of the command."
  1684. :group 'org-link-store
  1685. :type '(choice boolean integer))
  1686. (defcustom org-keep-stored-link-after-insertion nil
  1687. "Non-nil means keep link in list for entire session.
  1688. \\<org-mode-map>
  1689. The command `org-store-link' adds a link pointing to the current
  1690. location to an internal list. These links accumulate during a session.
  1691. The command `org-insert-link' can be used to insert links into any
  1692. Org file (offering completion for all stored links).
  1693. When this option is nil, every link which has been inserted once using
  1694. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1695. unused
  1696. links more efficient."
  1697. :group 'org-link-store
  1698. :type 'boolean)
  1699. (defgroup org-link-follow nil
  1700. "Options concerning following links in Org mode."
  1701. :tag "Org Follow Link"
  1702. :group 'org-link)
  1703. (defcustom org-link-translation-function nil
  1704. "Function to translate links with different syntax to Org syntax.
  1705. This can be used to translate links created for example by the Planner
  1706. or emacs-wiki packages to Org syntax.
  1707. The function must accept two parameters, a TYPE containing the link
  1708. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1709. which is everything after the link protocol. It should return a cons
  1710. with possibly modified values of type and path.
  1711. Org contains a function for this, so if you set this variable to
  1712. `org-translate-link-from-planner', you should be able follow many
  1713. links created by planner."
  1714. :group 'org-link-follow
  1715. :type '(choice (const nil) (function)))
  1716. (defcustom org-follow-link-hook nil
  1717. "Hook that is run after a link has been followed."
  1718. :group 'org-link-follow
  1719. :type 'hook)
  1720. (defcustom org-tab-follows-link nil
  1721. "Non-nil means on links TAB will follow the link.
  1722. Needs to be set before org.el is loaded.
  1723. This really should not be used, it does not make sense, and the
  1724. implementation is bad."
  1725. :group 'org-link-follow
  1726. :type 'boolean)
  1727. (defcustom org-return-follows-link nil
  1728. "Non-nil means on links RET will follow the link.
  1729. In tables, the special behavior of RET has precedence."
  1730. :group 'org-link-follow
  1731. :type 'boolean)
  1732. (defcustom org-mouse-1-follows-link
  1733. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1734. "Non-nil means mouse-1 on a link will follow the link.
  1735. A longer mouse click will still set point. Needs to be set
  1736. before org.el is loaded."
  1737. :group 'org-link-follow
  1738. :version "26.1"
  1739. :package-version '(Org . "8.3")
  1740. :type '(choice
  1741. (const :tag "A double click follows the link" double)
  1742. (const :tag "Unconditionally follow the link with mouse-1" t)
  1743. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1744. (defcustom org-mark-ring-length 4
  1745. "Number of different positions to be recorded in the ring.
  1746. Changing this requires a restart of Emacs to work correctly."
  1747. :group 'org-link-follow
  1748. :type 'integer)
  1749. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1750. "Non-nil means internal fuzzy links can only match headlines.
  1751. When nil, the a fuzzy link may point to a target or a named
  1752. construct in the document. When set to the special value
  1753. `query-to-create', offer to create a new headline when none
  1754. matched.
  1755. Spaces and statistics cookies are ignored during heading searches."
  1756. :group 'org-link-follow
  1757. :version "24.1"
  1758. :type '(choice
  1759. (const :tag "Use fuzzy text search" nil)
  1760. (const :tag "Match only exact headline" t)
  1761. (const :tag "Match exact headline or query to create it"
  1762. query-to-create))
  1763. :safe #'symbolp)
  1764. (defcustom org-link-frame-setup
  1765. '((vm . vm-visit-folder-other-frame)
  1766. (vm-imap . vm-visit-imap-folder-other-frame)
  1767. (gnus . org-gnus-no-new-news)
  1768. (file . find-file-other-window)
  1769. (wl . wl-other-frame))
  1770. "Setup the frame configuration for following links.
  1771. When following a link with Emacs, it may often be useful to display
  1772. this link in another window or frame. This variable can be used to
  1773. set this up for the different types of links.
  1774. For VM, use any of
  1775. `vm-visit-folder'
  1776. `vm-visit-folder-other-window'
  1777. `vm-visit-folder-other-frame'
  1778. For Gnus, use any of
  1779. `gnus'
  1780. `gnus-other-frame'
  1781. `org-gnus-no-new-news'
  1782. For FILE, use any of
  1783. `find-file'
  1784. `find-file-other-window'
  1785. `find-file-other-frame'
  1786. For Wanderlust use any of
  1787. `wl'
  1788. `wl-other-frame'
  1789. For the calendar, use the variable `calendar-setup'.
  1790. For BBDB, it is currently only possible to display the matches in
  1791. another window."
  1792. :group 'org-link-follow
  1793. :type '(list
  1794. (cons (const vm)
  1795. (choice
  1796. (const vm-visit-folder)
  1797. (const vm-visit-folder-other-window)
  1798. (const vm-visit-folder-other-frame)))
  1799. (cons (const vm-imap)
  1800. (choice
  1801. (const vm-visit-imap-folder)
  1802. (const vm-visit-imap-folder-other-window)
  1803. (const vm-visit-imap-folder-other-frame)))
  1804. (cons (const gnus)
  1805. (choice
  1806. (const gnus)
  1807. (const gnus-other-frame)
  1808. (const org-gnus-no-new-news)))
  1809. (cons (const file)
  1810. (choice
  1811. (const find-file)
  1812. (const find-file-other-window)
  1813. (const find-file-other-frame)))
  1814. (cons (const wl)
  1815. (choice
  1816. (const wl)
  1817. (const wl-other-frame)))))
  1818. (defcustom org-display-internal-link-with-indirect-buffer nil
  1819. "Non-nil means use indirect buffer to display infile links.
  1820. Activating internal links (from one location in a file to another location
  1821. in the same file) normally just jumps to the location. When the link is
  1822. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1823. is displayed in
  1824. another window. When this option is set, the other window actually displays
  1825. an indirect buffer clone of the current buffer, to avoid any visibility
  1826. changes to the current buffer."
  1827. :group 'org-link-follow
  1828. :type 'boolean)
  1829. (defcustom org-open-non-existing-files nil
  1830. "Non-nil means `org-open-file' will open non-existing files.
  1831. When nil, an error will be generated.
  1832. This variable applies only to external applications because they
  1833. might choke on non-existing files. If the link is to a file that
  1834. will be opened in Emacs, the variable is ignored."
  1835. :group 'org-link-follow
  1836. :type 'boolean)
  1837. (defcustom org-open-directory-means-index-dot-org nil
  1838. "Non-nil means a link to a directory really means to index.org.
  1839. When nil, following a directory link will run dired or open a finder/explorer
  1840. window on that directory."
  1841. :group 'org-link-follow
  1842. :type 'boolean)
  1843. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1844. "Non-nil means ask for confirmation before executing shell links.
  1845. Shell links can be dangerous: just think about a link
  1846. [[shell:rm -rf ~/*][Google Search]]
  1847. This link would show up in your Org document as \"Google Search\",
  1848. but really it would remove your entire home directory.
  1849. Therefore we advise against setting this variable to nil.
  1850. Just change it to `y-or-n-p' if you want to confirm with a
  1851. single keystroke rather than having to type \"yes\"."
  1852. :group 'org-link-follow
  1853. :type '(choice
  1854. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1855. (const :tag "with y-or-n (faster)" y-or-n-p)
  1856. (const :tag "no confirmation (dangerous)" nil)))
  1857. (put 'org-confirm-shell-link-function
  1858. 'safe-local-variable
  1859. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1860. (defcustom org-confirm-shell-link-not-regexp ""
  1861. "A regexp to skip confirmation for shell links."
  1862. :group 'org-link-follow
  1863. :version "24.1"
  1864. :type 'regexp)
  1865. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1866. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1867. Elisp links can be dangerous: just think about a link
  1868. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1869. This link would show up in your Org document as \"Google Search\",
  1870. but really it would remove your entire home directory.
  1871. Therefore we advise against setting this variable to nil.
  1872. Just change it to `y-or-n-p' if you want to confirm with a
  1873. single keystroke rather than having to type \"yes\"."
  1874. :group 'org-link-follow
  1875. :type '(choice
  1876. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1877. (const :tag "with y-or-n (faster)" y-or-n-p)
  1878. (const :tag "no confirmation (dangerous)" nil)))
  1879. (put 'org-confirm-shell-link-function
  1880. 'safe-local-variable
  1881. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1882. (defcustom org-confirm-elisp-link-not-regexp ""
  1883. "A regexp to skip confirmation for Elisp links."
  1884. :group 'org-link-follow
  1885. :version "24.1"
  1886. :type 'regexp)
  1887. (defconst org-file-apps-defaults-gnu
  1888. '((remote . emacs)
  1889. (system . mailcap)
  1890. (t . mailcap))
  1891. "Default file applications on a UNIX or GNU/Linux system.
  1892. See `org-file-apps'.")
  1893. (defconst org-file-apps-defaults-macosx
  1894. '((remote . emacs)
  1895. (system . "open %s")
  1896. ("ps.gz" . "gv %s")
  1897. ("eps.gz" . "gv %s")
  1898. ("dvi" . "xdvi %s")
  1899. ("fig" . "xfig %s")
  1900. (t . "open %s"))
  1901. "Default file applications on a macOS system.
  1902. The system \"open\" is known as a default, but we use X11 applications
  1903. for some files for which the OS does not have a good default.
  1904. See `org-file-apps'.")
  1905. (defconst org-file-apps-defaults-windowsnt
  1906. (list '(remote . emacs)
  1907. (cons 'system (lambda (file _path)
  1908. (with-no-warnings (w32-shell-execute "open" file))))
  1909. (cons t (lambda (file _path)
  1910. (with-no-warnings (w32-shell-execute "open" file)))))
  1911. "Default file applications on a Windows NT system.
  1912. The system \"open\" is used for most files.
  1913. See `org-file-apps'.")
  1914. (defcustom org-file-apps
  1915. '((auto-mode . emacs)
  1916. ("\\.mm\\'" . default)
  1917. ("\\.x?html?\\'" . default)
  1918. ("\\.pdf\\'" . default))
  1919. "External applications for opening `file:path' items in a document.
  1920. \\<org-mode-map>\
  1921. Org mode uses system defaults for different file types, but
  1922. you can use this variable to set the application for a given file
  1923. extension. The entries in this list are cons cells where the car identifies
  1924. files and the cdr the corresponding command.
  1925. Possible values for the file identifier are:
  1926. \"string\" A string as a file identifier can be interpreted in different
  1927. ways, depending on its contents:
  1928. - Alphanumeric characters only:
  1929. Match links with this file extension.
  1930. Example: (\"pdf\" . \"evince %s\")
  1931. to open PDFs with evince.
  1932. - Regular expression: Match links where the
  1933. filename matches the regexp. If you want to
  1934. use groups here, use shy groups.
  1935. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1936. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1937. to open *.html and *.xhtml with firefox.
  1938. - Regular expression which contains (non-shy) groups:
  1939. Match links where the whole link, including \"::\", and
  1940. anything after that, matches the regexp.
  1941. In a custom command string, %1, %2, etc. are replaced with
  1942. the parts of the link that were matched by the groups.
  1943. For backwards compatibility, if a command string is given
  1944. that does not use any of the group matches, this case is
  1945. handled identically to the second one (i.e. match against
  1946. file name only).
  1947. In a custom function, you can access the group matches with
  1948. (match-string n link).
  1949. Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
  1950. \"evince -p %1 %s\")
  1951. to open [[file:document.pdf::5]] with evince at page 5.
  1952. `directory' Matches a directory
  1953. `remote' Matches a remote file, accessible through tramp or efs.
  1954. Remote files most likely should be visited through Emacs
  1955. because external applications cannot handle such paths.
  1956. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1957. so all files Emacs knows how to handle. Using this with
  1958. command `emacs' will open most files in Emacs. Beware that this
  1959. will also open html files inside Emacs, unless you add
  1960. (\"html\" . default) to the list as well.
  1961. `system' The system command to open files, like `open' on Windows
  1962. and macOS, and mailcap under GNU/Linux. This is the command
  1963. that will be selected if you call `org-open-at-point' with a
  1964. double prefix argument (`\\[universal-argument] \
  1965. \\[universal-argument] \\[org-open-at-point]').
  1966. t Default for files not matched by any of the other options.
  1967. Possible values for the command are:
  1968. `emacs' The file will be visited by the current Emacs process.
  1969. `default' Use the default application for this file type, which is the
  1970. association for t in the list, most likely in the system-specific
  1971. part. This can be used to overrule an unwanted setting in the
  1972. system-specific variable.
  1973. `system' Use the system command for opening files, like \"open\".
  1974. This command is specified by the entry whose car is `system'.
  1975. Most likely, the system-specific version of this variable
  1976. does define this command, but you can overrule/replace it
  1977. here.
  1978. `mailcap' Use command specified in the mailcaps.
  1979. string A command to be executed by a shell; %s will be replaced
  1980. by the path to the file.
  1981. function A Lisp function, which will be called with two arguments:
  1982. the file path and the original link string, without the
  1983. \"file:\" prefix.
  1984. For more examples, see the system specific constants
  1985. `org-file-apps-defaults-macosx'
  1986. `org-file-apps-defaults-windowsnt'
  1987. `org-file-apps-defaults-gnu'."
  1988. :group 'org-link-follow
  1989. :type '(repeat
  1990. (cons (choice :value ""
  1991. (string :tag "Extension")
  1992. (const :tag "System command to open files" system)
  1993. (const :tag "Default for unrecognized files" t)
  1994. (const :tag "Remote file" remote)
  1995. (const :tag "Links to a directory" directory)
  1996. (const :tag "Any files that have Emacs modes"
  1997. auto-mode))
  1998. (choice :value ""
  1999. (const :tag "Visit with Emacs" emacs)
  2000. (const :tag "Use default" default)
  2001. (const :tag "Use the system command" system)
  2002. (string :tag "Command")
  2003. (function :tag "Function")))))
  2004. (defcustom org-doi-server-url "http://dx.doi.org/"
  2005. "The URL of the DOI server."
  2006. :type 'string
  2007. :version "24.3"
  2008. :group 'org-link-follow)
  2009. (defgroup org-refile nil
  2010. "Options concerning refiling entries in Org mode."
  2011. :tag "Org Refile"
  2012. :group 'org)
  2013. (defcustom org-directory "~/org"
  2014. "Directory with Org files.
  2015. This is just a default location to look for Org files. There is no need
  2016. at all to put your files into this directory. It is used in the
  2017. following situations:
  2018. 1. When a capture template specifies a target file that is not an
  2019. absolute path. The path will then be interpreted relative to
  2020. `org-directory'
  2021. 2. When the value of variable `org-agenda-files' is a single file, any
  2022. relative paths in this file will be taken as relative to
  2023. `org-directory'."
  2024. :group 'org-refile
  2025. :group 'org-capture
  2026. :type 'directory)
  2027. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2028. "Default target for storing notes.
  2029. Used as a fall back file for org-capture.el, for templates that
  2030. do not specify a target file."
  2031. :group 'org-refile
  2032. :group 'org-capture
  2033. :type 'file)
  2034. (defcustom org-reverse-note-order nil
  2035. "Non-nil means store new notes at the beginning of a file or entry.
  2036. When nil, new notes will be filed to the end of a file or entry.
  2037. This can also be a list with cons cells of regular expressions that
  2038. are matched against file names, and values."
  2039. :group 'org-capture
  2040. :group 'org-refile
  2041. :type '(choice
  2042. (const :tag "Reverse always" t)
  2043. (const :tag "Reverse never" nil)
  2044. (repeat :tag "By file name regexp"
  2045. (cons regexp boolean))))
  2046. (defcustom org-log-refile nil
  2047. "Information to record when a task is refiled.
  2048. Possible values are:
  2049. nil Don't add anything
  2050. time Add a time stamp to the task
  2051. note Prompt for a note and add it with template `org-log-note-headings'
  2052. This option can also be set with on a per-file-basis with
  2053. #+STARTUP: nologrefile
  2054. #+STARTUP: logrefile
  2055. #+STARTUP: lognoterefile
  2056. You can have local logging settings for a subtree by setting the LOGGING
  2057. property to one or more of these keywords.
  2058. When bulk-refiling from the agenda, the value `note' is forbidden and
  2059. will temporarily be changed to `time'."
  2060. :group 'org-refile
  2061. :group 'org-progress
  2062. :version "24.1"
  2063. :type '(choice
  2064. (const :tag "No logging" nil)
  2065. (const :tag "Record timestamp" time)
  2066. (const :tag "Record timestamp with note." note)))
  2067. (defcustom org-refile-targets nil
  2068. "Targets for refiling entries with `\\[org-refile]'.
  2069. This is a list of cons cells. Each cell contains:
  2070. - a specification of the files to be considered, either a list of files,
  2071. or a symbol whose function or variable value will be used to retrieve
  2072. a file name or a list of file names. If you use `org-agenda-files' for
  2073. that, all agenda files will be scanned for targets. Nil means consider
  2074. headings in the current buffer.
  2075. - A specification of how to find candidate refile targets. This may be
  2076. any of:
  2077. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2078. This tag has to be present in all target headlines, inheritance will
  2079. not be considered.
  2080. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2081. todo keyword.
  2082. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2083. headlines that are refiling targets.
  2084. - a cons cell (:level . N). Any headline of level N is considered a target.
  2085. Note that, when `org-odd-levels-only' is set, level corresponds to
  2086. order in hierarchy, not to the number of stars.
  2087. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2088. Note that, when `org-odd-levels-only' is set, level corresponds to
  2089. order in hierarchy, not to the number of stars.
  2090. Each element of this list generates a set of possible targets.
  2091. The union of these sets is presented (with completion) to
  2092. the user by `org-refile'.
  2093. You can set the variable `org-refile-target-verify-function' to a function
  2094. to verify each headline found by the simple criteria above.
  2095. When this variable is nil, all top-level headlines in the current buffer
  2096. are used, equivalent to the value `((nil . (:level . 1))'."
  2097. :group 'org-refile
  2098. :type '(repeat
  2099. (cons
  2100. (choice :value org-agenda-files
  2101. (const :tag "All agenda files" org-agenda-files)
  2102. (const :tag "Current buffer" nil)
  2103. (function) (variable) (file))
  2104. (choice :tag "Identify target headline by"
  2105. (cons :tag "Specific tag" (const :value :tag) (string))
  2106. (cons :tag "TODO keyword" (const :value :todo) (string))
  2107. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2108. (cons :tag "Level number" (const :value :level) (integer))
  2109. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2110. (defcustom org-refile-target-verify-function nil
  2111. "Function to verify if the headline at point should be a refile target.
  2112. The function will be called without arguments, with point at the
  2113. beginning of the headline. It should return t and leave point
  2114. where it is if the headline is a valid target for refiling.
  2115. If the target should not be selected, the function must return nil.
  2116. In addition to this, it may move point to a place from where the search
  2117. should be continued. For example, the function may decide that the entire
  2118. subtree of the current entry should be excluded and move point to the end
  2119. of the subtree."
  2120. :group 'org-refile
  2121. :type '(choice
  2122. (const nil)
  2123. (function)))
  2124. (defcustom org-refile-use-cache nil
  2125. "Non-nil means cache refile targets to speed up the process.
  2126. \\<org-mode-map>\
  2127. The cache for a particular file will be updated automatically when
  2128. the buffer has been killed, or when any of the marker used for flagging
  2129. refile targets no longer points at a live buffer.
  2130. If you have added new entries to a buffer that might themselves be targets,
  2131. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2132. if you find that easier, \
  2133. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2134. \\[org-refile]'."
  2135. :group 'org-refile
  2136. :version "24.1"
  2137. :type 'boolean)
  2138. (defcustom org-refile-use-outline-path nil
  2139. "Non-nil means provide refile targets as paths.
  2140. So a level 3 headline will be available as level1/level2/level3.
  2141. When the value is `file', also include the file name (without directory)
  2142. into the path. In this case, you can also stop the completion after
  2143. the file name, to get entries inserted as top level in the file.
  2144. When `full-file-path', include the full file path.
  2145. When `buffer-name', use the buffer name."
  2146. :group 'org-refile
  2147. :type '(choice
  2148. (const :tag "Not" nil)
  2149. (const :tag "Yes" t)
  2150. (const :tag "Start with file name" file)
  2151. (const :tag "Start with full file path" full-file-path)
  2152. (const :tag "Start with buffer name" buffer-name)))
  2153. (defcustom org-outline-path-complete-in-steps t
  2154. "Non-nil means complete the outline path in hierarchical steps.
  2155. When Org uses the refile interface to select an outline path (see
  2156. `org-refile-use-outline-path'), the completion of the path can be
  2157. done in a single go, or it can be done in steps down the headline
  2158. hierarchy. Going in steps is probably the best if you do not use
  2159. a special completion package like `ido' or `icicles'. However,
  2160. when using these packages, going in one step can be very fast,
  2161. while still showing the whole path to the entry."
  2162. :group 'org-refile
  2163. :type 'boolean)
  2164. (defcustom org-refile-allow-creating-parent-nodes nil
  2165. "Non-nil means allow the creation of new nodes as refile targets.
  2166. New nodes are then created by adding \"/new node name\" to the completion
  2167. of an existing node. When the value of this variable is `confirm',
  2168. new node creation must be confirmed by the user (recommended).
  2169. When nil, the completion must match an existing entry.
  2170. Note that, if the new heading is not seen by the criteria
  2171. listed in `org-refile-targets', multiple instances of the same
  2172. heading would be created by trying again to file under the new
  2173. heading."
  2174. :group 'org-refile
  2175. :type '(choice
  2176. (const :tag "Never" nil)
  2177. (const :tag "Always" t)
  2178. (const :tag "Prompt for confirmation" confirm)))
  2179. (defcustom org-refile-active-region-within-subtree nil
  2180. "Non-nil means also refile active region within a subtree.
  2181. By default `org-refile' doesn't allow refiling regions if they
  2182. don't contain a set of subtrees, but it might be convenient to
  2183. do so sometimes: in that case, the first line of the region is
  2184. converted to a headline before refiling."
  2185. :group 'org-refile
  2186. :version "24.1"
  2187. :type 'boolean)
  2188. (defgroup org-todo nil
  2189. "Options concerning TODO items in Org mode."
  2190. :tag "Org TODO"
  2191. :group 'org)
  2192. (defgroup org-progress nil
  2193. "Options concerning Progress logging in Org mode."
  2194. :tag "Org Progress"
  2195. :group 'org-time)
  2196. (defvar org-todo-interpretation-widgets
  2197. '((:tag "Sequence (cycling hits every state)" sequence)
  2198. (:tag "Type (cycling directly to DONE)" type))
  2199. "The available interpretation symbols for customizing `org-todo-keywords'.
  2200. Interested libraries should add to this list.")
  2201. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2202. "List of TODO entry keyword sequences and their interpretation.
  2203. \\<org-mode-map>This is a list of sequences.
  2204. Each sequence starts with a symbol, either `sequence' or `type',
  2205. indicating if the keywords should be interpreted as a sequence of
  2206. action steps, or as different types of TODO items. The first
  2207. keywords are states requiring action - these states will select a headline
  2208. for inclusion into the global TODO list Org produces. If one of the
  2209. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2210. signify that no further action is necessary. If \"|\" is not found,
  2211. the last keyword is treated as the only DONE state of the sequence.
  2212. The command `\\[org-todo]' cycles an entry through these states, and one
  2213. additional state where no keyword is present. For details about this
  2214. cycling, see the manual.
  2215. TODO keywords and interpretation can also be set on a per-file basis with
  2216. the special #+SEQ_TODO and #+TYP_TODO lines.
  2217. Each keyword can optionally specify a character for fast state selection
  2218. \(in combination with the variable `org-use-fast-todo-selection')
  2219. and specifiers for state change logging, using the same syntax that
  2220. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2221. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2222. indicates to record a time stamp each time this state is selected.
  2223. Each keyword may also specify if a timestamp or a note should be
  2224. recorded when entering or leaving the state, by adding additional
  2225. characters in the parenthesis after the keyword. This looks like this:
  2226. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2227. record only the time of the state change. With X and Y being either
  2228. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2229. Y when leaving the state if and only if the *target* state does not
  2230. define X. You may omit any of the fast-selection key or X or /Y,
  2231. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2232. For backward compatibility, this variable may also be just a list
  2233. of keywords. In this case the interpretation (sequence or type) will be
  2234. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2235. :group 'org-todo
  2236. :group 'org-keywords
  2237. :type '(choice
  2238. (repeat :tag "Old syntax, just keywords"
  2239. (string :tag "Keyword"))
  2240. (repeat :tag "New syntax"
  2241. (cons
  2242. (choice
  2243. :tag "Interpretation"
  2244. ;;Quick and dirty way to see
  2245. ;;`org-todo-interpretations'. This takes the
  2246. ;;place of item arguments
  2247. :convert-widget
  2248. (lambda (widget)
  2249. (widget-put widget
  2250. :args (mapcar
  2251. (lambda (x)
  2252. (widget-convert
  2253. (cons 'const x)))
  2254. org-todo-interpretation-widgets))
  2255. widget))
  2256. (repeat
  2257. (string :tag "Keyword"))))))
  2258. (defvar-local org-todo-keywords-1 nil
  2259. "All TODO and DONE keywords active in a buffer.")
  2260. (defvar org-todo-keywords-for-agenda nil)
  2261. (defvar org-done-keywords-for-agenda nil)
  2262. (defvar org-todo-keyword-alist-for-agenda nil)
  2263. (defvar org-tag-alist-for-agenda nil
  2264. "Alist of all tags from all agenda files.")
  2265. (defvar org-tag-groups-alist-for-agenda nil
  2266. "Alist of all groups tags from all current agenda files.")
  2267. (defvar-local org-tag-groups-alist nil)
  2268. (defvar org-agenda-contributing-files nil)
  2269. (defvar-local org-current-tag-alist nil
  2270. "Alist of all tag groups in current buffer.
  2271. This variable takes into consideration `org-tag-alist',
  2272. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2273. (defvar-local org-not-done-keywords nil)
  2274. (defvar-local org-done-keywords nil)
  2275. (defvar-local org-todo-heads nil)
  2276. (defvar-local org-todo-sets nil)
  2277. (defvar-local org-todo-log-states nil)
  2278. (defvar-local org-todo-kwd-alist nil)
  2279. (defvar-local org-todo-key-alist nil)
  2280. (defvar-local org-todo-key-trigger nil)
  2281. (defcustom org-todo-interpretation 'sequence
  2282. "Controls how TODO keywords are interpreted.
  2283. This variable is in principle obsolete and is only used for
  2284. backward compatibility, if the interpretation of todo keywords is
  2285. not given already in `org-todo-keywords'. See that variable for
  2286. more information."
  2287. :group 'org-todo
  2288. :group 'org-keywords
  2289. :type '(choice (const sequence)
  2290. (const type)))
  2291. (defcustom org-use-fast-todo-selection t
  2292. "\\<org-mode-map>\
  2293. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2294. This variable describes if and under what circumstances the cycling
  2295. mechanism for TODO keywords will be replaced by a single-key, direct
  2296. selection scheme.
  2297. When nil, fast selection is never used.
  2298. When the symbol `prefix', it will be used when `org-todo' is called
  2299. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2300. in an Org buffer, and
  2301. `\\[universal-argument] t' in an agenda buffer.
  2302. When t, fast selection is used by default. In this case, the prefix
  2303. argument forces cycling instead.
  2304. In all cases, the special interface is only used if access keys have
  2305. actually been assigned by the user, i.e. if keywords in the configuration
  2306. are followed by a letter in parenthesis, like TODO(t)."
  2307. :group 'org-todo
  2308. :type '(choice
  2309. (const :tag "Never" nil)
  2310. (const :tag "By default" t)
  2311. (const :tag "Only with C-u C-c C-t" prefix)))
  2312. (defcustom org-provide-todo-statistics t
  2313. "Non-nil means update todo statistics after insert and toggle.
  2314. ALL-HEADLINES means update todo statistics by including headlines
  2315. with no TODO keyword as well, counting them as not done.
  2316. A list of TODO keywords means the same, but skip keywords that are
  2317. not in this list.
  2318. When set to a list of two lists, the first list contains keywords
  2319. to consider as TODO keywords, the second list contains keywords
  2320. to consider as DONE keywords.
  2321. When this is set, todo statistics is updated in the parent of the
  2322. current entry each time a todo state is changed."
  2323. :group 'org-todo
  2324. :type '(choice
  2325. (const :tag "Yes, only for TODO entries" t)
  2326. (const :tag "Yes, including all entries" all-headlines)
  2327. (repeat :tag "Yes, for TODOs in this list"
  2328. (string :tag "TODO keyword"))
  2329. (list :tag "Yes, for TODOs and DONEs in these lists"
  2330. (repeat (string :tag "TODO keyword"))
  2331. (repeat (string :tag "DONE keyword")))
  2332. (other :tag "No TODO statistics" nil)))
  2333. (defcustom org-hierarchical-todo-statistics t
  2334. "Non-nil means TODO statistics covers just direct children.
  2335. When nil, all entries in the subtree are considered.
  2336. This has only an effect if `org-provide-todo-statistics' is set.
  2337. To set this to nil for only a single subtree, use a COOKIE_DATA
  2338. property and include the word \"recursive\" into the value."
  2339. :group 'org-todo
  2340. :type 'boolean)
  2341. (defcustom org-after-todo-state-change-hook nil
  2342. "Hook which is run after the state of a TODO item was changed.
  2343. The new state (a string with a TODO keyword, or nil) is available in the
  2344. Lisp variable `org-state'."
  2345. :group 'org-todo
  2346. :type 'hook)
  2347. (defvar org-blocker-hook nil
  2348. "Hook for functions that are allowed to block a state change.
  2349. Functions in this hook should not modify the buffer.
  2350. Each function gets as its single argument a property list,
  2351. see `org-trigger-hook' for more information about this list.
  2352. If any of the functions in this hook returns nil, the state change
  2353. is blocked.")
  2354. (defvar org-trigger-hook nil
  2355. "Hook for functions that are triggered by a state change.
  2356. Each function gets as its single argument a property list with at
  2357. least the following elements:
  2358. (:type type-of-change :position pos-at-entry-start
  2359. :from old-state :to new-state)
  2360. Depending on the type, more properties may be present.
  2361. This mechanism is currently implemented for:
  2362. TODO state changes
  2363. ------------------
  2364. :type todo-state-change
  2365. :from previous state (keyword as a string), or nil, or a symbol
  2366. `todo' or `done', to indicate the general type of state.
  2367. :to new state, like in :from")
  2368. (defcustom org-enforce-todo-dependencies nil
  2369. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2370. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2371. be blocked if any prior sibling is not yet done.
  2372. Finally, if the parent is blocked because of ordered siblings of its own,
  2373. the child will also be blocked."
  2374. :set (lambda (var val)
  2375. (set var val)
  2376. (if val
  2377. (add-hook 'org-blocker-hook
  2378. 'org-block-todo-from-children-or-siblings-or-parent)
  2379. (remove-hook 'org-blocker-hook
  2380. 'org-block-todo-from-children-or-siblings-or-parent)))
  2381. :group 'org-todo
  2382. :type 'boolean)
  2383. (defcustom org-enforce-todo-checkbox-dependencies nil
  2384. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2385. When this is nil, checkboxes have no influence on switching TODO states.
  2386. When non-nil, you first need to check off all check boxes before the TODO
  2387. entry can be switched to DONE.
  2388. This variable needs to be set before org.el is loaded, and you need to
  2389. restart Emacs after a change to make the change effective. The only way
  2390. to change is while Emacs is running is through the customize interface."
  2391. :set (lambda (var val)
  2392. (set var val)
  2393. (if val
  2394. (add-hook 'org-blocker-hook
  2395. 'org-block-todo-from-checkboxes)
  2396. (remove-hook 'org-blocker-hook
  2397. 'org-block-todo-from-checkboxes)))
  2398. :group 'org-todo
  2399. :type 'boolean)
  2400. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2401. "Non-nil means inserting a TODO heading is treated as state change.
  2402. So when the command `\\[org-insert-todo-heading]' is used, state change
  2403. logging will apply if appropriate. When nil, the new TODO item will
  2404. be inserted directly, and no logging will take place."
  2405. :group 'org-todo
  2406. :type 'boolean)
  2407. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2408. "Non-nil means switching TODO states with S-cursor counts as state change.
  2409. This is the default behavior. However, setting this to nil allows a
  2410. convenient way to select a TODO state and bypass any logging associated
  2411. with that."
  2412. :group 'org-todo
  2413. :type 'boolean)
  2414. (defcustom org-todo-state-tags-triggers nil
  2415. "Tag changes that should be triggered by TODO state changes.
  2416. This is a list. Each entry is
  2417. (state-change (tag . flag) .......)
  2418. State-change can be a string with a state, and empty string to indicate the
  2419. state that has no TODO keyword, or it can be one of the symbols `todo'
  2420. or `done', meaning any not-done or done state, respectively."
  2421. :group 'org-todo
  2422. :group 'org-tags
  2423. :type '(repeat
  2424. (cons (choice :tag "When changing to"
  2425. (const :tag "Not-done state" todo)
  2426. (const :tag "Done state" done)
  2427. (string :tag "State"))
  2428. (repeat
  2429. (cons :tag "Tag action"
  2430. (string :tag "Tag")
  2431. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2432. (defcustom org-log-done nil
  2433. "Information to record when a task moves to the DONE state.
  2434. Possible values are:
  2435. nil Don't add anything, just change the keyword
  2436. time Add a time stamp to the task
  2437. note Prompt for a note and add it with template `org-log-note-headings'
  2438. This option can also be set with on a per-file-basis with
  2439. #+STARTUP: nologdone
  2440. #+STARTUP: logdone
  2441. #+STARTUP: lognotedone
  2442. You can have local logging settings for a subtree by setting the LOGGING
  2443. property to one or more of these keywords."
  2444. :group 'org-todo
  2445. :group 'org-progress
  2446. :type '(choice
  2447. (const :tag "No logging" nil)
  2448. (const :tag "Record CLOSED timestamp" time)
  2449. (const :tag "Record CLOSED timestamp with note." note)))
  2450. ;; Normalize old uses of org-log-done.
  2451. (cond
  2452. ((eq org-log-done t) (setq org-log-done 'time))
  2453. ((and (listp org-log-done) (memq 'done org-log-done))
  2454. (setq org-log-done 'note)))
  2455. (defcustom org-log-reschedule nil
  2456. "Information to record when the scheduling date of a tasks is modified.
  2457. Possible values are:
  2458. nil Don't add anything, just change the date
  2459. time Add a time stamp to the task
  2460. note Prompt for a note and add it with template `org-log-note-headings'
  2461. This option can also be set with on a per-file-basis with
  2462. #+STARTUP: nologreschedule
  2463. #+STARTUP: logreschedule
  2464. #+STARTUP: lognotereschedule"
  2465. :group 'org-todo
  2466. :group 'org-progress
  2467. :type '(choice
  2468. (const :tag "No logging" nil)
  2469. (const :tag "Record timestamp" time)
  2470. (const :tag "Record timestamp with note." note)))
  2471. (defcustom org-log-redeadline nil
  2472. "Information to record when the deadline date of a tasks is modified.
  2473. Possible values are:
  2474. nil Don't add anything, just change the date
  2475. time Add a time stamp to the task
  2476. note Prompt for a note and add it with template `org-log-note-headings'
  2477. This option can also be set with on a per-file-basis with
  2478. #+STARTUP: nologredeadline
  2479. #+STARTUP: logredeadline
  2480. #+STARTUP: lognoteredeadline
  2481. You can have local logging settings for a subtree by setting the LOGGING
  2482. property to one or more of these keywords."
  2483. :group 'org-todo
  2484. :group 'org-progress
  2485. :type '(choice
  2486. (const :tag "No logging" nil)
  2487. (const :tag "Record timestamp" time)
  2488. (const :tag "Record timestamp with note." note)))
  2489. (defcustom org-log-note-clock-out nil
  2490. "Non-nil means record a note when clocking out of an item.
  2491. This can also be configured on a per-file basis by adding one of
  2492. the following lines anywhere in the buffer:
  2493. #+STARTUP: lognoteclock-out
  2494. #+STARTUP: nolognoteclock-out"
  2495. :group 'org-todo
  2496. :group 'org-progress
  2497. :type 'boolean)
  2498. (defcustom org-log-done-with-time t
  2499. "Non-nil means the CLOSED time stamp will contain date and time.
  2500. When nil, only the date will be recorded."
  2501. :group 'org-progress
  2502. :type 'boolean)
  2503. (defcustom org-log-note-headings
  2504. '((done . "CLOSING NOTE %t")
  2505. (state . "State %-12s from %-12S %t")
  2506. (note . "Note taken on %t")
  2507. (reschedule . "Rescheduled from %S on %t")
  2508. (delschedule . "Not scheduled, was %S on %t")
  2509. (redeadline . "New deadline from %S on %t")
  2510. (deldeadline . "Removed deadline, was %S on %t")
  2511. (refile . "Refiled on %t")
  2512. (clock-out . ""))
  2513. "Headings for notes added to entries.
  2514. The value is an alist, with the car being a symbol indicating the
  2515. note context, and the cdr is the heading to be used. The heading
  2516. may also be the empty string. The following placeholders can be
  2517. used:
  2518. %t a time stamp.
  2519. %T an active time stamp instead the default inactive one
  2520. %d a short-format time stamp.
  2521. %D an active short-format time stamp.
  2522. %s the new TODO state or time stamp (inactive), in double quotes.
  2523. %S the old TODO state or time stamp (inactive), in double quotes.
  2524. %u the user name.
  2525. %U full user name.
  2526. In fact, it is not a good idea to change the `state' entry,
  2527. because Agenda Log mode depends on the format of these entries."
  2528. :group 'org-todo
  2529. :group 'org-progress
  2530. :type '(list :greedy t
  2531. (cons (const :tag "Heading when closing an item" done) string)
  2532. (cons (const :tag
  2533. "Heading when changing todo state (todo sequence only)"
  2534. state) string)
  2535. (cons (const :tag "Heading when just taking a note" note) string)
  2536. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2537. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2538. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2539. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2540. (cons (const :tag "Heading when refiling" refile) string)
  2541. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2542. (unless (assq 'note org-log-note-headings)
  2543. (push '(note . "%t") org-log-note-headings))
  2544. (defcustom org-log-into-drawer nil
  2545. "Non-nil means insert state change notes and time stamps into a drawer.
  2546. When nil, state changes notes will be inserted after the headline and
  2547. any scheduling and clock lines, but not inside a drawer.
  2548. The value of this variable should be the name of the drawer to use.
  2549. LOGBOOK is proposed as the default drawer for this purpose, you can
  2550. also set this to a string to define the drawer of your choice.
  2551. A value of t is also allowed, representing \"LOGBOOK\".
  2552. A value of t or nil can also be set with on a per-file-basis with
  2553. #+STARTUP: logdrawer
  2554. #+STARTUP: nologdrawer
  2555. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2556. will be ignored.
  2557. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2558. a subtree.
  2559. Do not check directly this variable in a Lisp program. Call
  2560. function `org-log-into-drawer' instead."
  2561. :group 'org-todo
  2562. :group 'org-progress
  2563. :type '(choice
  2564. (const :tag "Not into a drawer" nil)
  2565. (const :tag "LOGBOOK" t)
  2566. (string :tag "Other")))
  2567. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2568. (defun org-log-into-drawer ()
  2569. "Name of the log drawer, as a string, or nil.
  2570. This is the value of `org-log-into-drawer'. However, if the
  2571. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2572. be used instead of the default value."
  2573. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2574. (cond ((equal p "nil") nil)
  2575. ((equal p "t") "LOGBOOK")
  2576. ((stringp p) p)
  2577. (p "LOGBOOK")
  2578. ((stringp org-log-into-drawer) org-log-into-drawer)
  2579. (org-log-into-drawer "LOGBOOK"))))
  2580. (defcustom org-log-state-notes-insert-after-drawers nil
  2581. "Non-nil means insert state change notes after any drawers in entry.
  2582. Only the drawers that *immediately* follow the headline and the
  2583. deadline/scheduled line are skipped.
  2584. When nil, insert notes right after the heading and perhaps the line
  2585. with deadline/scheduling if present.
  2586. This variable will have no effect if `org-log-into-drawer' is
  2587. set."
  2588. :group 'org-todo
  2589. :group 'org-progress
  2590. :type 'boolean)
  2591. (defcustom org-log-states-order-reversed t
  2592. "Non-nil means the latest state note will be directly after heading.
  2593. When nil, the state change notes will be ordered according to time.
  2594. This option can also be set with on a per-file-basis with
  2595. #+STARTUP: logstatesreversed
  2596. #+STARTUP: nologstatesreversed"
  2597. :group 'org-todo
  2598. :group 'org-progress
  2599. :type 'boolean)
  2600. (defcustom org-todo-repeat-to-state nil
  2601. "The TODO state to which a repeater should return the repeating task.
  2602. By default this is the first task in a TODO sequence, or the previous state
  2603. in a TODO_TYP set. But you can specify another task here.
  2604. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2605. :group 'org-todo
  2606. :version "24.1"
  2607. :type '(choice (const :tag "Head of sequence" nil)
  2608. (string :tag "Specific state")))
  2609. (defcustom org-log-repeat 'time
  2610. "Non-nil means record moving through the DONE state when triggering repeat.
  2611. An auto-repeating task is immediately switched back to TODO when
  2612. marked DONE. If you are not logging state changes (by adding \"@\"
  2613. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2614. record a closing note, there will be no record of the task moving
  2615. through DONE. This variable forces taking a note anyway.
  2616. nil Don't force a record
  2617. time Record a time stamp
  2618. note Prompt for a note and add it with template `org-log-note-headings'
  2619. This option can also be set with on a per-file-basis with
  2620. #+STARTUP: nologrepeat
  2621. #+STARTUP: logrepeat
  2622. #+STARTUP: lognoterepeat
  2623. You can have local logging settings for a subtree by setting the LOGGING
  2624. property to one or more of these keywords."
  2625. :group 'org-todo
  2626. :group 'org-progress
  2627. :type '(choice
  2628. (const :tag "Don't force a record" nil)
  2629. (const :tag "Force recording the DONE state" time)
  2630. (const :tag "Force recording a note with the DONE state" note)))
  2631. (defgroup org-priorities nil
  2632. "Priorities in Org mode."
  2633. :tag "Org Priorities"
  2634. :group 'org-todo)
  2635. (defcustom org-enable-priority-commands t
  2636. "Non-nil means priority commands are active.
  2637. When nil, these commands will be disabled, so that you never accidentally
  2638. set a priority."
  2639. :group 'org-priorities
  2640. :type 'boolean)
  2641. (defcustom org-highest-priority ?A
  2642. "The highest priority of TODO items. A character like ?A, ?B etc.
  2643. Must have a smaller ASCII number than `org-lowest-priority'."
  2644. :group 'org-priorities
  2645. :type 'character)
  2646. (defcustom org-lowest-priority ?C
  2647. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2648. Must have a larger ASCII number than `org-highest-priority'."
  2649. :group 'org-priorities
  2650. :type 'character)
  2651. (defcustom org-default-priority ?B
  2652. "The default priority of TODO items.
  2653. This is the priority an item gets if no explicit priority is given.
  2654. When starting to cycle on an empty priority the first step in the cycle
  2655. depends on `org-priority-start-cycle-with-default'. The resulting first
  2656. step priority must not exceed the range from `org-highest-priority' to
  2657. `org-lowest-priority' which means that `org-default-priority' has to be
  2658. in this range exclusive or inclusive the range boundaries. Else the
  2659. first step refuses to set the default and the second will fall back
  2660. to (depending on the command used) the highest or lowest priority."
  2661. :group 'org-priorities
  2662. :type 'character)
  2663. (defcustom org-priority-start-cycle-with-default t
  2664. "Non-nil means start with default priority when starting to cycle.
  2665. When this is nil, the first step in the cycle will be (depending on the
  2666. command used) one higher or lower than the default priority.
  2667. See also `org-default-priority'."
  2668. :group 'org-priorities
  2669. :type 'boolean)
  2670. (defcustom org-get-priority-function nil
  2671. "Function to extract the priority from a string.
  2672. The string is normally the headline. If this is nil Org computes the
  2673. priority from the priority cookie like [#A] in the headline. It returns
  2674. an integer, increasing by 1000 for each priority level.
  2675. The user can set a different function here, which should take a string
  2676. as an argument and return the numeric priority."
  2677. :group 'org-priorities
  2678. :version "24.1"
  2679. :type '(choice
  2680. (const nil)
  2681. (function)))
  2682. (defgroup org-time nil
  2683. "Options concerning time stamps and deadlines in Org mode."
  2684. :tag "Org Time"
  2685. :group 'org)
  2686. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2687. "Number of minutes to round time stamps to.
  2688. \\<org-mode-map>\
  2689. These are two values, the first applies when first creating a time stamp.
  2690. The second applies when changing it with the commands `S-up' and `S-down'.
  2691. When changing the time stamp, this means that it will change in steps
  2692. of N minutes, as given by the second value.
  2693. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2694. numbers should be factors of 60, so for example 5, 10, 15.
  2695. When this is larger than 1, you can still force an exact time stamp by using
  2696. a double prefix argument to a time stamp command like \
  2697. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2698. and by using a prefix arg to `S-up/down' to specify the exact number
  2699. of minutes to shift."
  2700. :group 'org-time
  2701. :get (lambda (var) ; Make sure both elements are there
  2702. (if (integerp (default-value var))
  2703. (list (default-value var) 5)
  2704. (default-value var)))
  2705. :type '(list
  2706. (integer :tag "when inserting times")
  2707. (integer :tag "when modifying times")))
  2708. ;; Normalize old customizations of this variable.
  2709. (when (integerp org-time-stamp-rounding-minutes)
  2710. (setq org-time-stamp-rounding-minutes
  2711. (list org-time-stamp-rounding-minutes
  2712. org-time-stamp-rounding-minutes)))
  2713. (defcustom org-display-custom-times nil
  2714. "Non-nil means overlay custom formats over all time stamps.
  2715. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2716. To turn this on on a per-file basis, insert anywhere in the file:
  2717. #+STARTUP: customtime"
  2718. :group 'org-time
  2719. :set 'set-default
  2720. :type 'sexp)
  2721. (make-variable-buffer-local 'org-display-custom-times)
  2722. (defcustom org-time-stamp-custom-formats
  2723. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2724. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2725. These are overlaid over the default ISO format if the variable
  2726. `org-display-custom-times' is set. Time like %H:%M should be at the
  2727. end of the second format. The custom formats are also honored by export
  2728. commands, if custom time display is turned on at the time of export."
  2729. :group 'org-time
  2730. :type 'sexp)
  2731. (defun org-time-stamp-format (&optional long inactive)
  2732. "Get the right format for a time string."
  2733. (let ((f (if long (cdr org-time-stamp-formats)
  2734. (car org-time-stamp-formats))))
  2735. (if inactive
  2736. (concat "[" (substring f 1 -1) "]")
  2737. f)))
  2738. (defcustom org-deadline-warning-days 14
  2739. "Number of days before expiration during which a deadline becomes active.
  2740. This variable governs the display in sparse trees and in the agenda.
  2741. When 0 or negative, it means use this number (the absolute value of it)
  2742. even if a deadline has a different individual lead time specified.
  2743. Custom commands can set this variable in the options section."
  2744. :group 'org-time
  2745. :group 'org-agenda-daily/weekly
  2746. :type 'integer)
  2747. (defcustom org-scheduled-delay-days 0
  2748. "Number of days before a scheduled item becomes active.
  2749. This variable governs the display in sparse trees and in the agenda.
  2750. The default value (i.e. 0) means: don't delay scheduled item.
  2751. When negative, it means use this number (the absolute value of it)
  2752. even if a scheduled item has a different individual delay time
  2753. specified.
  2754. Custom commands can set this variable in the options section."
  2755. :group 'org-time
  2756. :group 'org-agenda-daily/weekly
  2757. :version "24.4"
  2758. :package-version '(Org . "8.0")
  2759. :type 'integer)
  2760. (defcustom org-read-date-prefer-future t
  2761. "Non-nil means assume future for incomplete date input from user.
  2762. This affects the following situations:
  2763. 1. The user gives a month but not a year.
  2764. For example, if it is April and you enter \"feb 2\", this will be read
  2765. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2766. 2. The user gives a day, but no month.
  2767. For example, if today is the 15th, and you enter \"3\", Org will read
  2768. this as the third of *next* month. However, if you enter \"17\",
  2769. it will be considered as *this* month.
  2770. If you set this variable to the symbol `time', then also the following
  2771. will work:
  2772. 3. If the user gives a time.
  2773. If the time is before now, it will be interpreted as tomorrow.
  2774. Currently none of this works for ISO week specifications.
  2775. When this option is nil, the current day, month and year will always be
  2776. used as defaults.
  2777. See also `org-agenda-jump-prefer-future'."
  2778. :group 'org-time
  2779. :type '(choice
  2780. (const :tag "Never" nil)
  2781. (const :tag "Check month and day" t)
  2782. (const :tag "Check month, day, and time" time)))
  2783. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2784. "Should the agenda jump command prefer the future for incomplete dates?
  2785. The default is to do the same as configured in `org-read-date-prefer-future'.
  2786. But you can also set a deviating value here.
  2787. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2788. :group 'org-agenda
  2789. :group 'org-time
  2790. :version "24.1"
  2791. :type '(choice
  2792. (const :tag "Use org-read-date-prefer-future"
  2793. org-read-date-prefer-future)
  2794. (const :tag "Never" nil)
  2795. (const :tag "Always" t)))
  2796. (defcustom org-read-date-force-compatible-dates t
  2797. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2798. Depending on the system Emacs is running on, certain dates cannot
  2799. be represented with the type used internally to represent time.
  2800. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2801. correctly. Some systems allow for earlier dates, some for later,
  2802. some for both. One way to find out it to insert any date into an
  2803. Org buffer, putting the cursor on the year and hitting S-up and
  2804. S-down to test the range.
  2805. When this variable is set to t, the date/time prompt will not let
  2806. you specify dates outside the 1970-2037 range, so it is certain that
  2807. these dates will work in whatever version of Emacs you are
  2808. running, and also that you can move a file from one Emacs implementation
  2809. to another. WHenever Org is forcing the year for you, it will display
  2810. a message and beep.
  2811. When this variable is nil, Org will check if the date is
  2812. representable in the specific Emacs implementation you are using.
  2813. If not, it will force a year, usually the current year, and beep
  2814. to remind you. Currently this setting is not recommended because
  2815. the likelihood that you will open your Org files in an Emacs that
  2816. has limited date range is not negligible.
  2817. A workaround for this problem is to use diary sexp dates for time
  2818. stamps outside of this range."
  2819. :group 'org-time
  2820. :version "24.1"
  2821. :type 'boolean)
  2822. (defcustom org-read-date-display-live t
  2823. "Non-nil means display current interpretation of date prompt live.
  2824. This display will be in an overlay, in the minibuffer."
  2825. :group 'org-time
  2826. :type 'boolean)
  2827. (defcustom org-read-date-popup-calendar t
  2828. "Non-nil means pop up a calendar when prompting for a date.
  2829. In the calendar, the date can be selected with mouse-1. However, the
  2830. minibuffer will also be active, and you can simply enter the date as well.
  2831. When nil, only the minibuffer will be available."
  2832. :group 'org-time
  2833. :type 'boolean)
  2834. (defvaralias 'org-popup-calendar-for-date-prompt
  2835. 'org-read-date-popup-calendar)
  2836. (defcustom org-extend-today-until 0
  2837. "The hour when your day really ends. Must be an integer.
  2838. This has influence for the following applications:
  2839. - When switching the agenda to \"today\". It it is still earlier than
  2840. the time given here, the day recognized as TODAY is actually yesterday.
  2841. - When a date is read from the user and it is still before the time given
  2842. here, the current date and time will be assumed to be yesterday, 23:59.
  2843. Also, timestamps inserted in capture templates follow this rule.
  2844. IMPORTANT: This is a feature whose implementation is and likely will
  2845. remain incomplete. Really, it is only here because past midnight seems to
  2846. be the favorite working time of John Wiegley :-)"
  2847. :group 'org-time
  2848. :type 'integer)
  2849. (defcustom org-use-effective-time nil
  2850. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2851. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2852. \"effective time\" of any timestamps between midnight and 8am will be
  2853. 23:59 of the previous day."
  2854. :group 'org-time
  2855. :version "24.1"
  2856. :type 'boolean)
  2857. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2858. "When non-nil, use the last clock out time for `org-todo'.
  2859. Note that this option has precedence over the combined use of
  2860. `org-use-effective-time' and `org-extend-today-until'."
  2861. :group 'org-time
  2862. :version "24.4"
  2863. :package-version '(Org . "8.0")
  2864. :type 'boolean)
  2865. (defcustom org-edit-timestamp-down-means-later nil
  2866. "Non-nil means S-down will increase the time in a time stamp.
  2867. When nil, S-up will increase."
  2868. :group 'org-time
  2869. :type 'boolean)
  2870. (defcustom org-calendar-follow-timestamp-change t
  2871. "Non-nil means make the calendar window follow timestamp changes.
  2872. When a timestamp is modified and the calendar window is visible, it will be
  2873. moved to the new date."
  2874. :group 'org-time
  2875. :type 'boolean)
  2876. (defgroup org-tags nil
  2877. "Options concerning tags in Org mode."
  2878. :tag "Org Tags"
  2879. :group 'org)
  2880. (defcustom org-tag-alist nil
  2881. "Default tags available in Org files.
  2882. The value of this variable is an alist. Associations either:
  2883. (TAG)
  2884. (TAG . SELECT)
  2885. (SPECIAL)
  2886. where TAG is a tag as a string, SELECT is character, used to
  2887. select that tag through the fast tag selection interface, and
  2888. SPECIAL is one of the following keywords: `:startgroup',
  2889. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2890. `:newline'. These keywords are used to define a hierarchy of
  2891. tags. See manual for details.
  2892. When this variable is nil, Org mode bases tag input on what is
  2893. already in the buffer. The value can be overridden locally by
  2894. using a TAGS keyword, e.g.,
  2895. #+TAGS: tag1 tag2
  2896. See also `org-tag-persistent-alist' to sidestep this behavior."
  2897. :group 'org-tags
  2898. :type '(repeat
  2899. (choice
  2900. (cons :tag "Tag with key"
  2901. (string :tag "Tag name")
  2902. (character :tag "Access char"))
  2903. (list :tag "Tag" (string :tag "Tag name"))
  2904. (const :tag "Start radio group" (:startgroup))
  2905. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2906. (const :tag "Group tags delimiter" (:grouptags))
  2907. (const :tag "End radio group" (:endgroup))
  2908. (const :tag "End tag group, non distinct" (:endgrouptag))
  2909. (const :tag "New line" (:newline)))))
  2910. (defcustom org-tag-persistent-alist nil
  2911. "Tags always available in Org files.
  2912. The value of this variable is an alist. Associations either:
  2913. (TAG)
  2914. (TAG . SELECT)
  2915. (SPECIAL)
  2916. where TAG is a tag as a string, SELECT is a character, used to
  2917. select that tag through the fast tag selection interface, and
  2918. SPECIAL is one of the following keywords: `:startgroup',
  2919. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2920. `:newline'. These keywords are used to define a hierarchy of
  2921. tags. See manual for details.
  2922. Unlike to `org-tag-alist', tags defined in this variable do not
  2923. depend on a local TAGS keyword. Instead, to disable these tags
  2924. on a per-file basis, insert anywhere in the file:
  2925. #+STARTUP: noptag"
  2926. :group 'org-tags
  2927. :type '(repeat
  2928. (choice
  2929. (cons :tag "Tag with key"
  2930. (string :tag "Tag name")
  2931. (character :tag "Access char"))
  2932. (list :tag "Tag" (string :tag "Tag name"))
  2933. (const :tag "Start radio group" (:startgroup))
  2934. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2935. (const :tag "Group tags delimiter" (:grouptags))
  2936. (const :tag "End radio group" (:endgroup))
  2937. (const :tag "End tag group, non distinct" (:endgrouptag))
  2938. (const :tag "New line" (:newline)))))
  2939. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2940. "If non-nil, always offer completion for all tags of all agenda files.
  2941. Instead of customizing this variable directly, you might want to
  2942. set it locally for capture buffers, because there no list of
  2943. tags in that file can be created dynamically (there are none).
  2944. (add-hook \\='org-capture-mode-hook
  2945. (lambda ()
  2946. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2947. :group 'org-tags
  2948. :version "24.1"
  2949. :type 'boolean)
  2950. (defvar org-file-tags nil
  2951. "List of tags that can be inherited by all entries in the file.
  2952. The tags will be inherited if the variable `org-use-tag-inheritance'
  2953. says they should be.
  2954. This variable is populated from #+FILETAGS lines.")
  2955. (defcustom org-use-fast-tag-selection 'auto
  2956. "Non-nil means use fast tag selection scheme.
  2957. This is a special interface to select and deselect tags with single keys.
  2958. When nil, fast selection is never used.
  2959. When the symbol `auto', fast selection is used if and only if selection
  2960. characters for tags have been configured, either through the variable
  2961. `org-tag-alist' or through a #+TAGS line in the buffer.
  2962. When t, fast selection is always used and selection keys are assigned
  2963. automatically if necessary."
  2964. :group 'org-tags
  2965. :type '(choice
  2966. (const :tag "Always" t)
  2967. (const :tag "Never" nil)
  2968. (const :tag "When selection characters are configured" auto)))
  2969. (defcustom org-fast-tag-selection-single-key nil
  2970. "Non-nil means fast tag selection exits after first change.
  2971. When nil, you have to press RET to exit it.
  2972. During fast tag selection, you can toggle this flag with `C-c'.
  2973. This variable can also have the value `expert'. In this case, the window
  2974. displaying the tags menu is not even shown, until you press C-c again."
  2975. :group 'org-tags
  2976. :type '(choice
  2977. (const :tag "No" nil)
  2978. (const :tag "Yes" t)
  2979. (const :tag "Expert" expert)))
  2980. (defvar org-fast-tag-selection-include-todo nil
  2981. "Non-nil means fast tags selection interface will also offer TODO states.
  2982. This is an undocumented feature, you should not rely on it.")
  2983. (defcustom org-tags-column -77
  2984. "The column to which tags should be indented in a headline.
  2985. If this number is positive, it specifies the column. If it is negative,
  2986. it means that the tags should be flushright to that column. For example,
  2987. -80 works well for a normal 80 character screen.
  2988. When 0, place tags directly after headline text, with only one space in
  2989. between."
  2990. :group 'org-tags
  2991. :type 'integer)
  2992. (defcustom org-auto-align-tags t
  2993. "Non-nil keeps tags aligned when modifying headlines.
  2994. Some operations (i.e. demoting) change the length of a headline and
  2995. therefore shift the tags around. With this option turned on, after
  2996. each such operation the tags are again aligned to `org-tags-column'."
  2997. :group 'org-tags
  2998. :type 'boolean)
  2999. (defcustom org-use-tag-inheritance t
  3000. "Non-nil means tags in levels apply also for sublevels.
  3001. When nil, only the tags directly given in a specific line apply there.
  3002. This may also be a list of tags that should be inherited, or a regexp that
  3003. matches tags that should be inherited. Additional control is possible
  3004. with the variable `org-tags-exclude-from-inheritance' which gives an
  3005. explicit list of tags to be excluded from inheritance, even if the value of
  3006. `org-use-tag-inheritance' would select it for inheritance.
  3007. If this option is t, a match early-on in a tree can lead to a large
  3008. number of matches in the subtree when constructing the agenda or creating
  3009. a sparse tree. If you only want to see the first match in a tree during
  3010. a search, check out the variable `org-tags-match-list-sublevels'."
  3011. :group 'org-tags
  3012. :type '(choice
  3013. (const :tag "Not" nil)
  3014. (const :tag "Always" t)
  3015. (repeat :tag "Specific tags" (string :tag "Tag"))
  3016. (regexp :tag "Tags matched by regexp")))
  3017. (defcustom org-tags-exclude-from-inheritance nil
  3018. "List of tags that should never be inherited.
  3019. This is a way to exclude a few tags from inheritance. For way to do
  3020. the opposite, to actively allow inheritance for selected tags,
  3021. see the variable `org-use-tag-inheritance'."
  3022. :group 'org-tags
  3023. :type '(repeat (string :tag "Tag")))
  3024. (defun org-tag-inherit-p (tag)
  3025. "Check if TAG is one that should be inherited."
  3026. (cond
  3027. ((member tag org-tags-exclude-from-inheritance) nil)
  3028. ((eq org-use-tag-inheritance t) t)
  3029. ((not org-use-tag-inheritance) nil)
  3030. ((stringp org-use-tag-inheritance)
  3031. (string-match org-use-tag-inheritance tag))
  3032. ((listp org-use-tag-inheritance)
  3033. (member tag org-use-tag-inheritance))
  3034. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3035. (defcustom org-tags-match-list-sublevels t
  3036. "Non-nil means list also sublevels of headlines matching a search.
  3037. This variable applies to tags/property searches, and also to stuck
  3038. projects because this search is based on a tags match as well.
  3039. When set to the symbol `indented', sublevels are indented with
  3040. leading dots.
  3041. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3042. the sublevels of a headline matching a tag search often also match
  3043. the same search. Listing all of them can create very long lists.
  3044. Setting this variable to nil causes subtrees of a match to be skipped.
  3045. This variable is semi-obsolete and probably should always be true. It
  3046. is better to limit inheritance to certain tags using the variables
  3047. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3048. :group 'org-tags
  3049. :type '(choice
  3050. (const :tag "No, don't list them" nil)
  3051. (const :tag "Yes, do list them" t)
  3052. (const :tag "List them, indented with leading dots" indented)))
  3053. (defcustom org-tags-sort-function nil
  3054. "When set, tags are sorted using this function as a comparator."
  3055. :group 'org-tags
  3056. :type '(choice
  3057. (const :tag "No sorting" nil)
  3058. (const :tag "Alphabetical" string<)
  3059. (const :tag "Reverse alphabetical" string>)
  3060. (function :tag "Custom function" nil)))
  3061. (defvar org-tags-history nil
  3062. "History of minibuffer reads for tags.")
  3063. (defvar org-last-tags-completion-table nil
  3064. "The last used completion table for tags.")
  3065. (defvar org-after-tags-change-hook nil
  3066. "Hook that is run after the tags in a line have changed.")
  3067. (defgroup org-properties nil
  3068. "Options concerning properties in Org mode."
  3069. :tag "Org Properties"
  3070. :group 'org)
  3071. (defcustom org-property-format "%-10s %s"
  3072. "How property key/value pairs should be formatted by `indent-line'.
  3073. When `indent-line' hits a property definition, it will format the line
  3074. according to this format, mainly to make sure that the values are
  3075. lined-up with respect to each other."
  3076. :group 'org-properties
  3077. :type 'string)
  3078. (defcustom org-properties-postprocess-alist nil
  3079. "Alist of properties and functions to adjust inserted values.
  3080. Elements of this alist must be of the form
  3081. ([string] [function])
  3082. where [string] must be a property name and [function] must be a
  3083. lambda expression: this lambda expression must take one argument,
  3084. the value to adjust, and return the new value as a string.
  3085. For example, this element will allow the property \"Remaining\"
  3086. to be updated wrt the relation between the \"Effort\" property
  3087. and the clock summary:
  3088. ((\"Remaining\" (lambda(value)
  3089. (let ((clocksum (org-clock-sum-current-item))
  3090. (effort (org-duration-to-minutes
  3091. (org-entry-get (point) \"Effort\"))))
  3092. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3093. :group 'org-properties
  3094. :version "24.1"
  3095. :type '(alist :key-type (string :tag "Property")
  3096. :value-type (function :tag "Function")))
  3097. (defcustom org-use-property-inheritance nil
  3098. "Non-nil means properties apply also for sublevels.
  3099. This setting is chiefly used during property searches. Turning it on can
  3100. cause significant overhead when doing a search, which is why it is not
  3101. on by default.
  3102. When nil, only the properties directly given in the current entry count.
  3103. When t, every property is inherited. The value may also be a list of
  3104. properties that should have inheritance, or a regular expression matching
  3105. properties that should be inherited.
  3106. However, note that some special properties use inheritance under special
  3107. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3108. and the properties ending in \"_ALL\" when they are used as descriptor
  3109. for valid values of a property.
  3110. Note for programmers:
  3111. When querying an entry with `org-entry-get', you can control if inheritance
  3112. should be used. By default, `org-entry-get' looks only at the local
  3113. properties. You can request inheritance by setting the inherit argument
  3114. to t (to force inheritance) or to `selective' (to respect the setting
  3115. in this variable)."
  3116. :group 'org-properties
  3117. :type '(choice
  3118. (const :tag "Not" nil)
  3119. (const :tag "Always" t)
  3120. (repeat :tag "Specific properties" (string :tag "Property"))
  3121. (regexp :tag "Properties matched by regexp")))
  3122. (defun org-property-inherit-p (property)
  3123. "Return a non-nil value if PROPERTY should be inherited."
  3124. (cond
  3125. ((eq org-use-property-inheritance t) t)
  3126. ((not org-use-property-inheritance) nil)
  3127. ((stringp org-use-property-inheritance)
  3128. (string-match org-use-property-inheritance property))
  3129. ((listp org-use-property-inheritance)
  3130. (member-ignore-case property org-use-property-inheritance))
  3131. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3132. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3133. "The default column format, if no other format has been defined.
  3134. This variable can be set on the per-file basis by inserting a line
  3135. #+COLUMNS: %25ITEM ....."
  3136. :group 'org-properties
  3137. :type 'string)
  3138. (defcustom org-columns-ellipses ".."
  3139. "The ellipses to be used when a field in column view is truncated.
  3140. When this is the empty string, as many characters as possible are shown,
  3141. but then there will be no visual indication that the field has been truncated.
  3142. When this is a string of length N, the last N characters of a truncated
  3143. field are replaced by this string. If the column is narrower than the
  3144. ellipses string, only part of the ellipses string will be shown."
  3145. :group 'org-properties
  3146. :type 'string)
  3147. (defconst org-global-properties-fixed
  3148. '(("VISIBILITY_ALL" . "folded children content all")
  3149. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3150. "List of property/value pairs that can be inherited by any entry.
  3151. These are fixed values, for the preset properties. The user variable
  3152. that can be used to add to this list is `org-global-properties'.
  3153. The entries in this list are cons cells where the car is a property
  3154. name and cdr is a string with the value. If the value represents
  3155. multiple items like an \"_ALL\" property, separate the items by
  3156. spaces.")
  3157. (defcustom org-global-properties nil
  3158. "List of property/value pairs that can be inherited by any entry.
  3159. This list will be combined with the constant `org-global-properties-fixed'.
  3160. The entries in this list are cons cells where the car is a property
  3161. name and cdr is a string with the value.
  3162. You can set buffer-local values for the same purpose in the variable
  3163. `org-file-properties' this by adding lines like
  3164. #+PROPERTY: NAME VALUE"
  3165. :group 'org-properties
  3166. :type '(repeat
  3167. (cons (string :tag "Property")
  3168. (string :tag "Value"))))
  3169. (defvar-local org-file-properties nil
  3170. "List of property/value pairs that can be inherited by any entry.
  3171. Valid for the current buffer.
  3172. This variable is populated from #+PROPERTY lines.")
  3173. (defgroup org-agenda nil
  3174. "Options concerning agenda views in Org mode."
  3175. :tag "Org Agenda"
  3176. :group 'org)
  3177. (defvar-local org-category nil
  3178. "Variable used by org files to set a category for agenda display.
  3179. Such files should use a file variable to set it, for example
  3180. # -*- mode: org; org-category: \"ELisp\"
  3181. or contain a special line
  3182. #+CATEGORY: ELisp
  3183. If the file does not specify a category, then file's base name
  3184. is used instead.")
  3185. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3186. (defcustom org-agenda-files nil
  3187. "The files to be used for agenda display.
  3188. If an entry is a directory, all files in that directory that are matched
  3189. by `org-agenda-file-regexp' will be part of the file list.
  3190. If the value of the variable is not a list but a single file name, then
  3191. the list of agenda files is actually stored and maintained in that file,
  3192. one agenda file per line. In this file paths can be given relative to
  3193. `org-directory'. Tilde expansion and environment variable substitution
  3194. are also made.
  3195. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3196. and removed with `\\[org-remove-file]'."
  3197. :group 'org-agenda
  3198. :type '(choice
  3199. (repeat :tag "List of files and directories" file)
  3200. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3201. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3202. "Regular expression to match files for `org-agenda-files'.
  3203. If any element in the list in that variable contains a directory instead
  3204. of a normal file, all files in that directory that are matched by this
  3205. regular expression will be included."
  3206. :group 'org-agenda
  3207. :type 'regexp)
  3208. (defcustom org-agenda-text-search-extra-files nil
  3209. "List of extra files to be searched by text search commands.
  3210. These files will be searched in addition to the agenda files by the
  3211. commands `org-search-view' (`\\[org-agenda] s') \
  3212. and `org-occur-in-agenda-files'.
  3213. Note that these files will only be searched for text search commands,
  3214. not for the other agenda views like todo lists, tag searches or the weekly
  3215. agenda. This variable is intended to list notes and possibly archive files
  3216. that should also be searched by these two commands.
  3217. In fact, if the first element in the list is the symbol `agenda-archives',
  3218. then all archive files of all agenda files will be added to the search
  3219. scope."
  3220. :group 'org-agenda
  3221. :type '(set :greedy t
  3222. (const :tag "Agenda Archives" agenda-archives)
  3223. (repeat :inline t (file))))
  3224. (defvaralias 'org-agenda-multi-occur-extra-files
  3225. 'org-agenda-text-search-extra-files)
  3226. (defcustom org-agenda-skip-unavailable-files nil
  3227. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3228. A nil value means to remove them, after a query, from the list."
  3229. :group 'org-agenda
  3230. :type 'boolean)
  3231. (defcustom org-calendar-to-agenda-key [?c]
  3232. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3233. The command `org-calendar-goto-agenda' will be bound to this key. The
  3234. default is the character `c' because then `c' can be used to switch back and
  3235. forth between agenda and calendar."
  3236. :group 'org-agenda
  3237. :type 'sexp)
  3238. (defcustom org-calendar-insert-diary-entry-key [?i]
  3239. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3240. This option is irrelevant until `org-agenda-diary-file' has been configured
  3241. to point to an Org file. When that is the case, the command
  3242. `org-agenda-diary-entry' will be bound to the key given here, by default
  3243. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3244. if you want to continue doing this, you need to change this to a different
  3245. key."
  3246. :group 'org-agenda
  3247. :type 'sexp)
  3248. (defcustom org-agenda-diary-file 'diary-file
  3249. "File to which to add new entries with the `i' key in agenda and calendar.
  3250. When this is the symbol `diary-file', the functionality in the Emacs
  3251. calendar will be used to add entries to the `diary-file'. But when this
  3252. points to a file, `org-agenda-diary-entry' will be used instead."
  3253. :group 'org-agenda
  3254. :type '(choice
  3255. (const :tag "The standard Emacs diary file" diary-file)
  3256. (file :tag "Special Org file diary entries")))
  3257. (eval-after-load "calendar"
  3258. '(progn
  3259. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3260. 'org-calendar-goto-agenda)
  3261. (add-hook 'calendar-mode-hook
  3262. (lambda ()
  3263. (unless (eq org-agenda-diary-file 'diary-file)
  3264. (define-key calendar-mode-map
  3265. org-calendar-insert-diary-entry-key
  3266. 'org-agenda-diary-entry))))))
  3267. (defgroup org-latex nil
  3268. "Options for embedding LaTeX code into Org mode."
  3269. :tag "Org LaTeX"
  3270. :group 'org)
  3271. (defcustom org-format-latex-options
  3272. '(:foreground default :background default :scale 1.0
  3273. :html-foreground "Black" :html-background "Transparent"
  3274. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3275. "Options for creating images from LaTeX fragments.
  3276. This is a property list with the following properties:
  3277. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3278. `default' means use the foreground of the default face.
  3279. `auto' means use the foreground from the text face.
  3280. :background the background color, or \"Transparent\".
  3281. `default' means use the background of the default face.
  3282. `auto' means use the background from the text face.
  3283. :scale a scaling factor for the size of the images, to get more pixels
  3284. :html-foreground, :html-background, :html-scale
  3285. the same numbers for HTML export.
  3286. :matchers a list indicating which matchers should be used to
  3287. find LaTeX fragments. Valid members of this list are:
  3288. \"begin\" find environments
  3289. \"$1\" find single characters surrounded by $.$
  3290. \"$\" find math expressions surrounded by $...$
  3291. \"$$\" find math expressions surrounded by $$....$$
  3292. \"\\(\" find math expressions surrounded by \\(...\\)
  3293. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3294. :group 'org-latex
  3295. :type 'plist)
  3296. (defcustom org-format-latex-signal-error t
  3297. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3298. When nil, just push out a message."
  3299. :group 'org-latex
  3300. :version "24.1"
  3301. :type 'boolean)
  3302. (defcustom org-latex-to-mathml-jar-file nil
  3303. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3304. Use this to specify additional executable file say a jar file.
  3305. When using MathToWeb as the converter, specify the full-path to
  3306. your mathtoweb.jar file."
  3307. :group 'org-latex
  3308. :version "24.1"
  3309. :type '(choice
  3310. (const :tag "None" nil)
  3311. (file :tag "JAR file" :must-match t)))
  3312. (defcustom org-latex-to-mathml-convert-command nil
  3313. "Command to convert LaTeX fragments to MathML.
  3314. Replace format-specifiers in the command as noted below and use
  3315. `shell-command' to convert LaTeX to MathML.
  3316. %j: Executable file in fully expanded form as specified by
  3317. `org-latex-to-mathml-jar-file'.
  3318. %I: Input LaTeX file in fully expanded form.
  3319. %i: The latex fragment to be converted.
  3320. %o: Output MathML file.
  3321. This command is used by `org-create-math-formula'.
  3322. When using MathToWeb as the converter, set this option to
  3323. \"java -jar %j -unicode -force -df %o %I\".
  3324. When using LaTeXML set this option to
  3325. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3326. :group 'org-latex
  3327. :version "24.1"
  3328. :type '(choice
  3329. (const :tag "None" nil)
  3330. (string :tag "\nShell command")))
  3331. (defcustom org-preview-latex-default-process 'dvipng
  3332. "The default process to convert LaTeX fragments to image files.
  3333. All available processes and theirs documents can be found in
  3334. `org-preview-latex-process-alist', which see."
  3335. :group 'org-latex
  3336. :version "26.1"
  3337. :package-version '(Org . "9.0")
  3338. :type 'symbol)
  3339. (defcustom org-preview-latex-process-alist
  3340. '((dvipng
  3341. :programs ("latex" "dvipng")
  3342. :description "dvi > png"
  3343. :message "you need to install the programs: latex and dvipng."
  3344. :image-input-type "dvi"
  3345. :image-output-type "png"
  3346. :image-size-adjust (1.0 . 1.0)
  3347. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3348. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3349. (dvisvgm
  3350. :programs ("latex" "dvisvgm")
  3351. :description "dvi > svg"
  3352. :message "you need to install the programs: latex and dvisvgm."
  3353. :use-xcolor t
  3354. :image-input-type "dvi"
  3355. :image-output-type "svg"
  3356. :image-size-adjust (1.7 . 1.5)
  3357. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3358. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3359. (imagemagick
  3360. :programs ("latex" "convert")
  3361. :description "pdf > png"
  3362. :message "you need to install the programs: latex and imagemagick."
  3363. :use-xcolor t
  3364. :image-input-type "pdf"
  3365. :image-output-type "png"
  3366. :image-size-adjust (1.0 . 1.0)
  3367. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3368. :image-converter
  3369. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3370. "Definitions of external processes for LaTeX previewing.
  3371. Org mode can use some external commands to generate TeX snippet's images for
  3372. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3373. `org-create-formula-image' how to call them.
  3374. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3375. PROPERTIES accepts the following attributes:
  3376. :programs list of strings, required programs.
  3377. :description string, describe the process.
  3378. :message string, message it when required programs cannot be found.
  3379. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3380. :image-output-type string, output file type of image converter (e.g., \"png\").
  3381. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3382. deal with background and foreground color of image.
  3383. Otherwise, dvipng style background and foreground color
  3384. format are generated. You may then refer to them in
  3385. command options with \"%F\" and \"%B\".
  3386. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3387. image size showed in buffer and the cdr element is for
  3388. HTML file. This option is only useful for process
  3389. developers, users should use variable
  3390. `org-format-latex-options' instead.
  3391. :post-clean list of strings, files matched are to be cleaned up once
  3392. the image is generated. When nil, the files with \".dvi\",
  3393. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3394. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3395. be cleaned up.
  3396. :latex-header list of strings, the LaTeX header of the snippet file.
  3397. When nil, the fallback value is used instead, which is
  3398. controlled by `org-format-latex-header',
  3399. `org-latex-default-packages-alist' and
  3400. `org-latex-packages-alist', which see.
  3401. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3402. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3403. replaced with values defined below.
  3404. :image-converter list of image converter commands strings. Each of them is
  3405. given to the shell and supports any of the following
  3406. place-holders defined below.
  3407. Place-holders used by `:image-converter' and `:latex-compiler':
  3408. %f input file name
  3409. %b base name of input file
  3410. %o base directory of input file
  3411. %O absolute output file name
  3412. Place-holders only used by `:image-converter':
  3413. %F foreground of image
  3414. %B background of image
  3415. %D dpi, which is used to adjust image size by some processing commands.
  3416. %S the image size scale ratio, which is used to adjust image size by some
  3417. processing commands."
  3418. :group 'org-latex
  3419. :version "26.1"
  3420. :package-version '(Org . "9.0")
  3421. :type '(alist :tag "LaTeX to image backends"
  3422. :value-type (plist)))
  3423. (defcustom org-preview-latex-image-directory "ltximg/"
  3424. "Path to store latex preview images.
  3425. A relative path here creates many directories relative to the
  3426. processed org files paths. An absolute path puts all preview
  3427. images at the same place."
  3428. :group 'org-latex
  3429. :version "26.1"
  3430. :package-version '(Org . "9.0")
  3431. :type 'string)
  3432. (defun org-format-latex-mathml-available-p ()
  3433. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3434. (save-match-data
  3435. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3436. org-latex-to-mathml-convert-command)
  3437. (let ((executable (car (split-string
  3438. org-latex-to-mathml-convert-command))))
  3439. (when (executable-find executable)
  3440. (if (string-match
  3441. "%j" org-latex-to-mathml-convert-command)
  3442. (file-readable-p org-latex-to-mathml-jar-file)
  3443. t))))))
  3444. (defcustom org-format-latex-header "\\documentclass{article}
  3445. \\usepackage[usenames]{color}
  3446. \[PACKAGES]
  3447. \[DEFAULT-PACKAGES]
  3448. \\pagestyle{empty} % do not remove
  3449. % The settings below are copied from fullpage.sty
  3450. \\setlength{\\textwidth}{\\paperwidth}
  3451. \\addtolength{\\textwidth}{-3cm}
  3452. \\setlength{\\oddsidemargin}{1.5cm}
  3453. \\addtolength{\\oddsidemargin}{-2.54cm}
  3454. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3455. \\setlength{\\textheight}{\\paperheight}
  3456. \\addtolength{\\textheight}{-\\headheight}
  3457. \\addtolength{\\textheight}{-\\headsep}
  3458. \\addtolength{\\textheight}{-\\footskip}
  3459. \\addtolength{\\textheight}{-3cm}
  3460. \\setlength{\\topmargin}{1.5cm}
  3461. \\addtolength{\\topmargin}{-2.54cm}"
  3462. "The document header used for processing LaTeX fragments.
  3463. It is imperative that this header make sure that no page number
  3464. appears on the page. The package defined in the variables
  3465. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3466. will either replace the placeholder \"[PACKAGES]\" in this
  3467. header, or they will be appended."
  3468. :group 'org-latex
  3469. :type 'string)
  3470. (defun org-set-packages-alist (var val)
  3471. "Set the packages alist and make sure it has 3 elements per entry."
  3472. (set var (mapcar (lambda (x)
  3473. (if (and (consp x) (= (length x) 2))
  3474. (list (car x) (nth 1 x) t)
  3475. x))
  3476. val)))
  3477. (defun org-get-packages-alist (var)
  3478. "Get the packages alist and make sure it has 3 elements per entry."
  3479. (mapcar (lambda (x)
  3480. (if (and (consp x) (= (length x) 2))
  3481. (list (car x) (nth 1 x) t)
  3482. x))
  3483. (default-value var)))
  3484. (defcustom org-latex-default-packages-alist
  3485. '(("AUTO" "inputenc" t ("pdflatex"))
  3486. ("T1" "fontenc" t ("pdflatex"))
  3487. ("" "graphicx" t)
  3488. ("" "grffile" t)
  3489. ("" "longtable" nil)
  3490. ("" "wrapfig" nil)
  3491. ("" "rotating" nil)
  3492. ("normalem" "ulem" t)
  3493. ("" "amsmath" t)
  3494. ("" "textcomp" t)
  3495. ("" "amssymb" t)
  3496. ("" "capt-of" nil)
  3497. ("" "hyperref" nil))
  3498. "Alist of default packages to be inserted in the header.
  3499. Change this only if one of the packages here causes an
  3500. incompatibility with another package you are using.
  3501. The packages in this list are needed by one part or another of
  3502. Org mode to function properly:
  3503. - inputenc, fontenc: for basic font and character selection
  3504. - graphicx: for including images
  3505. - grffile: allow periods and spaces in graphics file names
  3506. - longtable: For multipage tables
  3507. - wrapfig: for figure placement
  3508. - rotating: for sideways figures and tables
  3509. - ulem: for underline and strike-through
  3510. - amsmath: for subscript and superscript and math environments
  3511. - textcomp, amssymb: for various symbols used
  3512. for interpreting the entities in `org-entities'. You can skip
  3513. some of these packages if you don't use any of their symbols.
  3514. - capt-of: for captions outside of floats
  3515. - hyperref: for cross references
  3516. Therefore you should not modify this variable unless you know
  3517. what you are doing. The one reason to change it anyway is that
  3518. you might be loading some other package that conflicts with one
  3519. of the default packages. Each element is either a cell or
  3520. a string.
  3521. A cell is of the format
  3522. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3523. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3524. when compiling LaTeX snippets into images for inclusion into
  3525. non-LaTeX output. COMPILERS is a list of compilers that should
  3526. include the package, see `org-latex-compiler'. If the document
  3527. compiler is not in the list, and the list is non-nil, the package
  3528. will not be inserted in the final document.
  3529. A string will be inserted as-is in the header of the document."
  3530. :group 'org-latex
  3531. :group 'org-export-latex
  3532. :set 'org-set-packages-alist
  3533. :get 'org-get-packages-alist
  3534. :version "26.1"
  3535. :package-version '(Org . "8.3")
  3536. :type '(repeat
  3537. (choice
  3538. (list :tag "options/package pair"
  3539. (string :tag "options")
  3540. (string :tag "package")
  3541. (boolean :tag "Snippet"))
  3542. (string :tag "A line of LaTeX"))))
  3543. (defcustom org-latex-packages-alist nil
  3544. "Alist of packages to be inserted in every LaTeX header.
  3545. These will be inserted after `org-latex-default-packages-alist'.
  3546. Each element is either a cell or a string.
  3547. A cell is of the format:
  3548. (\"options\" \"package\" SNIPPET-FLAG)
  3549. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3550. needed when turning LaTeX snippets into images for inclusion into
  3551. non-LaTeX output.
  3552. A string will be inserted as-is in the header of the document.
  3553. Make sure that you only list packages here which:
  3554. - you want in every file;
  3555. - do not conflict with the setup in `org-format-latex-header';
  3556. - do not conflict with the default packages in
  3557. `org-latex-default-packages-alist'."
  3558. :group 'org-latex
  3559. :group 'org-export-latex
  3560. :set 'org-set-packages-alist
  3561. :get 'org-get-packages-alist
  3562. :type '(repeat
  3563. (choice
  3564. (list :tag "options/package pair"
  3565. (string :tag "options")
  3566. (string :tag "package")
  3567. (boolean :tag "Snippet"))
  3568. (string :tag "A line of LaTeX"))))
  3569. (defgroup org-appearance nil
  3570. "Settings for Org mode appearance."
  3571. :tag "Org Appearance"
  3572. :group 'org)
  3573. (defcustom org-level-color-stars-only nil
  3574. "Non-nil means fontify only the stars in each headline.
  3575. When nil, the entire headline is fontified.
  3576. Changing it requires restart of `font-lock-mode' to become effective
  3577. also in regions already fontified."
  3578. :group 'org-appearance
  3579. :type 'boolean)
  3580. (defcustom org-hide-leading-stars nil
  3581. "Non-nil means hide the first N-1 stars in a headline.
  3582. This works by using the face `org-hide' for these stars. This
  3583. face is white for a light background, and black for a dark
  3584. background. You may have to customize the face `org-hide' to
  3585. make this work.
  3586. Changing it requires restart of `font-lock-mode' to become effective
  3587. also in regions already fontified.
  3588. You may also set this on a per-file basis by adding one of the following
  3589. lines to the buffer:
  3590. #+STARTUP: hidestars
  3591. #+STARTUP: showstars"
  3592. :group 'org-appearance
  3593. :type 'boolean)
  3594. (defcustom org-hidden-keywords nil
  3595. "List of symbols corresponding to keywords to be hidden the org buffer.
  3596. For example, a value \\='(title) for this list will make the document's title
  3597. appear in the buffer without the initial #+TITLE: keyword."
  3598. :group 'org-appearance
  3599. :version "24.1"
  3600. :type '(set (const :tag "#+AUTHOR" author)
  3601. (const :tag "#+DATE" date)
  3602. (const :tag "#+EMAIL" email)
  3603. (const :tag "#+TITLE" title)))
  3604. (defcustom org-custom-properties nil
  3605. "List of properties (as strings) with a special meaning.
  3606. The default use of these custom properties is to let the user
  3607. hide them with `org-toggle-custom-properties-visibility'."
  3608. :group 'org-properties
  3609. :group 'org-appearance
  3610. :version "24.3"
  3611. :type '(repeat (string :tag "Property Name")))
  3612. (defcustom org-fontify-done-headline nil
  3613. "Non-nil means change the face of a headline if it is marked DONE.
  3614. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3615. When this is non-nil, the headline after the keyword is set to the
  3616. `org-headline-done' as an additional indication."
  3617. :group 'org-appearance
  3618. :type 'boolean)
  3619. (defcustom org-fontify-emphasized-text t
  3620. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3621. Changing this variable requires a restart of Emacs to take effect."
  3622. :group 'org-appearance
  3623. :type 'boolean)
  3624. (defcustom org-fontify-whole-heading-line nil
  3625. "Non-nil means fontify the whole line for headings.
  3626. This is useful when setting a background color for the
  3627. org-level-* faces."
  3628. :group 'org-appearance
  3629. :type 'boolean)
  3630. (defcustom org-highlight-latex-and-related nil
  3631. "Non-nil means highlight LaTeX related syntax in the buffer.
  3632. When non nil, the value should be a list containing any of the
  3633. following symbols:
  3634. `latex' Highlight LaTeX snippets and environments.
  3635. `script' Highlight subscript and superscript.
  3636. `entities' Highlight entities."
  3637. :group 'org-appearance
  3638. :version "24.4"
  3639. :package-version '(Org . "8.0")
  3640. :type '(choice
  3641. (const :tag "No highlighting" nil)
  3642. (set :greedy t :tag "Highlight"
  3643. (const :tag "LaTeX snippets and environments" latex)
  3644. (const :tag "Subscript and superscript" script)
  3645. (const :tag "Entities" entities))))
  3646. (defcustom org-hide-emphasis-markers nil
  3647. "Non-nil mean font-lock should hide the emphasis marker characters."
  3648. :group 'org-appearance
  3649. :type 'boolean)
  3650. (defcustom org-hide-macro-markers nil
  3651. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3652. :group 'org-appearance
  3653. :type 'boolean)
  3654. (defcustom org-pretty-entities nil
  3655. "Non-nil means show entities as UTF8 characters.
  3656. When nil, the \\name form remains in the buffer."
  3657. :group 'org-appearance
  3658. :version "24.1"
  3659. :type 'boolean)
  3660. (defcustom org-pretty-entities-include-sub-superscripts t
  3661. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3662. :group 'org-appearance
  3663. :version "24.1"
  3664. :type 'boolean)
  3665. (defvar org-emph-re nil
  3666. "Regular expression for matching emphasis.
  3667. After a match, the match groups contain these elements:
  3668. 0 The match of the full regular expression, including the characters
  3669. before and after the proper match
  3670. 1 The character before the proper match, or empty at beginning of line
  3671. 2 The proper match, including the leading and trailing markers
  3672. 3 The leading marker like * or /, indicating the type of highlighting
  3673. 4 The text between the emphasis markers, not including the markers
  3674. 5 The character after the match, empty at the end of a line")
  3675. (defvar org-verbatim-re nil
  3676. "Regular expression for matching verbatim text.")
  3677. (defvar org-emphasis-regexp-components) ; defined just below
  3678. (defvar org-emphasis-alist) ; defined just below
  3679. (defun org-set-emph-re (var val)
  3680. "Set variable and compute the emphasis regular expression."
  3681. (set var val)
  3682. (when (and (boundp 'org-emphasis-alist)
  3683. (boundp 'org-emphasis-regexp-components)
  3684. org-emphasis-alist org-emphasis-regexp-components)
  3685. (pcase-let*
  3686. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3687. (body (if (<= nl 0) body
  3688. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3689. (template
  3690. (format (concat "\\([%s]\\|^\\)" ;before markers
  3691. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3692. "\\([%s]\\|$\\)") ;after markers
  3693. pre border border body border post)))
  3694. (setq org-emph-re (format template "*/_+"))
  3695. (setq org-verbatim-re (format template "=~")))))
  3696. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3697. ;; set this option proved cumbersome. See this message/thread:
  3698. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3699. (defvar org-emphasis-regexp-components
  3700. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3701. "Components used to build the regular expression for emphasis.
  3702. This is a list with five entries. Terminology: In an emphasis string
  3703. like \" *strong word* \", we call the initial space PREMATCH, the final
  3704. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3705. and \"trong wor\" is the body. The different components in this variable
  3706. specify what is allowed/forbidden in each part:
  3707. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3708. post Chars allowed as postmatch. End of line will be allowed too.
  3709. border The chars *forbidden* as border characters.
  3710. body-regexp A regexp like \".\" to match a body character. Don't use
  3711. non-shy groups here, and don't allow newline here.
  3712. newline The maximum number of newlines allowed in an emphasis exp.
  3713. You need to reload Org or to restart Emacs after setting this.")
  3714. (defcustom org-emphasis-alist
  3715. '(("*" bold)
  3716. ("/" italic)
  3717. ("_" underline)
  3718. ("=" org-verbatim verbatim)
  3719. ("~" org-code verbatim)
  3720. ("+" (:strike-through t)))
  3721. "Alist of characters and faces to emphasize text.
  3722. Text starting and ending with a special character will be emphasized,
  3723. for example *bold*, _underlined_ and /italic/. This variable sets the
  3724. marker characters and the face to be used by font-lock for highlighting
  3725. in Org buffers.
  3726. You need to reload Org or to restart Emacs after customizing this."
  3727. :group 'org-appearance
  3728. :set 'org-set-emph-re
  3729. :version "24.4"
  3730. :package-version '(Org . "8.0")
  3731. :type '(repeat
  3732. (list
  3733. (string :tag "Marker character")
  3734. (choice
  3735. (face :tag "Font-lock-face")
  3736. (plist :tag "Face property list"))
  3737. (option (const verbatim)))))
  3738. (defvar org-protecting-blocks '("src" "example" "export")
  3739. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3740. This is needed for font-lock setup.")
  3741. ;;; Functions and variables from their packages
  3742. ;; Declared here to avoid compiler warnings
  3743. (defvar mark-active)
  3744. ;; Various packages
  3745. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3746. (declare-function calendar-forward-day "cal-move" (arg))
  3747. (declare-function calendar-goto-date "cal-move" (date))
  3748. (declare-function calendar-goto-today "cal-move" ())
  3749. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3750. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3751. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3752. (declare-function cdlatex-tab "ext:cdlatex" ())
  3753. (declare-function dired-get-filename
  3754. "dired"
  3755. (&optional localp no-error-if-not-filep))
  3756. (declare-function iswitchb-read-buffer
  3757. "iswitchb"
  3758. (prompt &optional
  3759. default require-match _predicate start matches-set))
  3760. (declare-function org-agenda-change-all-lines
  3761. "org-agenda"
  3762. (newhead hdmarker &optional fixface just-this))
  3763. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3764. "org-agenda"
  3765. (&optional end))
  3766. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3767. (declare-function org-agenda-format-item
  3768. "org-agenda"
  3769. (extra txt &optional level category tags dotime
  3770. remove-re habitp))
  3771. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3772. (declare-function org-agenda-save-markers-for-cut-and-paste
  3773. "org-agenda"
  3774. (beg end))
  3775. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3776. (declare-function org-agenda-skip "org-agenda" ())
  3777. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3778. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3779. (declare-function org-indent-mode "org-indent" (&optional arg))
  3780. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3781. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3782. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3783. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3784. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3785. (declare-function parse-time-string "parse-time" (string))
  3786. (defvar align-mode-rules-list)
  3787. (defvar calc-embedded-close-formula)
  3788. (defvar calc-embedded-open-formula)
  3789. (defvar calc-embedded-open-mode)
  3790. (defvar font-lock-unfontify-region-function)
  3791. (defvar iswitchb-temp-buflist)
  3792. (defvar org-agenda-tags-todo-honor-ignore-options)
  3793. (defvar remember-data-file)
  3794. (defvar texmathp-why)
  3795. ;;;###autoload
  3796. (defun turn-on-orgtbl ()
  3797. "Unconditionally turn on `orgtbl-mode'."
  3798. (require 'org-table)
  3799. (orgtbl-mode 1))
  3800. (defun org-at-table-p (&optional table-type)
  3801. "Non-nil if the cursor is inside an Org table.
  3802. If TABLE-TYPE is non-nil, also check for table.el-type tables."
  3803. (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
  3804. (or (not (derived-mode-p 'org-mode))
  3805. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3806. (and e (or table-type
  3807. (eq 'org (org-element-property :type e))))))))
  3808. (defun org-at-table.el-p ()
  3809. "Non-nil when point is at a table.el table."
  3810. (and (org-match-line "[ \t]*[|+]")
  3811. (let ((element (org-element-at-point)))
  3812. (and (eq (org-element-type element) 'table)
  3813. (eq (org-element-property :type element) 'table.el)))))
  3814. (defun org-at-table-hline-p ()
  3815. "Non-nil when point is inside a hline in a table.
  3816. Assume point is already in a table."
  3817. (org-match-line org-table-hline-regexp))
  3818. (defun org-table-map-tables (function &optional quietly)
  3819. "Apply FUNCTION to the start of all tables in the buffer."
  3820. (org-with-wide-buffer
  3821. (goto-char (point-min))
  3822. (while (re-search-forward org-table-any-line-regexp nil t)
  3823. (unless quietly
  3824. (message "Mapping tables: %d%%"
  3825. (floor (* 100.0 (point)) (buffer-size))))
  3826. (beginning-of-line 1)
  3827. (when (and (looking-at org-table-line-regexp)
  3828. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3829. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3830. (save-excursion (funcall function))
  3831. (or (looking-at org-table-line-regexp)
  3832. (forward-char 1)))
  3833. (re-search-forward org-table-any-border-regexp nil 1)))
  3834. (unless quietly (message "Mapping tables: done")))
  3835. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3836. (declare-function org-clock-update-mode-line "org-clock" ())
  3837. (declare-function org-resolve-clocks "org-clock"
  3838. (&optional also-non-dangling-p prompt last-valid))
  3839. (defun org-at-TBLFM-p (&optional pos)
  3840. "Non-nil when point (or POS) is in #+TBLFM line."
  3841. (save-excursion
  3842. (goto-char (or pos (point)))
  3843. (beginning-of-line)
  3844. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3845. (eq (org-element-type (org-element-at-point)) 'table))))
  3846. (defvar org-clock-start-time)
  3847. (defvar org-clock-marker (make-marker)
  3848. "Marker recording the last clock-in.")
  3849. (defvar org-clock-hd-marker (make-marker)
  3850. "Marker recording the last clock-in, but the headline position.")
  3851. (defvar org-clock-heading ""
  3852. "The heading of the current clock entry.")
  3853. (defun org-clock-is-active ()
  3854. "Return the buffer where the clock is currently running.
  3855. Return nil if no clock is running."
  3856. (marker-buffer org-clock-marker))
  3857. (defun org-check-running-clock ()
  3858. "Check if the current buffer contains the running clock.
  3859. If yes, offer to stop it and to save the buffer with the changes."
  3860. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3861. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3862. (buffer-name))))
  3863. (org-clock-out)
  3864. (when (y-or-n-p "Save changed buffer?")
  3865. (save-buffer))))
  3866. (defun org-clocktable-try-shift (dir n)
  3867. "Check if this line starts a clock table, if yes, shift the time block."
  3868. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3869. (org-clocktable-shift dir n)))
  3870. ;;;###autoload
  3871. (defun org-clock-persistence-insinuate ()
  3872. "Set up hooks for clock persistence."
  3873. (require 'org-clock)
  3874. (add-hook 'org-mode-hook 'org-clock-load)
  3875. (add-hook 'kill-emacs-hook 'org-clock-save))
  3876. (defgroup org-archive nil
  3877. "Options concerning archiving in Org mode."
  3878. :tag "Org Archive"
  3879. :group 'org-structure)
  3880. (defcustom org-archive-location "%s_archive::"
  3881. "The location where subtrees should be archived.
  3882. The value of this variable is a string, consisting of two parts,
  3883. separated by a double-colon. The first part is a filename and
  3884. the second part is a headline.
  3885. When the filename is omitted, archiving happens in the same file.
  3886. %s in the filename will be replaced by the current file
  3887. name (without the directory part). Archiving to a different file
  3888. is useful to keep archived entries from contributing to the
  3889. Org Agenda.
  3890. The archived entries will be filed as subtrees of the specified
  3891. headline. When the headline is omitted, the subtrees are simply
  3892. filed away at the end of the file, as top-level entries. Also in
  3893. the heading you can use %s to represent the file name, this can be
  3894. useful when using the same archive for a number of different files.
  3895. Here are a few examples:
  3896. \"%s_archive::\"
  3897. If the current file is Projects.org, archive in file
  3898. Projects.org_archive, as top-level trees. This is the default.
  3899. \"::* Archived Tasks\"
  3900. Archive in the current file, under the top-level headline
  3901. \"* Archived Tasks\".
  3902. \"~/org/archive.org::\"
  3903. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3904. \"~/org/archive.org::* From %s\"
  3905. Archive in file ~/org/archive.org (absolute path), under headlines
  3906. \"From FILENAME\" where file name is the current file name.
  3907. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3908. The \"datetree/\" string is special, signifying to archive
  3909. items to the datetree. Items are placed in either the CLOSED
  3910. date of the item, or the current date if there is no CLOSED date.
  3911. The heading will be a subentry to the current date. There doesn't
  3912. need to be a heading, but there always needs to be a slash after
  3913. datetree. For example, to store archived items directly in the
  3914. datetree, use \"~/org/datetree.org::datetree/\".
  3915. \"basement::** Finished Tasks\"
  3916. Archive in file ./basement (relative path), as level 3 trees
  3917. below the level 2 heading \"** Finished Tasks\".
  3918. You may set this option on a per-file basis by adding to the buffer a
  3919. line like
  3920. #+ARCHIVE: basement::** Finished Tasks
  3921. You may also define it locally for a subtree by setting an ARCHIVE property
  3922. in the entry. If such a property is found in an entry, or anywhere up
  3923. the hierarchy, it will be used."
  3924. :group 'org-archive
  3925. :type 'string)
  3926. (defcustom org-agenda-skip-archived-trees t
  3927. "Non-nil means the agenda will skip any items located in archived trees.
  3928. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3929. variable is no longer recommended, you should leave it at the value t.
  3930. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3931. :group 'org-archive
  3932. :group 'org-agenda-skip
  3933. :type 'boolean)
  3934. (defcustom org-columns-skip-archived-trees t
  3935. "Non-nil means ignore archived trees when creating column view."
  3936. :group 'org-archive
  3937. :group 'org-properties
  3938. :type 'boolean)
  3939. (defcustom org-cycle-open-archived-trees nil
  3940. "Non-nil means `org-cycle' will open archived trees.
  3941. An archived tree is a tree marked with the tag ARCHIVE.
  3942. When nil, archived trees will stay folded. You can still open them with
  3943. normal outline commands like `show-all', but not with the cycling commands."
  3944. :group 'org-archive
  3945. :group 'org-cycle
  3946. :type 'boolean)
  3947. (defcustom org-sparse-tree-open-archived-trees nil
  3948. "Non-nil means sparse tree construction shows matches in archived trees.
  3949. When nil, matches in these trees are highlighted, but the trees are kept in
  3950. collapsed state."
  3951. :group 'org-archive
  3952. :group 'org-sparse-trees
  3953. :type 'boolean)
  3954. (defcustom org-sparse-tree-default-date-type nil
  3955. "The default date type when building a sparse tree.
  3956. When this is nil, a date is a scheduled or a deadline timestamp.
  3957. Otherwise, these types are allowed:
  3958. all: all timestamps
  3959. active: only active timestamps (<...>)
  3960. inactive: only inactive timestamps ([...])
  3961. scheduled: only scheduled timestamps
  3962. deadline: only deadline timestamps"
  3963. :type '(choice (const :tag "Scheduled or deadline" nil)
  3964. (const :tag "All timestamps" all)
  3965. (const :tag "Only active timestamps" active)
  3966. (const :tag "Only inactive timestamps" inactive)
  3967. (const :tag "Only scheduled timestamps" scheduled)
  3968. (const :tag "Only deadline timestamps" deadline)
  3969. (const :tag "Only closed timestamps" closed))
  3970. :version "26.1"
  3971. :package-version '(Org . "8.3")
  3972. :group 'org-sparse-trees)
  3973. (defun org-cycle-hide-archived-subtrees (state)
  3974. "Re-hide all archived subtrees after a visibility state change.
  3975. STATE should be one of the symbols listed in the docstring of
  3976. `org-cycle-hook'."
  3977. (when (and (not org-cycle-open-archived-trees)
  3978. (not (memq state '(overview folded))))
  3979. (save-excursion
  3980. (let* ((globalp (memq state '(contents all)))
  3981. (beg (if globalp (point-min) (point)))
  3982. (end (if globalp (point-max) (org-end-of-subtree t))))
  3983. (org-hide-archived-subtrees beg end)
  3984. (goto-char beg)
  3985. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3986. (message "%s" (substitute-command-keys
  3987. "Subtree is archived and stays closed. Use \
  3988. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3989. (defun org-force-cycle-archived ()
  3990. "Cycle subtree even if it is archived."
  3991. (interactive)
  3992. (setq this-command 'org-cycle)
  3993. (let ((org-cycle-open-archived-trees t))
  3994. (call-interactively 'org-cycle)))
  3995. (defun org-hide-archived-subtrees (beg end)
  3996. "Re-hide all archived subtrees after a visibility state change."
  3997. (org-with-wide-buffer
  3998. (let ((case-fold-search nil)
  3999. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4000. (goto-char beg)
  4001. ;; Include headline point is currently on.
  4002. (beginning-of-line)
  4003. (while (and (< (point) end) (re-search-forward re end t))
  4004. (when (member org-archive-tag (org-get-tags))
  4005. (org-flag-subtree t)
  4006. (org-end-of-subtree t))))))
  4007. (declare-function outline-end-of-heading "outline" ())
  4008. (declare-function outline-flag-region "outline" (from to flag))
  4009. (defun org-flag-subtree (flag)
  4010. (save-excursion
  4011. (org-back-to-heading t)
  4012. (outline-end-of-heading)
  4013. (outline-flag-region (point)
  4014. (progn (org-end-of-subtree t) (point))
  4015. flag)))
  4016. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4017. ;; Declare Column View Code
  4018. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4019. (declare-function org-columns-compute "org-colview" (property))
  4020. ;; Declare ID code
  4021. (declare-function org-id-store-link "org-id")
  4022. (declare-function org-id-locations-load "org-id")
  4023. (declare-function org-id-locations-save "org-id")
  4024. (defvar org-id-track-globally)
  4025. ;;; Variables for pre-computed regular expressions, all buffer local
  4026. (defvar-local org-todo-regexp nil
  4027. "Matches any of the TODO state keywords.
  4028. Since TODO keywords are case-sensitive, `case-fold-search' is
  4029. expected to be bound to nil when matching against this regexp.")
  4030. (defvar-local org-not-done-regexp nil
  4031. "Matches any of the TODO state keywords except the last one.
  4032. Since TODO keywords are case-sensitive, `case-fold-search' is
  4033. expected to be bound to nil when matching against this regexp.")
  4034. (defvar-local org-not-done-heading-regexp nil
  4035. "Matches a TODO headline that is not done.
  4036. Since TODO keywords are case-sensitive, `case-fold-search' is
  4037. expected to be bound to nil when matching against this regexp.")
  4038. (defvar-local org-todo-line-regexp nil
  4039. "Matches a headline and puts TODO state into group 2 if present.
  4040. Since TODO keywords are case-sensitive, `case-fold-search' is
  4041. expected to be bound to nil when matching against this regexp.")
  4042. (defvar-local org-complex-heading-regexp nil
  4043. "Matches a headline and puts everything into groups:
  4044. group 1: Stars
  4045. group 2: The TODO keyword, maybe
  4046. group 3: Priority cookie
  4047. group 4: True headline
  4048. group 5: Tags
  4049. Since TODO keywords are case-sensitive, `case-fold-search' is
  4050. expected to be bound to nil when matching against this regexp.")
  4051. (defvar-local org-complex-heading-regexp-format nil
  4052. "Printf format to make regexp to match an exact headline.
  4053. This regexp will match the headline of any node which has the
  4054. exact headline text that is put into the format, but may have any
  4055. TODO state, priority and tags.")
  4056. (defvar-local org-todo-line-tags-regexp nil
  4057. "Matches a headline and puts TODO state into group 2 if present.
  4058. Also put tags into group 4 if tags are present.")
  4059. (defconst org-plain-time-of-day-regexp
  4060. (concat
  4061. "\\(\\<[012]?[0-9]"
  4062. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4063. "\\(--?"
  4064. "\\(\\<[012]?[0-9]"
  4065. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4066. "\\)?")
  4067. "Regular expression to match a plain time or time range.
  4068. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4069. groups carry important information:
  4070. 0 the full match
  4071. 1 the first time, range or not
  4072. 8 the second time, if it is a range.")
  4073. (defconst org-plain-time-extension-regexp
  4074. (concat
  4075. "\\(\\<[012]?[0-9]"
  4076. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4077. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4078. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4079. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4080. groups carry important information:
  4081. 0 the full match
  4082. 7 hours of duration
  4083. 9 minutes of duration")
  4084. (defconst org-stamp-time-of-day-regexp
  4085. (concat
  4086. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4087. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4088. "\\(--?"
  4089. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4090. "Regular expression to match a timestamp time or time range.
  4091. After a match, the following groups carry important information:
  4092. 0 the full match
  4093. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4094. 2 the first time, range or not
  4095. 4 the second time, if it is a range.")
  4096. (defconst org-startup-options
  4097. '(("fold" org-startup-folded t)
  4098. ("overview" org-startup-folded t)
  4099. ("nofold" org-startup-folded nil)
  4100. ("showall" org-startup-folded nil)
  4101. ("showeverything" org-startup-folded showeverything)
  4102. ("content" org-startup-folded content)
  4103. ("indent" org-startup-indented t)
  4104. ("noindent" org-startup-indented nil)
  4105. ("hidestars" org-hide-leading-stars t)
  4106. ("showstars" org-hide-leading-stars nil)
  4107. ("odd" org-odd-levels-only t)
  4108. ("oddeven" org-odd-levels-only nil)
  4109. ("align" org-startup-align-all-tables t)
  4110. ("noalign" org-startup-align-all-tables nil)
  4111. ("shrink" org-startup-shrink-all-tables t)
  4112. ("inlineimages" org-startup-with-inline-images t)
  4113. ("noinlineimages" org-startup-with-inline-images nil)
  4114. ("latexpreview" org-startup-with-latex-preview t)
  4115. ("nolatexpreview" org-startup-with-latex-preview nil)
  4116. ("customtime" org-display-custom-times t)
  4117. ("logdone" org-log-done time)
  4118. ("lognotedone" org-log-done note)
  4119. ("nologdone" org-log-done nil)
  4120. ("lognoteclock-out" org-log-note-clock-out t)
  4121. ("nolognoteclock-out" org-log-note-clock-out nil)
  4122. ("logrepeat" org-log-repeat state)
  4123. ("lognoterepeat" org-log-repeat note)
  4124. ("logdrawer" org-log-into-drawer t)
  4125. ("nologdrawer" org-log-into-drawer nil)
  4126. ("logstatesreversed" org-log-states-order-reversed t)
  4127. ("nologstatesreversed" org-log-states-order-reversed nil)
  4128. ("nologrepeat" org-log-repeat nil)
  4129. ("logreschedule" org-log-reschedule time)
  4130. ("lognotereschedule" org-log-reschedule note)
  4131. ("nologreschedule" org-log-reschedule nil)
  4132. ("logredeadline" org-log-redeadline time)
  4133. ("lognoteredeadline" org-log-redeadline note)
  4134. ("nologredeadline" org-log-redeadline nil)
  4135. ("logrefile" org-log-refile time)
  4136. ("lognoterefile" org-log-refile note)
  4137. ("nologrefile" org-log-refile nil)
  4138. ("fninline" org-footnote-define-inline t)
  4139. ("nofninline" org-footnote-define-inline nil)
  4140. ("fnlocal" org-footnote-section nil)
  4141. ("fnauto" org-footnote-auto-label t)
  4142. ("fnprompt" org-footnote-auto-label nil)
  4143. ("fnconfirm" org-footnote-auto-label confirm)
  4144. ("fnplain" org-footnote-auto-label plain)
  4145. ("fnadjust" org-footnote-auto-adjust t)
  4146. ("nofnadjust" org-footnote-auto-adjust nil)
  4147. ("constcgs" constants-unit-system cgs)
  4148. ("constSI" constants-unit-system SI)
  4149. ("noptag" org-tag-persistent-alist nil)
  4150. ("hideblocks" org-hide-block-startup t)
  4151. ("nohideblocks" org-hide-block-startup nil)
  4152. ("beamer" org-startup-with-beamer-mode t)
  4153. ("entitiespretty" org-pretty-entities t)
  4154. ("entitiesplain" org-pretty-entities nil))
  4155. "Variable associated with STARTUP options for org-mode.
  4156. Each element is a list of three items: the startup options (as written
  4157. in the #+STARTUP line), the corresponding variable, and the value to set
  4158. this variable to if the option is found. An optional forth element PUSH
  4159. means to push this value onto the list in the variable.")
  4160. (defcustom org-group-tags t
  4161. "When non-nil (the default), use group tags.
  4162. This can be turned on/off through `org-toggle-tags-groups'."
  4163. :group 'org-tags
  4164. :group 'org-startup
  4165. :type 'boolean)
  4166. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4167. (defun org-toggle-tags-groups ()
  4168. "Toggle support for group tags.
  4169. Support for group tags is controlled by the option
  4170. `org-group-tags', which is non-nil by default."
  4171. (interactive)
  4172. (setq org-group-tags (not org-group-tags))
  4173. (cond ((and (derived-mode-p 'org-agenda-mode)
  4174. org-group-tags)
  4175. (org-agenda-redo))
  4176. ((derived-mode-p 'org-mode)
  4177. (let ((org-inhibit-startup t)) (org-mode))))
  4178. (message "Groups tags support has been turned %s"
  4179. (if org-group-tags "on" "off")))
  4180. (defun org-set-regexps-and-options (&optional tags-only)
  4181. "Precompute regular expressions used in the current buffer.
  4182. When optional argument TAGS-ONLY is non-nil, only compute tags
  4183. related expressions."
  4184. (when (derived-mode-p 'org-mode)
  4185. (let ((alist (org--setup-collect-keywords
  4186. (org-make-options-regexp
  4187. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4188. (and (not tags-only)
  4189. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4190. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4191. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4192. ;; Startup options. Get this early since it does change
  4193. ;; behavior for other options (e.g., tags).
  4194. (let ((startup (cdr (assq 'startup alist))))
  4195. (dolist (option startup)
  4196. (let ((entry (assoc-string option org-startup-options t)))
  4197. (when entry
  4198. (let ((var (nth 1 entry))
  4199. (val (nth 2 entry)))
  4200. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4201. (unless (listp (symbol-value var))
  4202. (set (make-local-variable var) nil))
  4203. (add-to-list var val)))))))
  4204. (setq-local org-file-tags
  4205. (mapcar #'org-add-prop-inherited
  4206. (cdr (assq 'filetags alist))))
  4207. (setq org-current-tag-alist
  4208. (append org-tag-persistent-alist
  4209. (let ((tags (cdr (assq 'tags alist))))
  4210. (if tags (org-tag-string-to-alist tags)
  4211. org-tag-alist))))
  4212. (setq org-tag-groups-alist
  4213. (org-tag-alist-to-groups org-current-tag-alist))
  4214. (unless tags-only
  4215. ;; File properties.
  4216. (setq-local org-file-properties (cdr (assq 'property alist)))
  4217. ;; Archive location.
  4218. (let ((archive (cdr (assq 'archive alist))))
  4219. (when archive (setq-local org-archive-location archive)))
  4220. ;; Category.
  4221. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4222. (when cat
  4223. (setq-local org-category (intern cat))
  4224. (setq-local org-file-properties
  4225. (org--update-property-plist
  4226. "CATEGORY" cat org-file-properties))))
  4227. ;; Columns.
  4228. (let ((column (cdr (assq 'columns alist))))
  4229. (when column (setq-local org-columns-default-format column)))
  4230. ;; Constants.
  4231. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4232. ;; Link abbreviations.
  4233. (let ((links (cdr (assq 'link alist))))
  4234. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4235. ;; Priorities.
  4236. (let ((priorities (cdr (assq 'priorities alist))))
  4237. (when priorities
  4238. (setq-local org-highest-priority (nth 0 priorities))
  4239. (setq-local org-lowest-priority (nth 1 priorities))
  4240. (setq-local org-default-priority (nth 2 priorities))))
  4241. ;; Scripts.
  4242. (let ((scripts (assq 'scripts alist)))
  4243. (when scripts
  4244. (setq-local org-use-sub-superscripts (cdr scripts))))
  4245. ;; TODO keywords.
  4246. (setq-local org-todo-kwd-alist nil)
  4247. (setq-local org-todo-key-alist nil)
  4248. (setq-local org-todo-key-trigger nil)
  4249. (setq-local org-todo-keywords-1 nil)
  4250. (setq-local org-done-keywords nil)
  4251. (setq-local org-todo-heads nil)
  4252. (setq-local org-todo-sets nil)
  4253. (setq-local org-todo-log-states nil)
  4254. (let ((todo-sequences
  4255. (or (nreverse (cdr (assq 'todo alist)))
  4256. (let ((d (default-value 'org-todo-keywords)))
  4257. (if (not (stringp (car d))) d
  4258. ;; XXX: Backward compatibility code.
  4259. (list (cons org-todo-interpretation d)))))))
  4260. (dolist (sequence todo-sequences)
  4261. (let* ((sequence (or (run-hook-with-args-until-success
  4262. 'org-todo-setup-filter-hook sequence)
  4263. sequence))
  4264. (sequence-type (car sequence))
  4265. (keywords (cdr sequence))
  4266. (sep (member "|" keywords))
  4267. names alist)
  4268. (dolist (k (remove "|" keywords))
  4269. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4270. k)
  4271. (error "Invalid TODO keyword %s" k))
  4272. (let ((name (match-string 1 k))
  4273. (key (match-string 2 k))
  4274. (log (org-extract-log-state-settings k)))
  4275. (push name names)
  4276. (push (cons name (and key (string-to-char key))) alist)
  4277. (when log (push log org-todo-log-states))))
  4278. (let* ((names (nreverse names))
  4279. (done (if sep (org-remove-keyword-keys (cdr sep))
  4280. (last names)))
  4281. (head (car names))
  4282. (tail (list sequence-type head (car done) (org-last done))))
  4283. (add-to-list 'org-todo-heads head 'append)
  4284. (push names org-todo-sets)
  4285. (setq org-done-keywords (append org-done-keywords done nil))
  4286. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4287. (setq org-todo-key-alist
  4288. (append org-todo-key-alist
  4289. (and alist
  4290. (append '((:startgroup))
  4291. (nreverse alist)
  4292. '((:endgroup))))))
  4293. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4294. (setq org-todo-sets (nreverse org-todo-sets)
  4295. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4296. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4297. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4298. ;; Compute the regular expressions and other local variables.
  4299. ;; Using `org-outline-regexp-bol' would complicate them much,
  4300. ;; because of the fixed white space at the end of that string.
  4301. (unless org-done-keywords
  4302. (setq org-done-keywords
  4303. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4304. (setq org-not-done-keywords
  4305. (org-delete-all org-done-keywords
  4306. (copy-sequence org-todo-keywords-1))
  4307. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4308. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4309. org-not-done-heading-regexp
  4310. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4311. org-todo-line-regexp
  4312. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4313. org-complex-heading-regexp
  4314. (concat "^\\(\\*+\\)"
  4315. "\\(?: +" org-todo-regexp "\\)?"
  4316. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4317. "\\(?: +\\(.*?\\)\\)??"
  4318. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4319. "[ \t]*$")
  4320. org-complex-heading-regexp-format
  4321. (concat "^\\(\\*+\\)"
  4322. "\\(?: +" org-todo-regexp "\\)?"
  4323. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4324. "\\(?: +"
  4325. ;; Stats cookies can be stuck to body.
  4326. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4327. "\\(%s\\)"
  4328. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4329. "\\)"
  4330. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4331. "[ \t]*$")
  4332. org-todo-line-tags-regexp
  4333. (concat "^\\(\\*+\\)"
  4334. "\\(?: +" org-todo-regexp "\\)?"
  4335. "\\(?: +\\(.*?\\)\\)??"
  4336. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4337. "[ \t]*$"))
  4338. (org-compute-latex-and-related-regexp)))))
  4339. (defun org--setup-collect-keywords (regexp &optional files alist)
  4340. "Return setup keywords values as an alist.
  4341. REGEXP matches a subset of setup keywords. FILES is a list of
  4342. file names already visited. It is used to avoid circular setup
  4343. files. ALIST, when non-nil, is the alist computed so far.
  4344. Return value contains the following keys: `archive', `category',
  4345. `columns', `constants', `filetags', `link', `priorities',
  4346. `property', `scripts', `startup', `tags' and `todo'."
  4347. (org-with-wide-buffer
  4348. (goto-char (point-min))
  4349. (let ((case-fold-search t))
  4350. (while (re-search-forward regexp nil t)
  4351. (let ((element (org-element-at-point)))
  4352. (when (eq (org-element-type element) 'keyword)
  4353. (let ((key (org-element-property :key element))
  4354. (value (org-element-property :value element)))
  4355. (cond
  4356. ((equal key "ARCHIVE")
  4357. (when (org-string-nw-p value)
  4358. (push (cons 'archive value) alist)))
  4359. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4360. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4361. ((equal key "CONSTANTS")
  4362. (let* ((constants (assq 'constants alist))
  4363. (store (cdr constants)))
  4364. (dolist (pair (split-string value))
  4365. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4366. pair)
  4367. (let* ((name (match-string 1 pair))
  4368. (value (match-string 2 pair))
  4369. (old (assoc name store)))
  4370. (if old (setcdr old value)
  4371. (push (cons name value) store)))))
  4372. (if constants (setcdr constants store)
  4373. (push (cons 'constants store) alist))))
  4374. ((equal key "FILETAGS")
  4375. (when (org-string-nw-p value)
  4376. (let ((old (assq 'filetags alist))
  4377. (new (apply #'nconc
  4378. (mapcar (lambda (x) (org-split-string x ":"))
  4379. (split-string value)))))
  4380. (if old (setcdr old (append new (cdr old)))
  4381. (push (cons 'filetags new) alist)))))
  4382. ((equal key "LINK")
  4383. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4384. (let ((links (assq 'link alist))
  4385. (pair (cons (match-string-no-properties 1 value)
  4386. (match-string-no-properties 2 value))))
  4387. (if links (push pair (cdr links))
  4388. (push (list 'link pair) alist)))))
  4389. ((equal key "OPTIONS")
  4390. (when (and (org-string-nw-p value)
  4391. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4392. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4393. ((equal key "PRIORITIES")
  4394. (push (cons 'priorities
  4395. (let ((prio (split-string value)))
  4396. (if (< (length prio) 3) '(?A ?C ?B)
  4397. (mapcar #'string-to-char prio))))
  4398. alist))
  4399. ((equal key "PROPERTY")
  4400. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4401. (let* ((property (assq 'property alist))
  4402. (value (org--update-property-plist
  4403. (match-string-no-properties 1 value)
  4404. (match-string-no-properties 2 value)
  4405. (cdr property))))
  4406. (if property (setcdr property value)
  4407. (push (cons 'property value) alist)))))
  4408. ((equal key "STARTUP")
  4409. (let ((startup (assq 'startup alist)))
  4410. (if startup
  4411. (setcdr startup
  4412. (append (cdr startup) (split-string value)))
  4413. (push (cons 'startup (split-string value)) alist))))
  4414. ((equal key "TAGS")
  4415. (let ((tag-cell (assq 'tags alist)))
  4416. (if tag-cell
  4417. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4418. (push (cons 'tags value) alist))))
  4419. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4420. (let ((todo (assq 'todo alist))
  4421. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4422. (split-string value))))
  4423. (if todo (push value (cdr todo))
  4424. (push (list 'todo value) alist))))
  4425. ((equal key "SETUPFILE")
  4426. (unless buffer-read-only ; Do not check in Gnus messages.
  4427. (let ((f (and (org-string-nw-p value)
  4428. (expand-file-name
  4429. (org-unbracket-string "\"" "\"" value)))))
  4430. (when (and f (file-readable-p f) (not (member f files)))
  4431. (with-temp-buffer
  4432. (setq default-directory (file-name-directory f))
  4433. (insert-file-contents f)
  4434. (setq alist
  4435. ;; Fake Org mode to benefit from cache
  4436. ;; without recurring needlessly.
  4437. (let ((major-mode 'org-mode))
  4438. (org--setup-collect-keywords
  4439. regexp (cons f files) alist)))))))))))))))
  4440. alist)
  4441. (defun org-tag-string-to-alist (s)
  4442. "Return tag alist associated to string S.
  4443. S is a value for TAGS keyword or produced with
  4444. `org-tag-alist-to-string'. Return value is an alist suitable for
  4445. `org-tag-alist' or `org-tag-persistent-alist'."
  4446. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4447. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4448. "\\|{.+?}\\)" ; regular expression
  4449. "\\(?:(\\(.\\))\\)?\\'"))
  4450. alist group-flag)
  4451. (dolist (tokens lines (cdr (nreverse alist)))
  4452. (push '(:newline) alist)
  4453. (while tokens
  4454. (let ((token (pop tokens)))
  4455. (pcase token
  4456. ("{"
  4457. (push '(:startgroup) alist)
  4458. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4459. ("}"
  4460. (push '(:endgroup) alist)
  4461. (setq group-flag nil))
  4462. ("["
  4463. (push '(:startgrouptag) alist)
  4464. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4465. ("]"
  4466. (push '(:endgrouptag) alist)
  4467. (setq group-flag nil))
  4468. (":"
  4469. (push '(:grouptags) alist))
  4470. ((guard (string-match tag-re token))
  4471. (let ((tag (match-string 1 token))
  4472. (key (and (match-beginning 2)
  4473. (string-to-char (match-string 2 token)))))
  4474. ;; Push all tags in groups, no matter if they already
  4475. ;; appear somewhere else in the list.
  4476. (when (or group-flag (not (assoc tag alist)))
  4477. (push (cons tag key) alist))))))))))
  4478. (defun org-tag-alist-to-string (alist &optional skip-key)
  4479. "Return tag string associated to ALIST.
  4480. ALIST is an alist, as defined in `org-tag-alist' or
  4481. `org-tag-persistent-alist', or produced with
  4482. `org-tag-string-to-alist'.
  4483. Return value is a string suitable as a value for \"TAGS\"
  4484. keyword.
  4485. When optional argument SKIP-KEY is non-nil, skip selection keys
  4486. next to tags."
  4487. (mapconcat (lambda (token)
  4488. (pcase token
  4489. (`(:startgroup) "{")
  4490. (`(:endgroup) "}")
  4491. (`(:startgrouptag) "[")
  4492. (`(:endgrouptag) "]")
  4493. (`(:grouptags) ":")
  4494. (`(:newline) "\\n")
  4495. ((and
  4496. (guard (not skip-key))
  4497. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4498. (format "%s(%c)" tag key))
  4499. (`(,(and tag (pred stringp)) . ,_) tag)
  4500. (_ (user-error "Invalid tag token: %S" token))))
  4501. alist
  4502. " "))
  4503. (defun org-tag-alist-to-groups (alist)
  4504. "Return group alist from tag ALIST.
  4505. ALIST is an alist, as defined in `org-tag-alist' or
  4506. `org-tag-persistent-alist', or produced with
  4507. `org-tag-string-to-alist'. Return value is an alist following
  4508. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4509. a string, summarizing TAGS, as a list of strings."
  4510. (let (groups group-status current-group)
  4511. (dolist (token alist (nreverse groups))
  4512. (pcase token
  4513. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4514. (`(,(or :endgroup :endgrouptag))
  4515. (when (eq group-status 'append)
  4516. (push (nreverse current-group) groups))
  4517. (setq group-status nil))
  4518. (`(:grouptags) (setq group-status 'append))
  4519. ((and `(,tag . ,_) (guard group-status))
  4520. (if (eq group-status 'append) (push tag current-group)
  4521. (setq current-group (list tag))))
  4522. (_ nil)))))
  4523. (defvar org--file-cache (make-hash-table :test #'equal)
  4524. "Hash table to store contents of files referenced via a URL.
  4525. This is the cache of file URLs read using `org-file-contents'.")
  4526. (defun org-reset-file-cache ()
  4527. "Reset the cache of files downloaded by `org-file-contents'."
  4528. (clrhash org--file-cache))
  4529. (defun org-file-url-p (file)
  4530. "Non-nil if FILE is a URL."
  4531. (require 'ffap)
  4532. (string-match-p ffap-url-regexp file))
  4533. (defun org-file-contents (file &optional noerror nocache)
  4534. "Return the contents of FILE, as a string.
  4535. FILE can be a file name or URL.
  4536. If FILE is a URL, download the contents. If the URL contents are
  4537. already cached in the `org--file-cache' hash table, the download step
  4538. is skipped.
  4539. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4540. from file or URL.
  4541. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4542. is available. This option applies only if FILE is a URL."
  4543. (let* ((is-url (org-file-url-p file))
  4544. (cache (and is-url
  4545. (not nocache)
  4546. (gethash file org--file-cache))))
  4547. (cond
  4548. (cache)
  4549. (is-url
  4550. (with-current-buffer (url-retrieve-synchronously file)
  4551. (goto-char (point-min))
  4552. ;; Move point to after the url-retrieve header.
  4553. (search-forward "\n\n" nil :move)
  4554. ;; Search for the success code only in the url-retrieve header.
  4555. (if (save-excursion
  4556. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4557. ;; Update the cache `org--file-cache' and return contents.
  4558. (puthash file
  4559. (buffer-substring-no-properties (point) (point-max))
  4560. org--file-cache)
  4561. (funcall (if noerror #'message #'user-error)
  4562. "Unable to fetch file from %S"
  4563. file))))
  4564. (t
  4565. (with-temp-buffer
  4566. (condition-case nil
  4567. (progn
  4568. (insert-file-contents file)
  4569. (buffer-string))
  4570. (file-error
  4571. (funcall (if noerror #'message #'user-error)
  4572. "Unable to read file %S"
  4573. file))))))))
  4574. (defun org-extract-log-state-settings (x)
  4575. "Extract the log state setting from a TODO keyword string.
  4576. This will extract info from a string like \"WAIT(w@/!)\"."
  4577. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4578. (let ((kw (match-string 1 x))
  4579. (log1 (and (match-end 3) (match-string 3 x)))
  4580. (log2 (and (match-end 4) (match-string 4 x))))
  4581. (and (or log1 log2)
  4582. (list kw
  4583. (and log1 (if (equal log1 "!") 'time 'note))
  4584. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4585. (defun org-remove-keyword-keys (list)
  4586. "Remove a pair of parenthesis at the end of each string in LIST."
  4587. (mapcar (lambda (x)
  4588. (if (string-match "(.*)$" x)
  4589. (substring x 0 (match-beginning 0))
  4590. x))
  4591. list))
  4592. (defun org-assign-fast-keys (alist)
  4593. "Assign fast keys to a keyword-key alist.
  4594. Respect keys that are already there."
  4595. (let (new e (alt ?0))
  4596. (while (setq e (pop alist))
  4597. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4598. (cdr e)) ;; Key already assigned.
  4599. (push e new)
  4600. (let ((clist (string-to-list (downcase (car e))))
  4601. (used (append new alist)))
  4602. (when (= (car clist) ?@)
  4603. (pop clist))
  4604. (while (and clist (rassoc (car clist) used))
  4605. (pop clist))
  4606. (unless clist
  4607. (while (rassoc alt used)
  4608. (cl-incf alt)))
  4609. (push (cons (car e) (or (car clist) alt)) new))))
  4610. (nreverse new)))
  4611. ;;; Some variables used in various places
  4612. (defvar org-window-configuration nil
  4613. "Used in various places to store a window configuration.")
  4614. (defvar org-selected-window nil
  4615. "Used in various places to store a window configuration.")
  4616. (defvar org-finish-function nil
  4617. "Function to be called when `C-c C-c' is used.
  4618. This is for getting out of special buffers like capture.")
  4619. (defvar org-last-state)
  4620. ;; Defined somewhere in this file, but used before definition.
  4621. (defvar org-entities) ;; defined in org-entities.el
  4622. (defvar org-struct-menu)
  4623. (defvar org-org-menu)
  4624. (defvar org-tbl-menu)
  4625. ;;;; Define the Org mode
  4626. ;; We use a before-change function to check if a table might need
  4627. ;; an update.
  4628. (defvar org-table-may-need-update t
  4629. "Indicates that a table might need an update.
  4630. This variable is set by `org-before-change-function'.
  4631. `org-table-align' sets it back to nil.")
  4632. (defun org-before-change-function (_beg _end)
  4633. "Every change indicates that a table might need an update."
  4634. (setq org-table-may-need-update t))
  4635. (defvar org-mode-map)
  4636. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4637. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4638. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4639. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4640. (defvar org-table-buffer-is-an nil)
  4641. (defvar bidi-paragraph-direction)
  4642. (defvar buffer-face-mode-face)
  4643. (require 'outline)
  4644. ;; Other stuff we need.
  4645. (require 'time-date)
  4646. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4647. (require 'easymenu)
  4648. (autoload 'easy-menu-add "easymenu")
  4649. (require 'overlay)
  4650. ;; (require 'org-macs) moved higher up in the file before it is first used
  4651. (require 'org-entities)
  4652. ;; (require 'org-compat) moved higher up in the file before it is first used
  4653. (require 'org-faces)
  4654. (require 'org-list)
  4655. (require 'org-pcomplete)
  4656. (require 'org-src)
  4657. (require 'org-footnote)
  4658. (require 'org-macro)
  4659. ;; babel
  4660. (require 'ob)
  4661. ;;;###autoload
  4662. (define-derived-mode org-mode outline-mode "Org"
  4663. "Outline-based notes management and organizer, alias
  4664. \"Carsten's outline-mode for keeping track of everything.\"
  4665. Org mode develops organizational tasks around a NOTES file which
  4666. contains information about projects as plain text. Org mode is
  4667. implemented on top of Outline mode, which is ideal to keep the content
  4668. of large files well structured. It supports ToDo items, deadlines and
  4669. time stamps, which magically appear in the diary listing of the Emacs
  4670. calendar. Tables are easily created with a built-in table editor.
  4671. Plain text URL-like links connect to websites, emails (VM), Usenet
  4672. messages (Gnus), BBDB entries, and any files related to the project.
  4673. For printing and sharing of notes, an Org file (or a part of it)
  4674. can be exported as a structured ASCII or HTML file.
  4675. The following commands are available:
  4676. \\{org-mode-map}"
  4677. ;; Get rid of Outline menus, they are not needed
  4678. ;; Need to do this here because define-derived-mode sets up
  4679. ;; the keymap so late. Still, it is a waste to call this each time
  4680. ;; we switch another buffer into Org mode.
  4681. (define-key org-mode-map [menu-bar headings] 'undefined)
  4682. (define-key org-mode-map [menu-bar hide] 'undefined)
  4683. (define-key org-mode-map [menu-bar show] 'undefined)
  4684. (org-load-modules-maybe)
  4685. (org-install-agenda-files-menu)
  4686. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4687. (add-to-invisibility-spec '(org-hide-block . t))
  4688. (setq-local outline-regexp org-outline-regexp)
  4689. (setq-local outline-level 'org-outline-level)
  4690. (setq bidi-paragraph-direction 'left-to-right)
  4691. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4692. (unless org-display-table
  4693. (setq org-display-table (make-display-table)))
  4694. (set-display-table-slot
  4695. org-display-table 4
  4696. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4697. org-ellipsis)))
  4698. (setq buffer-display-table org-display-table))
  4699. (org-set-regexps-and-options)
  4700. (org-set-font-lock-defaults)
  4701. (when (and org-tag-faces (not org-tags-special-faces-re))
  4702. ;; tag faces set outside customize.... force initialization.
  4703. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4704. ;; Calc embedded
  4705. (setq-local calc-embedded-open-mode "# ")
  4706. ;; Modify a few syntax entries
  4707. (modify-syntax-entry ?@ "w")
  4708. (modify-syntax-entry ?\" "\"")
  4709. (modify-syntax-entry ?\\ "_")
  4710. (modify-syntax-entry ?~ "_")
  4711. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4712. ;; Activate before-change-function
  4713. (setq-local org-table-may-need-update t)
  4714. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4715. ;; Check for running clock before killing a buffer
  4716. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4717. ;; Initialize macros templates.
  4718. (org-macro-initialize-templates)
  4719. ;; Initialize radio targets.
  4720. (org-update-radio-target-regexp)
  4721. ;; Indentation.
  4722. (setq-local indent-line-function 'org-indent-line)
  4723. (setq-local indent-region-function 'org-indent-region)
  4724. ;; Filling and auto-filling.
  4725. (org-setup-filling)
  4726. ;; Comments.
  4727. (org-setup-comments-handling)
  4728. ;; Initialize cache.
  4729. (org-element-cache-reset)
  4730. ;; Beginning/end of defun
  4731. (setq-local beginning-of-defun-function 'org-backward-element)
  4732. (setq-local end-of-defun-function
  4733. (lambda ()
  4734. (if (not (org-at-heading-p))
  4735. (org-forward-element)
  4736. (org-forward-element)
  4737. (forward-char -1))))
  4738. ;; Next error for sparse trees
  4739. (setq-local next-error-function 'org-occur-next-match)
  4740. ;; Make sure dependence stuff works reliably, even for users who set it
  4741. ;; too late :-(
  4742. (if org-enforce-todo-dependencies
  4743. (add-hook 'org-blocker-hook
  4744. 'org-block-todo-from-children-or-siblings-or-parent)
  4745. (remove-hook 'org-blocker-hook
  4746. 'org-block-todo-from-children-or-siblings-or-parent))
  4747. (if org-enforce-todo-checkbox-dependencies
  4748. (add-hook 'org-blocker-hook
  4749. 'org-block-todo-from-checkboxes)
  4750. (remove-hook 'org-blocker-hook
  4751. 'org-block-todo-from-checkboxes))
  4752. ;; Align options lines
  4753. (setq-local
  4754. align-mode-rules-list
  4755. '((org-in-buffer-settings
  4756. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4757. (modes . '(org-mode)))))
  4758. ;; Imenu
  4759. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4760. ;; Make isearch reveal context
  4761. (setq-local outline-isearch-open-invisible-function
  4762. (lambda (&rest _) (org-show-context 'isearch)))
  4763. ;; Setup the pcomplete hooks
  4764. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4765. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4766. (setq-local pcomplete-default-completion-function 'ignore)
  4767. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4768. (setq-local pcomplete-termination-string "")
  4769. (setq-local buffer-face-mode-face 'org-default)
  4770. ;; If empty file that did not turn on Org mode automatically, make
  4771. ;; it to.
  4772. (when (and org-insert-mode-line-in-empty-file
  4773. (called-interactively-p 'any)
  4774. (= (point-min) (point-max)))
  4775. (insert "# -*- mode: org -*-\n\n"))
  4776. (unless org-inhibit-startup
  4777. (org-unmodified
  4778. (when org-startup-with-beamer-mode (org-beamer-mode))
  4779. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4780. (org-table-map-tables
  4781. (cond ((and org-startup-align-all-tables
  4782. org-startup-shrink-all-tables)
  4783. (lambda () (org-table-align) (org-table-shrink)))
  4784. (org-startup-align-all-tables #'org-table-align)
  4785. (t #'org-table-shrink))
  4786. t))
  4787. (when org-startup-with-inline-images (org-display-inline-images))
  4788. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4789. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4790. (when org-startup-truncated (setq truncate-lines t))
  4791. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4792. (org-refresh-effort-properties)))
  4793. ;; Try to set `org-hide' face correctly.
  4794. (let ((foreground (org-find-invisible-foreground)))
  4795. (when foreground
  4796. (set-face-foreground 'org-hide foreground))))
  4797. ;; Update `customize-package-emacs-version-alist'
  4798. (add-to-list 'customize-package-emacs-version-alist
  4799. '(Org ("8.0" . "24.4")
  4800. ("8.1" . "24.4")
  4801. ("8.2" . "24.4")
  4802. ("8.2.7" . "24.4")
  4803. ("8.3" . "26.1")
  4804. ("9.0" . "26.1")
  4805. ("9.1" . "26.1")
  4806. ("9.2" . "27.1")))
  4807. (defvar org-mode-transpose-word-syntax-table
  4808. (let ((st (make-syntax-table text-mode-syntax-table)))
  4809. (dolist (c org-emphasis-alist st)
  4810. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4811. (when (fboundp 'abbrev-table-put)
  4812. (abbrev-table-put org-mode-abbrev-table
  4813. :parents (list text-mode-abbrev-table)))
  4814. (defun org-find-invisible-foreground ()
  4815. (let ((candidates (remove
  4816. "unspecified-bg"
  4817. (nconc
  4818. (list (face-background 'default)
  4819. (face-background 'org-default))
  4820. (mapcar
  4821. (lambda (alist)
  4822. (when (boundp alist)
  4823. (cdr (assq 'background-color (symbol-value alist)))))
  4824. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4825. (list (face-foreground 'org-hide))))))
  4826. (car (remove nil candidates))))
  4827. (defun org-current-time (&optional rounding-minutes past)
  4828. "Current time, possibly rounded to ROUNDING-MINUTES.
  4829. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4830. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4831. the rounding returns a past time."
  4832. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4833. (car org-time-stamp-rounding-minutes)))
  4834. (time (decode-time)) res)
  4835. (if (< r 1)
  4836. (current-time)
  4837. (setq res
  4838. (apply 'encode-time
  4839. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4840. (nthcdr 2 time))))
  4841. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4842. (seconds-to-time (- (float-time res) (* r 60)))
  4843. res))))
  4844. (defun org-today ()
  4845. "Return today date, considering `org-extend-today-until'."
  4846. (time-to-days
  4847. (time-subtract (current-time)
  4848. (list 0 (* 3600 org-extend-today-until) 0))))
  4849. ;;;; Font-Lock stuff, including the activators
  4850. (defvar org-mouse-map (make-sparse-keymap))
  4851. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4852. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4853. (when org-mouse-1-follows-link
  4854. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4855. (when org-tab-follows-link
  4856. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  4857. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  4858. (require 'font-lock)
  4859. (defconst org-non-link-chars "]\t\n\r<>")
  4860. (defvar org-link-types-re nil
  4861. "Matches a link that has a url-like prefix like \"http:\"")
  4862. (defvar org-link-re-with-space nil
  4863. "Matches a link with spaces, optional angular brackets around it.")
  4864. (defvar org-link-re-with-space2 nil
  4865. "Matches a link with spaces, optional angular brackets around it.")
  4866. (defvar org-link-re-with-space3 nil
  4867. "Matches a link with spaces, only for internal part in bracket links.")
  4868. (defvar org-angle-link-re nil
  4869. "Matches link with angular brackets, spaces are allowed.")
  4870. (defvar org-plain-link-re nil
  4871. "Matches plain link, without spaces.")
  4872. (defvar org-bracket-link-regexp nil
  4873. "Matches a link in double brackets.")
  4874. (defvar org-bracket-link-analytic-regexp nil
  4875. "Regular expression used to analyze links.
  4876. Here is what the match groups contain after a match:
  4877. 1: http:
  4878. 2: http
  4879. 3: path
  4880. 4: [desc]
  4881. 5: desc")
  4882. (defvar org-bracket-link-analytic-regexp++ nil
  4883. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4884. (defvar org-any-link-re nil
  4885. "Regular expression matching any link.")
  4886. (defconst org-match-sexp-depth 3
  4887. "Number of stacked braces for sub/superscript matching.")
  4888. (defun org-create-multibrace-regexp (left right n)
  4889. "Create a regular expression which will match a balanced sexp.
  4890. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4891. as single character strings.
  4892. The regexp returned will match the entire expression including the
  4893. delimiters. It will also define a single group which contains the
  4894. match except for the outermost delimiters. The maximum depth of
  4895. stacked delimiters is N. Escaping delimiters is not possible."
  4896. (let* ((nothing (concat "[^" left right "]*?"))
  4897. (or "\\|")
  4898. (re nothing)
  4899. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4900. (while (> n 1)
  4901. (setq n (1- n)
  4902. re (concat re or next)
  4903. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4904. (concat left "\\(" re "\\)" right)))
  4905. (defconst org-match-substring-regexp
  4906. (concat
  4907. "\\(\\S-\\)\\([_^]\\)\\("
  4908. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4909. "\\|"
  4910. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4911. "\\|"
  4912. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4913. "The regular expression matching a sub- or superscript.")
  4914. (defconst org-match-substring-with-braces-regexp
  4915. (concat
  4916. "\\(\\S-\\)\\([_^]\\)"
  4917. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4918. "The regular expression matching a sub- or superscript, forcing braces.")
  4919. (defun org-make-link-regexps ()
  4920. "Update the link regular expressions.
  4921. This should be called after the variable `org-link-parameters' has changed."
  4922. (let ((types-re (regexp-opt (org-link-types) t)))
  4923. (setq org-link-types-re
  4924. (concat "\\`" types-re ":")
  4925. org-link-re-with-space
  4926. (concat "<?" types-re ":"
  4927. "\\([^" org-non-link-chars " ]"
  4928. "[^" org-non-link-chars "]*"
  4929. "[^" org-non-link-chars " ]\\)>?")
  4930. org-link-re-with-space2
  4931. (concat "<?" types-re ":"
  4932. "\\([^" org-non-link-chars " ]"
  4933. "[^\t\n\r]*"
  4934. "[^" org-non-link-chars " ]\\)>?")
  4935. org-link-re-with-space3
  4936. (concat "<?" types-re ":"
  4937. "\\([^" org-non-link-chars " ]"
  4938. "[^\t\n\r]*\\)")
  4939. org-angle-link-re
  4940. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  4941. types-re)
  4942. org-plain-link-re
  4943. (concat
  4944. "\\<" types-re ":"
  4945. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  4946. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  4947. org-bracket-link-regexp
  4948. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  4949. org-bracket-link-analytic-regexp
  4950. (concat
  4951. "\\[\\["
  4952. "\\(" types-re ":\\)?"
  4953. "\\([^]]+\\)"
  4954. "\\]"
  4955. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4956. "\\]")
  4957. org-bracket-link-analytic-regexp++
  4958. (concat
  4959. "\\[\\["
  4960. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  4961. "\\([^]]+\\)"
  4962. "\\]"
  4963. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4964. "\\]")
  4965. org-any-link-re
  4966. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  4967. org-angle-link-re "\\)\\|\\("
  4968. org-plain-link-re "\\)"))))
  4969. (org-make-link-regexps)
  4970. (defvar org-emph-face nil)
  4971. (defun org-do-emphasis-faces (limit)
  4972. "Run through the buffer and emphasize strings."
  4973. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4974. (car org-emphasis-regexp-components))))
  4975. (catch :exit
  4976. (while (re-search-forward quick-re limit t)
  4977. (let* ((marker (match-string 2))
  4978. (verbatim? (member marker '("~" "="))))
  4979. (when (save-excursion
  4980. (goto-char (match-beginning 0))
  4981. (and
  4982. ;; Do not match table hlines.
  4983. (not (and (equal marker "+")
  4984. (org-match-line
  4985. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4986. ;; Match full emphasis markup regexp.
  4987. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4988. ;; Do not span over paragraph boundaries.
  4989. (not (string-match-p org-element-paragraph-separate
  4990. (match-string 0)))
  4991. ;; Do not span over cells in table rows.
  4992. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4993. (string-match-p "|" (match-string 4))))))
  4994. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  4995. (font-lock-prepend-text-property
  4996. (match-beginning 2) (match-end 2) 'face face)
  4997. (when verbatim?
  4998. (org-remove-flyspell-overlays-in
  4999. (match-beginning 0) (match-end 0)))
  5000. (add-text-properties (match-beginning 2) (match-end 2)
  5001. '(font-lock-multiline t org-emphasis t))
  5002. (when org-hide-emphasis-markers
  5003. (add-text-properties (match-end 4) (match-beginning 5)
  5004. '(invisible org-link))
  5005. (add-text-properties (match-beginning 3) (match-end 3)
  5006. '(invisible org-link)))
  5007. (throw :exit t))))))))
  5008. (defun org-emphasize (&optional char)
  5009. "Insert or change an emphasis, i.e. a font like bold or italic.
  5010. If there is an active region, change that region to a new emphasis.
  5011. If there is no region, just insert the marker characters and position
  5012. the cursor between them.
  5013. CHAR should be the marker character. If it is a space, it means to
  5014. remove the emphasis of the selected region.
  5015. If CHAR is not given (for example in an interactive call) it will be
  5016. prompted for."
  5017. (interactive)
  5018. (let ((erc org-emphasis-regexp-components)
  5019. (string "") beg end move s)
  5020. (if (org-region-active-p)
  5021. (setq beg (region-beginning)
  5022. end (region-end)
  5023. string (buffer-substring beg end))
  5024. (setq move t))
  5025. (unless char
  5026. (message "Emphasis marker or tag: [%s]"
  5027. (mapconcat #'car org-emphasis-alist ""))
  5028. (setq char (read-char-exclusive)))
  5029. (if (equal char ?\s)
  5030. (setq s ""
  5031. move nil)
  5032. (unless (assoc (char-to-string char) org-emphasis-alist)
  5033. (user-error "No such emphasis marker: \"%c\"" char))
  5034. (setq s (char-to-string char)))
  5035. (while (and (> (length string) 1)
  5036. (equal (substring string 0 1) (substring string -1))
  5037. (assoc (substring string 0 1) org-emphasis-alist))
  5038. (setq string (substring string 1 -1)))
  5039. (setq string (concat s string s))
  5040. (when beg (delete-region beg end))
  5041. (unless (or (bolp)
  5042. (string-match (concat "[" (nth 0 erc) "\n]")
  5043. (char-to-string (char-before (point)))))
  5044. (insert " "))
  5045. (unless (or (eobp)
  5046. (string-match (concat "[" (nth 1 erc) "\n]")
  5047. (char-to-string (char-after (point)))))
  5048. (insert " ") (backward-char 1))
  5049. (insert string)
  5050. (and move (backward-char 1))))
  5051. (defconst org-nonsticky-props
  5052. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5053. (defsubst org-rear-nonsticky-at (pos)
  5054. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5055. (defun org-activate-links (limit)
  5056. "Add link properties to links.
  5057. This includes angle, plain, and bracket links."
  5058. (catch :exit
  5059. (while (re-search-forward org-any-link-re limit t)
  5060. (let* ((start (match-beginning 0))
  5061. (end (match-end 0))
  5062. (style (cond ((eq ?< (char-after start)) 'angle)
  5063. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5064. (t 'plain))))
  5065. (when (and (memq style org-highlight-links)
  5066. ;; Do not confuse plain links with tags.
  5067. (not (and (eq style 'plain)
  5068. (let ((face (get-text-property
  5069. (max (1- start) (point-min)) 'face)))
  5070. (if (consp face) (memq 'org-tag face)
  5071. (eq 'org-tag face))))))
  5072. (let* ((link-object (save-excursion
  5073. (goto-char start)
  5074. (save-match-data (org-element-link-parser))))
  5075. (link (org-element-property :raw-link link-object))
  5076. (type (org-element-property :type link-object))
  5077. (path (org-element-property :path link-object))
  5078. (properties ;for link's visible part
  5079. (list
  5080. 'face (pcase (org-link-get-parameter type :face)
  5081. ((and (pred functionp) face) (funcall face path))
  5082. ((and (pred facep) face) face)
  5083. ((and (pred consp) face) face) ;anonymous
  5084. (_ 'org-link))
  5085. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5086. 'highlight)
  5087. 'keymap (or (org-link-get-parameter type :keymap)
  5088. org-mouse-map)
  5089. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5090. ((and (pred stringp) echo) echo)
  5091. ((and (pred functionp) echo) echo)
  5092. (_ (concat "LINK: " link)))
  5093. 'htmlize-link (pcase (org-link-get-parameter type
  5094. :htmlize-link)
  5095. ((and (pred functionp) f) (funcall f))
  5096. (_ `(:uri ,link)))
  5097. 'font-lock-multiline t)))
  5098. (org-remove-flyspell-overlays-in start end)
  5099. (org-rear-nonsticky-at end)
  5100. (if (not (eq 'bracket style))
  5101. (add-text-properties start end properties)
  5102. ;; Handle invisible parts in bracket links.
  5103. (remove-text-properties start end '(invisible nil))
  5104. (let ((hidden
  5105. (append `(invisible
  5106. ,(or (org-link-get-parameter type :display)
  5107. 'org-link))
  5108. properties))
  5109. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5110. (visible-end (or (match-end 4) (match-end 2))))
  5111. (add-text-properties start visible-start hidden)
  5112. (add-text-properties visible-start visible-end properties)
  5113. (add-text-properties visible-end end hidden)
  5114. (org-rear-nonsticky-at visible-start)
  5115. (org-rear-nonsticky-at visible-end)))
  5116. (let ((f (org-link-get-parameter type :activate-func)))
  5117. (when (functionp f)
  5118. (funcall f start end path (eq style 'bracket))))
  5119. (throw :exit t))))) ;signal success
  5120. nil))
  5121. (defun org-activate-code (limit)
  5122. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5123. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5124. (remove-text-properties (match-beginning 0) (match-end 0)
  5125. '(display t invisible t intangible t))
  5126. t))
  5127. (defcustom org-src-fontify-natively t
  5128. "When non-nil, fontify code in code blocks.
  5129. See also the `org-block' face."
  5130. :type 'boolean
  5131. :version "26.1"
  5132. :package-version '(Org . "8.3")
  5133. :group 'org-appearance
  5134. :group 'org-babel)
  5135. (defcustom org-allow-promoting-top-level-subtree nil
  5136. "When non-nil, allow promoting a top level subtree.
  5137. The leading star of the top level headline will be replaced
  5138. by a #."
  5139. :type 'boolean
  5140. :version "24.1"
  5141. :group 'org-appearance)
  5142. (defun org-fontify-meta-lines-and-blocks (limit)
  5143. (condition-case nil
  5144. (org-fontify-meta-lines-and-blocks-1 limit)
  5145. (error (message "org-mode fontification error in %S at %d"
  5146. (current-buffer)
  5147. (line-number-at-pos)))))
  5148. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5149. "Fontify #+ lines and blocks."
  5150. (let ((case-fold-search t))
  5151. (when (re-search-forward
  5152. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5153. limit t)
  5154. (let ((beg (match-beginning 0))
  5155. (block-start (match-end 0))
  5156. (block-end nil)
  5157. (lang (match-string 7))
  5158. (beg1 (line-beginning-position 2))
  5159. (dc1 (downcase (match-string 2)))
  5160. (dc3 (downcase (match-string 3)))
  5161. end end1 quoting block-type)
  5162. (cond
  5163. ((and (match-end 4) (equal dc3 "+begin"))
  5164. ;; Truly a block
  5165. (setq block-type (downcase (match-string 5))
  5166. quoting (member block-type org-protecting-blocks))
  5167. (when (re-search-forward
  5168. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5169. nil t) ;; on purpose, we look further than LIMIT
  5170. (setq end (min (point-max) (match-end 0))
  5171. end1 (min (point-max) (1- (match-beginning 0))))
  5172. (setq block-end (match-beginning 0))
  5173. (when quoting
  5174. (org-remove-flyspell-overlays-in beg1 end1)
  5175. (remove-text-properties beg end
  5176. '(display t invisible t intangible t)))
  5177. (add-text-properties
  5178. beg end '(font-lock-fontified t font-lock-multiline t))
  5179. (add-text-properties beg beg1 '(face org-meta-line))
  5180. (org-remove-flyspell-overlays-in beg beg1)
  5181. (add-text-properties ; For end_src
  5182. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5183. (org-remove-flyspell-overlays-in end1 end)
  5184. (cond
  5185. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5186. (org-src-font-lock-fontify-block lang block-start block-end)
  5187. (add-text-properties beg1 block-end '(src-block t)))
  5188. (quoting
  5189. (add-text-properties beg1 (min (point-max) (1+ end1))
  5190. (list 'face
  5191. (list :inherit
  5192. (let ((face-name
  5193. (intern (format "org-block-%s" lang))))
  5194. (append (and (facep face-name) (list face-name))
  5195. '(org-block))))))) ; end of source block
  5196. ((not org-fontify-quote-and-verse-blocks))
  5197. ((string= block-type "quote")
  5198. (add-face-text-property
  5199. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5200. ((string= block-type "verse")
  5201. (add-face-text-property
  5202. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5203. (add-text-properties beg beg1 '(face org-block-begin-line))
  5204. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5205. '(face org-block-end-line))
  5206. t))
  5207. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5208. (org-remove-flyspell-overlays-in
  5209. (match-beginning 0)
  5210. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5211. (add-text-properties
  5212. beg (match-end 3)
  5213. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5214. '(font-lock-fontified t invisible t)
  5215. '(font-lock-fontified t face org-document-info-keyword)))
  5216. (add-text-properties
  5217. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5218. (if (string-equal dc1 "+title:")
  5219. '(font-lock-fontified t face org-document-title)
  5220. '(font-lock-fontified t face org-document-info))))
  5221. ((string-prefix-p "+caption" dc1)
  5222. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5223. (remove-text-properties (match-beginning 0) (match-end 0)
  5224. '(display t invisible t intangible t))
  5225. ;; Handle short captions.
  5226. (save-excursion
  5227. (beginning-of-line)
  5228. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5229. (add-text-properties (line-beginning-position) (match-end 1)
  5230. '(font-lock-fontified t face org-meta-line))
  5231. (add-text-properties (match-end 0) (line-end-position)
  5232. '(font-lock-fontified t face org-block))
  5233. t)
  5234. ((member dc3 '(" " ""))
  5235. (org-remove-flyspell-overlays-in beg (match-end 0))
  5236. (add-text-properties
  5237. beg (match-end 0)
  5238. '(font-lock-fontified t face font-lock-comment-face)))
  5239. (t ;; just any other in-buffer setting, but not indented
  5240. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5241. (remove-text-properties (match-beginning 0) (match-end 0)
  5242. '(display t invisible t intangible t))
  5243. (add-text-properties beg (match-end 0)
  5244. '(font-lock-fontified t face org-meta-line))
  5245. t))))))
  5246. (defun org-fontify-drawers (limit)
  5247. "Fontify drawers."
  5248. (when (re-search-forward org-drawer-regexp limit t)
  5249. (add-text-properties
  5250. (match-beginning 0) (match-end 0)
  5251. '(font-lock-fontified t face org-special-keyword))
  5252. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5253. t))
  5254. (defun org-fontify-macros (limit)
  5255. "Fontify macros."
  5256. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5257. (add-text-properties
  5258. (match-beginning 0) (match-end 0)
  5259. '(font-lock-fontified t face org-macro))
  5260. (when org-hide-macro-markers
  5261. (add-text-properties (match-end 2) (match-beginning 2)
  5262. '(invisible t))
  5263. (add-text-properties (match-beginning 1) (match-end 1)
  5264. '(invisible t)))
  5265. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5266. t))
  5267. (defun org-activate-footnote-links (limit)
  5268. "Add text properties for footnotes."
  5269. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5270. (when fn
  5271. (let* ((beg (nth 1 fn))
  5272. (end (nth 2 fn))
  5273. (label (car fn))
  5274. (referencep (/= (line-beginning-position) beg)))
  5275. (when (and referencep (nth 3 fn))
  5276. (save-excursion
  5277. (goto-char beg)
  5278. (search-forward (or label "fn:"))
  5279. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5280. (add-text-properties beg end
  5281. (list 'mouse-face 'highlight
  5282. 'keymap org-mouse-map
  5283. 'help-echo
  5284. (if referencep "Footnote reference"
  5285. "Footnote definition")
  5286. 'font-lock-fontified t
  5287. 'font-lock-multiline t
  5288. 'face 'org-footnote))))))
  5289. (defun org-activate-dates (limit)
  5290. "Add text properties for dates."
  5291. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5292. (not (equal (char-before (match-beginning 0)) 91)))
  5293. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5294. (add-text-properties (match-beginning 0) (match-end 0)
  5295. (list 'mouse-face 'highlight
  5296. 'keymap org-mouse-map))
  5297. (org-rear-nonsticky-at (match-end 0))
  5298. (when org-display-custom-times
  5299. ;; If it's a date range, activate custom time for second date.
  5300. (when (match-end 3)
  5301. (org-display-custom-time (match-beginning 3) (match-end 3)))
  5302. (org-display-custom-time (match-beginning 1) (match-end 1)))
  5303. t))
  5304. (defvar-local org-target-link-regexp nil
  5305. "Regular expression matching radio targets in plain text.")
  5306. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5307. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5308. border border border))
  5309. "Regular expression matching a link target.")
  5310. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5311. "Regular expression matching a radio target.")
  5312. (defconst org-any-target-regexp
  5313. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5314. "Regular expression matching any target.")
  5315. (defun org-activate-target-links (limit)
  5316. "Add text properties for target matches."
  5317. (when org-target-link-regexp
  5318. (let ((case-fold-search t))
  5319. (when (re-search-forward org-target-link-regexp limit t)
  5320. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5321. (add-text-properties (match-beginning 1) (match-end 1)
  5322. (list 'mouse-face 'highlight
  5323. 'keymap org-mouse-map
  5324. 'help-echo "Radio target link"
  5325. 'org-linked-text t))
  5326. (org-rear-nonsticky-at (match-end 1))
  5327. t))))
  5328. (defun org-update-radio-target-regexp ()
  5329. "Find all radio targets in this file and update the regular expression.
  5330. Also refresh fontification if needed."
  5331. (interactive)
  5332. (let ((old-regexp org-target-link-regexp)
  5333. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5334. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5335. (targets
  5336. (org-with-wide-buffer
  5337. (goto-char (point-min))
  5338. (let (rtn)
  5339. (while (re-search-forward org-radio-target-regexp nil t)
  5340. ;; Make sure point is really within the object.
  5341. (backward-char)
  5342. (let ((obj (org-element-context)))
  5343. (when (eq (org-element-type obj) 'radio-target)
  5344. (cl-pushnew (org-element-property :value obj) rtn
  5345. :test #'equal))))
  5346. rtn))))
  5347. (setq org-target-link-regexp
  5348. (and targets
  5349. (concat before-re
  5350. (mapconcat
  5351. (lambda (x)
  5352. (replace-regexp-in-string
  5353. " +" "\\s-+" (regexp-quote x) t t))
  5354. targets
  5355. "\\|")
  5356. after-re)))
  5357. (unless (equal old-regexp org-target-link-regexp)
  5358. ;; Clean-up cache.
  5359. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5360. ((not org-target-link-regexp) old-regexp)
  5361. (t
  5362. (concat before-re
  5363. (mapconcat
  5364. (lambda (re)
  5365. (substring re (length before-re)
  5366. (- (length after-re))))
  5367. (list old-regexp org-target-link-regexp)
  5368. "\\|")
  5369. after-re)))))
  5370. (org-with-wide-buffer
  5371. (goto-char (point-min))
  5372. (while (re-search-forward regexp nil t)
  5373. (org-element-cache-refresh (match-beginning 1)))))
  5374. ;; Re fontify buffer.
  5375. (when (memq 'radio org-highlight-links)
  5376. (org-restart-font-lock)))))
  5377. (defvar org-latex-and-related-regexp nil
  5378. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5379. (defun org-compute-latex-and-related-regexp ()
  5380. "Compute regular expression for LaTeX, entities and sub/superscript.
  5381. Result depends on variable `org-highlight-latex-and-related'."
  5382. (setq-local
  5383. org-latex-and-related-regexp
  5384. (let* ((re-sub
  5385. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5386. ((eq org-use-sub-superscripts '{})
  5387. (list org-match-substring-with-braces-regexp))
  5388. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5389. (re-latex
  5390. (when (memq 'latex org-highlight-latex-and-related)
  5391. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5392. (delq nil
  5393. (mapcar (lambda (x)
  5394. (and (member (car x) matchers) (nth 1 x)))
  5395. org-latex-regexps)))))
  5396. (re-entities
  5397. (when (memq 'entities org-highlight-latex-and-related)
  5398. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5399. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5400. (defun org-do-latex-and-related (limit)
  5401. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5402. LIMIT bounds the search for syntax to highlight. Stop at first
  5403. highlighted object, if any. Return t if some highlighting was
  5404. done, nil otherwise."
  5405. (when (org-string-nw-p org-latex-and-related-regexp)
  5406. (catch 'found
  5407. (while (re-search-forward org-latex-and-related-regexp limit t)
  5408. (unless
  5409. (cl-some
  5410. (lambda (f)
  5411. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5412. (save-excursion
  5413. (goto-char (1+ (match-beginning 0)))
  5414. (face-at-point nil t)))
  5415. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5416. '(?_ ?^))
  5417. 1
  5418. 0)))
  5419. (font-lock-prepend-text-property
  5420. (+ offset (match-beginning 0)) (match-end 0)
  5421. 'face 'org-latex-and-related)
  5422. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5423. '(font-lock-multiline t)))
  5424. (throw 'found t)))
  5425. nil)))
  5426. (defun org-restart-font-lock ()
  5427. "Restart `font-lock-mode', to force refontification."
  5428. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5429. (font-lock-mode -1)
  5430. (font-lock-mode 1)))
  5431. (defun org-activate-tags (limit)
  5432. (when (re-search-forward
  5433. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5434. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5435. (add-text-properties (match-beginning 1) (match-end 1)
  5436. (list 'mouse-face 'highlight
  5437. 'keymap org-mouse-map))
  5438. (org-rear-nonsticky-at (match-end 1))
  5439. t))
  5440. (defun org-outline-level ()
  5441. "Compute the outline level of the heading at point.
  5442. If this is called at a normal headline, the level is the number
  5443. of stars. Use `org-reduced-level' to remove the effect of
  5444. `org-odd-levels'. Unlike to `org-current-level', this function
  5445. takes into consideration inlinetasks."
  5446. (org-with-wide-buffer
  5447. (end-of-line)
  5448. (if (re-search-backward org-outline-regexp-bol nil t)
  5449. (1- (- (match-end 0) (match-beginning 0)))
  5450. 0)))
  5451. (defvar org-font-lock-keywords nil)
  5452. (defsubst org-re-property (property &optional literal allow-null value)
  5453. "Return a regexp matching a PROPERTY line.
  5454. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5455. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5456. non-nil, match properties even without a value.
  5457. Match group 3 is set to the value when it exists. If there is no
  5458. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5459. With optional argument VALUE, match only property lines with
  5460. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5461. unless LITERAL is non-nil."
  5462. (concat
  5463. "^\\(?4:[ \t]*\\)"
  5464. (format "\\(?1::\\(?2:%s\\):\\)"
  5465. (if literal property (regexp-quote property)))
  5466. (cond (value
  5467. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5468. (if literal value (regexp-quote value))))
  5469. (allow-null
  5470. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5471. (t
  5472. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5473. (defconst org-property-re
  5474. (org-re-property "\\S-+" 'literal t)
  5475. "Regular expression matching a property line.
  5476. There are four matching groups:
  5477. 1: :PROPKEY: including the leading and trailing colon,
  5478. 2: PROPKEY without the leading and trailing colon,
  5479. 3: PROPVAL without leading or trailing spaces,
  5480. 4: the indentation of the current line,
  5481. 5: trailing whitespace.")
  5482. (defvar org-font-lock-hook nil
  5483. "Functions to be called for special font lock stuff.")
  5484. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5485. (defvar org-font-lock-set-keywords-hook nil
  5486. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5487. This is called after `org-font-lock-extra-keywords' is defined, but before
  5488. it is installed to be used by font lock. This can be useful if something
  5489. needs to be inserted at a specific position in the font-lock sequence.")
  5490. (defun org-font-lock-hook (limit)
  5491. "Run `org-font-lock-hook' within LIMIT."
  5492. (run-hook-with-args 'org-font-lock-hook limit))
  5493. (defun org-set-font-lock-defaults ()
  5494. "Set font lock defaults for the current buffer."
  5495. (let* ((em org-fontify-emphasized-text)
  5496. (lk org-highlight-links)
  5497. (org-font-lock-extra-keywords
  5498. (list
  5499. ;; Call the hook
  5500. '(org-font-lock-hook)
  5501. ;; Headlines
  5502. `(,(if org-fontify-whole-heading-line
  5503. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5504. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5505. (1 (org-get-level-face 1))
  5506. (2 (org-get-level-face 2))
  5507. (3 (org-get-level-face 3)))
  5508. ;; Table lines
  5509. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5510. (1 'org-table t))
  5511. ;; Table internals
  5512. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5513. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5514. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5515. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5516. ;; Drawers
  5517. '(org-fontify-drawers)
  5518. ;; Properties
  5519. (list org-property-re
  5520. '(1 'org-special-keyword t)
  5521. '(3 'org-property-value t))
  5522. ;; Link related fontification.
  5523. '(org-activate-links)
  5524. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5525. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5526. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5527. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5528. ;; Targets.
  5529. (list org-any-target-regexp '(0 'org-target t))
  5530. ;; Diary sexps.
  5531. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5532. ;; Macro
  5533. '(org-fontify-macros)
  5534. ;; TODO keyword
  5535. (list (format org-heading-keyword-regexp-format
  5536. org-todo-regexp)
  5537. '(2 (org-get-todo-face 2) t))
  5538. ;; DONE
  5539. (if org-fontify-done-headline
  5540. (list (format org-heading-keyword-regexp-format
  5541. (concat
  5542. "\\(?:"
  5543. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5544. "\\)"))
  5545. '(2 'org-headline-done t))
  5546. nil)
  5547. ;; Priorities
  5548. '(org-font-lock-add-priority-faces)
  5549. ;; Tags
  5550. '(org-font-lock-add-tag-faces)
  5551. ;; Tags groups
  5552. (when (and org-group-tags org-tag-groups-alist)
  5553. (list (concat org-outline-regexp-bol ".+\\(:"
  5554. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5555. ":\\).*$")
  5556. '(1 'org-tag-group prepend)))
  5557. ;; Special keywords
  5558. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5559. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5560. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5561. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5562. ;; Emphasis
  5563. (when em '(org-do-emphasis-faces))
  5564. ;; Checkboxes
  5565. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5566. 1 'org-checkbox prepend)
  5567. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5568. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5569. (0 (org-get-checkbox-statistics-face) t)))
  5570. ;; Description list items
  5571. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5572. 1 'org-list-dt prepend)
  5573. ;; ARCHIVEd headings
  5574. (list (concat
  5575. org-outline-regexp-bol
  5576. "\\(.*:" org-archive-tag ":.*\\)")
  5577. '(1 'org-archived prepend))
  5578. ;; Specials
  5579. '(org-do-latex-and-related)
  5580. '(org-fontify-entities)
  5581. '(org-raise-scripts)
  5582. ;; Code
  5583. '(org-activate-code (1 'org-code t))
  5584. ;; COMMENT
  5585. (list (format
  5586. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5587. org-todo-regexp
  5588. org-comment-string)
  5589. '(9 'org-special-keyword t))
  5590. ;; Blocks and meta lines
  5591. '(org-fontify-meta-lines-and-blocks))))
  5592. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5593. (run-hooks 'org-font-lock-set-keywords-hook)
  5594. ;; Now set the full font-lock-keywords
  5595. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5596. (setq-local font-lock-defaults
  5597. '(org-font-lock-keywords t nil nil backward-paragraph))
  5598. (kill-local-variable 'font-lock-keywords)
  5599. nil))
  5600. (defun org-toggle-pretty-entities ()
  5601. "Toggle the composition display of entities as UTF8 characters."
  5602. (interactive)
  5603. (setq-local org-pretty-entities (not org-pretty-entities))
  5604. (org-restart-font-lock)
  5605. (if org-pretty-entities
  5606. (message "Entities are now displayed as UTF8 characters")
  5607. (save-restriction
  5608. (widen)
  5609. (decompose-region (point-min) (point-max))
  5610. (message "Entities are now displayed as plain text"))))
  5611. (defvar-local org-custom-properties-overlays nil
  5612. "List of overlays used for custom properties.")
  5613. (defun org-toggle-custom-properties-visibility ()
  5614. "Display or hide properties in `org-custom-properties'."
  5615. (interactive)
  5616. (if org-custom-properties-overlays
  5617. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5618. (setq org-custom-properties-overlays nil))
  5619. (when org-custom-properties
  5620. (org-with-wide-buffer
  5621. (goto-char (point-min))
  5622. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5623. (while (re-search-forward regexp nil t)
  5624. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5625. (when (and end (< (point) end))
  5626. ;; Hide first custom property in current drawer.
  5627. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5628. (overlay-put o 'invisible t)
  5629. (overlay-put o 'org-custom-property t)
  5630. (push o org-custom-properties-overlays))
  5631. ;; Hide additional custom properties in the same drawer.
  5632. (while (re-search-forward regexp end t)
  5633. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5634. (overlay-put o 'invisible t)
  5635. (overlay-put o 'org-custom-property t)
  5636. (push o org-custom-properties-overlays)))))
  5637. ;; Each entry is limited to a single property drawer.
  5638. (outline-next-heading)))))))
  5639. (defun org-fontify-entities (limit)
  5640. "Find an entity to fontify."
  5641. (let (ee)
  5642. (when org-pretty-entities
  5643. (catch 'match
  5644. ;; "\_ "-family is left out on purpose. Only the first one,
  5645. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5646. ;; confusing when adding a second white space character.
  5647. (while (re-search-forward
  5648. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5649. limit t)
  5650. (when (and (not (org-at-comment-p))
  5651. (setq ee (org-entity-get (match-string 1)))
  5652. (= (length (nth 6 ee)) 1))
  5653. (let* ((end (if (equal (match-string 2) "{}")
  5654. (match-end 2)
  5655. (match-end 1))))
  5656. (add-text-properties
  5657. (match-beginning 0) end
  5658. (list 'font-lock-fontified t))
  5659. (compose-region (match-beginning 0) end
  5660. (nth 6 ee) nil)
  5661. (backward-char 1)
  5662. (throw 'match t))))
  5663. nil))))
  5664. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5665. "Fontify string S like in Org mode."
  5666. (with-temp-buffer
  5667. (insert s)
  5668. (let ((org-odd-levels-only odd-levels))
  5669. (org-mode)
  5670. (org-font-lock-ensure)
  5671. (buffer-string))))
  5672. (defvar org-m nil)
  5673. (defvar org-l nil)
  5674. (defvar org-f nil)
  5675. (defun org-get-level-face (n)
  5676. "Get the right face for match N in font-lock matching of headlines."
  5677. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5678. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5679. (if org-cycle-level-faces
  5680. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5681. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5682. (cond
  5683. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5684. ((eq n 2) org-f)
  5685. (t (unless org-level-color-stars-only org-f))))
  5686. (defun org-face-from-face-or-color (context inherit face-or-color)
  5687. "Create a face list that inherits INHERIT, but sets the foreground color.
  5688. When FACE-OR-COLOR is not a string, just return it."
  5689. (if (stringp face-or-color)
  5690. (list :inherit inherit
  5691. (cdr (assoc context org-faces-easy-properties))
  5692. face-or-color)
  5693. face-or-color))
  5694. (defun org-get-todo-face (kwd)
  5695. "Get the right face for a TODO keyword KWD.
  5696. If KWD is a number, get the corresponding match group."
  5697. (when (numberp kwd) (setq kwd (match-string kwd)))
  5698. (or (org-face-from-face-or-color
  5699. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5700. (and (member kwd org-done-keywords) 'org-done)
  5701. 'org-todo))
  5702. (defun org-get-priority-face (priority)
  5703. "Get the right face for PRIORITY.
  5704. PRIORITY is a character."
  5705. (or (org-face-from-face-or-color
  5706. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5707. 'org-priority))
  5708. (defun org-get-tag-face (tag)
  5709. "Get the right face for TAG.
  5710. If TAG is a number, get the corresponding match group."
  5711. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5712. (or (org-face-from-face-or-color
  5713. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5714. 'org-tag)))
  5715. (defun org-font-lock-add-priority-faces (limit)
  5716. "Add the special priority faces."
  5717. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5718. (add-text-properties
  5719. (match-beginning 1) (match-end 1)
  5720. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5721. 'font-lock-fontified t))))
  5722. (defun org-font-lock-add-tag-faces (limit)
  5723. "Add the special tag faces."
  5724. (when (and org-tag-faces org-tags-special-faces-re)
  5725. (while (re-search-forward org-tags-special-faces-re limit t)
  5726. (add-text-properties (match-beginning 1) (match-end 1)
  5727. (list 'face (org-get-tag-face 1)
  5728. 'font-lock-fontified t))
  5729. (backward-char 1))))
  5730. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5731. "Remove fontification and activation overlays from links."
  5732. (font-lock-default-unfontify-region beg end)
  5733. (let* ((buffer-undo-list t)
  5734. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5735. (inhibit-modification-hooks t)
  5736. deactivate-mark buffer-file-name buffer-file-truename)
  5737. (decompose-region beg end)
  5738. (remove-text-properties beg end
  5739. '(mouse-face t keymap t org-linked-text t
  5740. invisible t intangible t
  5741. org-emphasis t))
  5742. (org-remove-font-lock-display-properties beg end)))
  5743. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5744. ((raise 0.3) (height 0.7))
  5745. ((raise -0.5))
  5746. ((raise 0.5)))
  5747. "Display properties for showing superscripts and subscripts.")
  5748. (defun org-remove-font-lock-display-properties (beg end)
  5749. "Remove specific display properties that have been added by font lock.
  5750. The will remove the raise properties that are used to show superscripts
  5751. and subscripts."
  5752. (let (next prop)
  5753. (while (< beg end)
  5754. (setq next (next-single-property-change beg 'display nil end)
  5755. prop (get-text-property beg 'display))
  5756. (when (member prop org-script-display)
  5757. (put-text-property beg next 'display nil))
  5758. (setq beg next))))
  5759. (defun org-raise-scripts (limit)
  5760. "Add raise properties to sub/superscripts."
  5761. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5762. (re-search-forward
  5763. (if (eq org-use-sub-superscripts t)
  5764. org-match-substring-regexp
  5765. org-match-substring-with-braces-regexp)
  5766. limit t))
  5767. (let* ((pos (point)) table-p comment-p
  5768. (mpos (match-beginning 3))
  5769. (emph-p (get-text-property mpos 'org-emphasis))
  5770. (link-p (get-text-property mpos 'mouse-face))
  5771. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5772. (goto-char (point-at-bol))
  5773. (setq table-p (looking-at-p org-table-dataline-regexp)
  5774. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5775. (goto-char pos)
  5776. ;; Handle a_b^c
  5777. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5778. (unless (or comment-p emph-p link-p keyw-p)
  5779. (put-text-property (match-beginning 3) (match-end 0)
  5780. 'display
  5781. (if (equal (char-after (match-beginning 2)) ?^)
  5782. (nth (if table-p 3 1) org-script-display)
  5783. (nth (if table-p 2 0) org-script-display)))
  5784. (add-text-properties (match-beginning 2) (match-end 2)
  5785. (list 'invisible t))
  5786. (when (and (eq (char-after (match-beginning 3)) ?{)
  5787. (eq (char-before (match-end 3)) ?}))
  5788. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5789. (list 'invisible t))
  5790. (add-text-properties (1- (match-end 3)) (match-end 3)
  5791. (list 'invisible t))))
  5792. t)))
  5793. ;;;; Visibility cycling, including org-goto and indirect buffer
  5794. ;;; Cycling
  5795. (defvar-local org-cycle-global-status nil)
  5796. (put 'org-cycle-global-status 'org-state t)
  5797. (defvar-local org-cycle-subtree-status nil)
  5798. (put 'org-cycle-subtree-status 'org-state t)
  5799. (defvar org-inlinetask-min-level)
  5800. (defun org-unlogged-message (&rest args)
  5801. "Display a message, but avoid logging it in the *Messages* buffer."
  5802. (let ((message-log-max nil))
  5803. (apply 'message args)))
  5804. ;;;###autoload
  5805. (defun org-cycle (&optional arg)
  5806. "TAB-action and visibility cycling for Org mode.
  5807. This is the command invoked in Org mode by the `TAB' key. Its main
  5808. purpose is outline visibility cycling, but it also invokes other actions
  5809. in special contexts.
  5810. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5811. the entire
  5812. buffer through 3 states (global cycling)
  5813. 1. OVERVIEW: Show only top-level headlines.
  5814. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5815. 3. SHOW ALL: Show everything.
  5816. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5817. switch to the startup visibility,
  5818. determined by the variable `org-startup-folded', and by any VISIBILITY
  5819. properties in the buffer.
  5820. With a `\\[universal-argument] \\[universal-argument] \
  5821. \\[universal-argument]' prefix argument, show the entire buffer, including
  5822. any drawers.
  5823. When inside a table, re-align the table and move to the next field.
  5824. When point is at the beginning of a headline, rotate the subtree started
  5825. by this line through 3 different states (local cycling)
  5826. 1. FOLDED: Only the main headline is shown.
  5827. 2. CHILDREN: The main headline and the direct children are shown.
  5828. From this state, you can move to one of the children
  5829. and zoom in further.
  5830. 3. SUBTREE: Show the entire subtree, including body text.
  5831. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5832. When point is at the beginning of an empty headline and the variable
  5833. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5834. of the headline by demoting and promoting it to likely levels. This
  5835. speeds up creation document structure by pressing `TAB' once or several
  5836. times right after creating a new headline.
  5837. When there is a numeric prefix, go up to a heading with level ARG, do
  5838. a `show-subtree' and return to the previous cursor position. If ARG
  5839. is negative, go up that many levels.
  5840. When point is not at the beginning of a headline, execute the global
  5841. binding for `TAB', which is re-indenting the line. See the option
  5842. `org-cycle-emulate-tab' for details.
  5843. As a special case, if point is at the beginning of the buffer and there is
  5844. no headline in line 1, this function will act as if called with prefix arg
  5845. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  5846. prefix arg, but only
  5847. if the variable `org-cycle-global-at-bob' is t."
  5848. (interactive "P")
  5849. (org-load-modules-maybe)
  5850. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5851. (and org-cycle-level-after-item/entry-creation
  5852. (or (org-cycle-level)
  5853. (org-cycle-item-indentation))))
  5854. (let* ((limit-level
  5855. (or org-cycle-max-level
  5856. (and (boundp 'org-inlinetask-min-level)
  5857. org-inlinetask-min-level
  5858. (1- org-inlinetask-min-level))))
  5859. (nstars (and limit-level
  5860. (if org-odd-levels-only
  5861. (and limit-level (1- (* limit-level 2)))
  5862. limit-level)))
  5863. (org-outline-regexp
  5864. (if (not (derived-mode-p 'org-mode))
  5865. outline-regexp
  5866. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5867. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5868. (not (looking-at org-outline-regexp))))
  5869. (org-cycle-hook
  5870. (if bob-special
  5871. (delq 'org-optimize-window-after-visibility-change
  5872. (copy-sequence org-cycle-hook))
  5873. org-cycle-hook))
  5874. (pos (point)))
  5875. (cond
  5876. ((equal arg '(16))
  5877. (setq last-command 'dummy)
  5878. (org-set-startup-visibility)
  5879. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5880. ((equal arg '(64))
  5881. (outline-show-all)
  5882. (org-unlogged-message "Entire buffer visible, including drawers"))
  5883. ((equal arg '(4)) (org-cycle-internal-global))
  5884. ;; Try hiding block at point.
  5885. ((org-hide-block-toggle-maybe))
  5886. ;; Try cdlatex TAB completion
  5887. ((org-try-cdlatex-tab))
  5888. ;; Table: enter it or move to the next field.
  5889. ((org-at-table-p 'any)
  5890. (if (org-at-table.el-p)
  5891. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  5892. Use `\\[org-edit-special]' to edit table.el tables"))
  5893. (if arg (org-table-edit-field t)
  5894. (org-table-justify-field-maybe)
  5895. (call-interactively 'org-table-next-field))))
  5896. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  5897. ;; Global cycling: delegate to `org-cycle-internal-global'.
  5898. (bob-special (org-cycle-internal-global))
  5899. ;; Drawers: delegate to `org-flag-drawer'.
  5900. ((save-excursion
  5901. (beginning-of-line 1)
  5902. (looking-at org-drawer-regexp))
  5903. (org-flag-drawer ; toggle block visibility
  5904. (not (get-char-property (match-end 0) 'invisible))))
  5905. ;; Show-subtree, ARG levels up from here.
  5906. ((integerp arg)
  5907. (save-excursion
  5908. (org-back-to-heading)
  5909. (outline-up-heading (if (< arg 0) (- arg)
  5910. (- (funcall outline-level) arg)))
  5911. (org-show-subtree)))
  5912. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5913. ((and (featurep 'org-inlinetask)
  5914. (org-inlinetask-at-task-p)
  5915. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5916. (org-inlinetask-toggle-visibility))
  5917. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5918. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  5919. (save-excursion (move-beginning-of-line 1)
  5920. (looking-at org-outline-regexp)))
  5921. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5922. (org-cycle-internal-local))
  5923. ;; From there: TAB emulation and template completion.
  5924. (buffer-read-only (org-back-to-heading))
  5925. ((run-hook-with-args-until-success
  5926. 'org-tab-after-check-for-cycling-hook))
  5927. ((run-hook-with-args-until-success
  5928. 'org-tab-before-tab-emulation-hook))
  5929. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5930. (or (not (bolp))
  5931. (not (looking-at org-outline-regexp))))
  5932. (call-interactively (global-key-binding "\t")))
  5933. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  5934. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5935. (or (and (eq org-cycle-emulate-tab 'white)
  5936. (= (match-end 0) (point-at-eol)))
  5937. (and (eq org-cycle-emulate-tab 'whitestart)
  5938. (>= (match-end 0) pos))))
  5939. t
  5940. (eq org-cycle-emulate-tab t))
  5941. (call-interactively (global-key-binding "\t")))
  5942. (t (save-excursion
  5943. (org-back-to-heading)
  5944. (org-cycle)))))))
  5945. (defun org-cycle-internal-global ()
  5946. "Do the global cycling action."
  5947. ;; Hack to avoid display of messages for .org attachments in Gnus
  5948. (let ((ga (string-match "\\*fontification" (buffer-name))))
  5949. (cond
  5950. ((and (eq last-command this-command)
  5951. (eq org-cycle-global-status 'overview))
  5952. ;; We just created the overview - now do table of contents
  5953. ;; This can be slow in very large buffers, so indicate action
  5954. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5955. (unless ga (org-unlogged-message "CONTENTS..."))
  5956. (org-content)
  5957. (unless ga (org-unlogged-message "CONTENTS...done"))
  5958. (setq org-cycle-global-status 'contents)
  5959. (run-hook-with-args 'org-cycle-hook 'contents))
  5960. ((and (eq last-command this-command)
  5961. (eq org-cycle-global-status 'contents))
  5962. ;; We just showed the table of contents - now show everything
  5963. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5964. (outline-show-all)
  5965. (unless ga (org-unlogged-message "SHOW ALL"))
  5966. (setq org-cycle-global-status 'all)
  5967. (run-hook-with-args 'org-cycle-hook 'all))
  5968. (t
  5969. ;; Default action: go to overview
  5970. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5971. (org-overview)
  5972. (unless ga (org-unlogged-message "OVERVIEW"))
  5973. (setq org-cycle-global-status 'overview)
  5974. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5975. (defvar org-called-with-limited-levels nil
  5976. "Non-nil when `org-with-limited-levels' is currently active.")
  5977. (defun org-cycle-internal-local ()
  5978. "Do the local cycling action."
  5979. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5980. ;; First, determine end of headline (EOH), end of subtree or item
  5981. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5982. (save-excursion
  5983. (if (org-at-item-p)
  5984. (progn
  5985. (beginning-of-line)
  5986. (setq struct (org-list-struct))
  5987. (setq eoh (point-at-eol))
  5988. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5989. (setq has-children (org-list-has-child-p (point) struct)))
  5990. (org-back-to-heading)
  5991. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5992. (setq eos (save-excursion (org-end-of-subtree t t)
  5993. (when (bolp) (backward-char)) (point)))
  5994. (setq has-children
  5995. (or (save-excursion
  5996. (let ((level (funcall outline-level)))
  5997. (outline-next-heading)
  5998. (and (org-at-heading-p t)
  5999. (> (funcall outline-level) level))))
  6000. (save-excursion
  6001. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6002. ;; Determine end invisible part of buffer (EOL)
  6003. (beginning-of-line 2)
  6004. (while (and (not (eobp)) ;This is like `next-line'.
  6005. (get-char-property (1- (point)) 'invisible))
  6006. (goto-char (next-single-char-property-change (point) 'invisible))
  6007. (and (eolp) (beginning-of-line 2)))
  6008. (setq eol (point)))
  6009. ;; Find out what to do next and set `this-command'
  6010. (cond
  6011. ((= eos eoh)
  6012. ;; Nothing is hidden behind this heading
  6013. (unless (org-before-first-heading-p)
  6014. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6015. (org-unlogged-message "EMPTY ENTRY")
  6016. (setq org-cycle-subtree-status nil)
  6017. (save-excursion
  6018. (goto-char eos)
  6019. (outline-next-heading)
  6020. (when (org-invisible-p) (org-flag-heading nil))))
  6021. ((and (or (>= eol eos)
  6022. (not (string-match "\\S-" (buffer-substring eol eos))))
  6023. (or has-children
  6024. (not (setq children-skipped
  6025. org-cycle-skip-children-state-if-no-children))))
  6026. ;; Entire subtree is hidden in one line: children view
  6027. (unless (org-before-first-heading-p)
  6028. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6029. (if (org-at-item-p)
  6030. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6031. (org-show-entry)
  6032. (org-with-limited-levels (org-show-children))
  6033. ;; FIXME: This slows down the func way too much.
  6034. ;; How keep drawers hidden in subtree anyway?
  6035. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6036. ;; (org-cycle-hide-drawers 'subtree))
  6037. ;; Fold every list in subtree to top-level items.
  6038. (when (eq org-cycle-include-plain-lists 'integrate)
  6039. (save-excursion
  6040. (org-back-to-heading)
  6041. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6042. (beginning-of-line 1)
  6043. (let* ((struct (org-list-struct))
  6044. (prevs (org-list-prevs-alist struct))
  6045. (end (org-list-get-bottom-point struct)))
  6046. (dolist (e (org-list-get-all-items (point) struct prevs))
  6047. (org-list-set-item-visibility e struct 'folded))
  6048. (goto-char (if (< end eos) end eos)))))))
  6049. (org-unlogged-message "CHILDREN")
  6050. (save-excursion
  6051. (goto-char eos)
  6052. (outline-next-heading)
  6053. (when (org-invisible-p) (org-flag-heading nil)))
  6054. (setq org-cycle-subtree-status 'children)
  6055. (unless (org-before-first-heading-p)
  6056. (run-hook-with-args 'org-cycle-hook 'children)))
  6057. ((or children-skipped
  6058. (and (eq last-command this-command)
  6059. (eq org-cycle-subtree-status 'children)))
  6060. ;; We just showed the children, or no children are there,
  6061. ;; now show everything.
  6062. (unless (org-before-first-heading-p)
  6063. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6064. (outline-flag-region eoh eos nil)
  6065. (org-unlogged-message
  6066. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6067. (setq org-cycle-subtree-status 'subtree)
  6068. (unless (org-before-first-heading-p)
  6069. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6070. (t
  6071. ;; Default action: hide the subtree.
  6072. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6073. (outline-flag-region eoh eos t)
  6074. (org-unlogged-message "FOLDED")
  6075. (setq org-cycle-subtree-status 'folded)
  6076. (unless (org-before-first-heading-p)
  6077. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6078. ;;;###autoload
  6079. (defun org-global-cycle (&optional arg)
  6080. "Cycle the global visibility. For details see `org-cycle'.
  6081. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6082. With a numeric prefix, show all headlines up to that level."
  6083. (interactive "P")
  6084. (let ((org-cycle-include-plain-lists
  6085. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6086. (cond
  6087. ((integerp arg)
  6088. (outline-show-all)
  6089. (outline-hide-sublevels arg)
  6090. (setq org-cycle-global-status 'contents))
  6091. ((equal arg '(4))
  6092. (org-set-startup-visibility)
  6093. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6094. (t
  6095. (org-cycle '(4))))))
  6096. (defun org-set-startup-visibility ()
  6097. "Set the visibility required by startup options and properties."
  6098. (cond
  6099. ((eq org-startup-folded t)
  6100. (org-overview))
  6101. ((eq org-startup-folded 'content)
  6102. (org-content))
  6103. ((or (eq org-startup-folded 'showeverything)
  6104. (eq org-startup-folded nil))
  6105. (outline-show-all)))
  6106. (unless (eq org-startup-folded 'showeverything)
  6107. (when org-hide-block-startup (org-hide-block-all))
  6108. (org-set-visibility-according-to-property 'no-cleanup)
  6109. (org-cycle-hide-archived-subtrees 'all)
  6110. (org-cycle-hide-drawers 'all)
  6111. (org-cycle-show-empty-lines t)))
  6112. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6113. "Switch subtree visibilities according to :VISIBILITY: property."
  6114. (interactive)
  6115. (org-with-wide-buffer
  6116. (goto-char (point-min))
  6117. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6118. (if (not (org-at-property-p)) (outline-next-heading)
  6119. (let ((state (match-string 3)))
  6120. (save-excursion
  6121. (org-back-to-heading t)
  6122. (outline-hide-subtree)
  6123. (org-reveal)
  6124. (cond
  6125. ((equal state "folded")
  6126. (outline-hide-subtree))
  6127. ((equal state "children")
  6128. (org-show-hidden-entry)
  6129. (org-show-children))
  6130. ((equal state "content")
  6131. (save-excursion
  6132. (save-restriction
  6133. (org-narrow-to-subtree)
  6134. (org-content))))
  6135. ((member state '("all" "showall"))
  6136. (outline-show-subtree)))))))
  6137. (unless no-cleanup
  6138. (org-cycle-hide-archived-subtrees 'all)
  6139. (org-cycle-hide-drawers 'all)
  6140. (org-cycle-show-empty-lines 'all))))
  6141. ;; This function uses outline-regexp instead of the more fundamental
  6142. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6143. ;; buffers, where outline-regexp is needed.
  6144. (defun org-overview ()
  6145. "Switch to overview mode, showing only top-level headlines.
  6146. This shows all headlines with a level equal or greater than the level
  6147. of the first headline in the buffer. This is important, because if the
  6148. first headline is not level one, then (hide-sublevels 1) gives confusing
  6149. results."
  6150. (interactive)
  6151. (save-excursion
  6152. (let ((level
  6153. (save-excursion
  6154. (goto-char (point-min))
  6155. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6156. (goto-char (match-beginning 0))
  6157. (funcall outline-level)))))
  6158. (and level (outline-hide-sublevels level)))))
  6159. (defun org-content (&optional arg)
  6160. "Show all headlines in the buffer, like a table of contents.
  6161. With numerical argument N, show content up to level N."
  6162. (interactive "P")
  6163. (org-overview)
  6164. (save-excursion
  6165. ;; Visit all headings and show their offspring
  6166. (and (integerp arg) (org-overview))
  6167. (goto-char (point-max))
  6168. (catch 'exit
  6169. (while (and (progn (condition-case nil
  6170. (outline-previous-visible-heading 1)
  6171. (error (goto-char (point-min))))
  6172. t)
  6173. (looking-at org-outline-regexp))
  6174. (if (integerp arg)
  6175. (org-show-children (1- arg))
  6176. (outline-show-branches))
  6177. (when (bobp) (throw 'exit nil))))))
  6178. (defun org-optimize-window-after-visibility-change (state)
  6179. "Adjust the window after a change in outline visibility.
  6180. This function is the default value of the hook `org-cycle-hook'."
  6181. (when (get-buffer-window (current-buffer))
  6182. (cond
  6183. ((eq state 'content) nil)
  6184. ((eq state 'all) nil)
  6185. ((eq state 'folded) nil)
  6186. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6187. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6188. (defun org-remove-empty-overlays-at (pos)
  6189. "Remove outline overlays that do not contain non-white stuff."
  6190. (dolist (o (overlays-at pos))
  6191. (and (eq 'outline (overlay-get o 'invisible))
  6192. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6193. (overlay-end o))))
  6194. (delete-overlay o))))
  6195. (defun org-clean-visibility-after-subtree-move ()
  6196. "Fix visibility issues after moving a subtree."
  6197. ;; First, find a reasonable region to look at:
  6198. ;; Start two siblings above, end three below
  6199. (let* ((beg (save-excursion
  6200. (and (org-get-last-sibling)
  6201. (org-get-last-sibling))
  6202. (point)))
  6203. (end (save-excursion
  6204. (and (org-get-next-sibling)
  6205. (org-get-next-sibling)
  6206. (org-get-next-sibling))
  6207. (if (org-at-heading-p)
  6208. (point-at-eol)
  6209. (point))))
  6210. (level (looking-at "\\*+"))
  6211. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6212. (save-excursion
  6213. (save-restriction
  6214. (narrow-to-region beg end)
  6215. (when re
  6216. ;; Properly fold already folded siblings
  6217. (goto-char (point-min))
  6218. (while (re-search-forward re nil t)
  6219. (when (and (not (org-invisible-p))
  6220. (save-excursion
  6221. (goto-char (point-at-eol)) (org-invisible-p)))
  6222. (outline-hide-entry))))
  6223. (org-cycle-show-empty-lines 'overview)
  6224. (org-cycle-hide-drawers 'overview)))))
  6225. (defun org-cycle-show-empty-lines (state)
  6226. "Show empty lines above all visible headlines.
  6227. The region to be covered depends on STATE when called through
  6228. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6229. entire buffer covered. Note that an empty line is only shown if there
  6230. are at least `org-cycle-separator-lines' empty lines before the headline."
  6231. (when (/= org-cycle-separator-lines 0)
  6232. (save-excursion
  6233. (let* ((n (abs org-cycle-separator-lines))
  6234. (re (cond
  6235. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6236. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6237. (t (let ((ns (number-to-string (- n 2))))
  6238. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6239. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6240. beg end)
  6241. (cond
  6242. ((memq state '(overview contents t))
  6243. (setq beg (point-min) end (point-max)))
  6244. ((memq state '(children folded))
  6245. (setq beg (point)
  6246. end (progn (org-end-of-subtree t t)
  6247. (line-beginning-position 2)))))
  6248. (when beg
  6249. (goto-char beg)
  6250. (while (re-search-forward re end t)
  6251. (unless (get-char-property (match-end 1) 'invisible)
  6252. (let ((e (match-end 1))
  6253. (b (if (>= org-cycle-separator-lines 0)
  6254. (match-beginning 1)
  6255. (save-excursion
  6256. (goto-char (match-beginning 0))
  6257. (skip-chars-backward " \t\n")
  6258. (line-end-position)))))
  6259. (outline-flag-region b e nil))))))))
  6260. ;; Never hide empty lines at the end of the file.
  6261. (save-excursion
  6262. (goto-char (point-max))
  6263. (outline-previous-heading)
  6264. (outline-end-of-heading)
  6265. (when (and (looking-at "[ \t\n]+")
  6266. (= (match-end 0) (point-max)))
  6267. (outline-flag-region (point) (match-end 0) nil))))
  6268. (defun org-show-empty-lines-in-parent ()
  6269. "Move to the parent and re-show empty lines before visible headlines."
  6270. (save-excursion
  6271. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6272. (org-cycle-show-empty-lines context))))
  6273. (defun org-files-list ()
  6274. "Return `org-agenda-files' list, plus all open Org files.
  6275. This is useful for operations that need to scan all of a user's
  6276. open and agenda-wise Org files."
  6277. (let ((files (mapcar 'expand-file-name (org-agenda-files))))
  6278. (dolist (buf (buffer-list))
  6279. (with-current-buffer buf
  6280. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6281. (cl-pushnew (expand-file-name (buffer-file-name)) files))))
  6282. files))
  6283. (defsubst org-entry-beginning-position ()
  6284. "Return the beginning position of the current entry."
  6285. (save-excursion (org-back-to-heading t) (point)))
  6286. (defsubst org-entry-end-position ()
  6287. "Return the end position of the current entry."
  6288. (save-excursion (outline-next-heading) (point)))
  6289. (defun org-cycle-hide-drawers (state &optional exceptions)
  6290. "Re-hide all drawers after a visibility state change.
  6291. STATE should be one of the symbols listed in the docstring of
  6292. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  6293. a list of strings specifying which drawers should not be hidden."
  6294. (when (and (derived-mode-p 'org-mode)
  6295. (not (memq state '(overview folded contents))))
  6296. (save-excursion
  6297. (let* ((globalp (eq state 'all))
  6298. (beg (if globalp (point-min) (point)))
  6299. (end (if globalp (point-max)
  6300. (if (eq state 'children)
  6301. (save-excursion (outline-next-heading) (point))
  6302. (org-end-of-subtree t)))))
  6303. (goto-char beg)
  6304. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6305. (unless (member-ignore-case (match-string 1) exceptions)
  6306. (let ((drawer (org-element-at-point)))
  6307. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6308. (org-flag-drawer t drawer)
  6309. ;; Make sure to skip drawer entirely or we might flag
  6310. ;; it another time when matching its ending line with
  6311. ;; `org-drawer-regexp'.
  6312. (goto-char (org-element-property :end drawer))))))))))
  6313. (defun org-flag-drawer (flag &optional element)
  6314. "When FLAG is non-nil, hide the drawer we are at.
  6315. Otherwise make it visible. When optional argument ELEMENT is
  6316. a parsed drawer, as returned by `org-element-at-point', hide or
  6317. show that drawer instead."
  6318. (let ((drawer (or element
  6319. (and (save-excursion
  6320. (beginning-of-line)
  6321. (looking-at-p org-drawer-regexp))
  6322. (org-element-at-point)))))
  6323. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6324. (let ((post (org-element-property :post-affiliated drawer)))
  6325. (save-excursion
  6326. (outline-flag-region
  6327. (progn (goto-char post) (line-end-position))
  6328. (progn (goto-char (org-element-property :end drawer))
  6329. (skip-chars-backward " \r\t\n")
  6330. (line-end-position))
  6331. flag))
  6332. ;; When the drawer is hidden away, make sure point lies in
  6333. ;; a visible part of the buffer.
  6334. (when (and flag (> (line-beginning-position) post))
  6335. (goto-char post))))))
  6336. (defun org-subtree-end-visible-p ()
  6337. "Is the end of the current subtree visible?"
  6338. (pos-visible-in-window-p
  6339. (save-excursion (org-end-of-subtree t) (point))))
  6340. (defun org-first-headline-recenter ()
  6341. "Move cursor to the first headline and recenter the headline."
  6342. (let ((window (get-buffer-window)))
  6343. (when window
  6344. (goto-char (point-min))
  6345. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6346. (set-window-start window (line-beginning-position))))))
  6347. ;;; Saving and restoring visibility
  6348. (defun org-outline-overlay-data (&optional use-markers)
  6349. "Return a list of the locations of all outline overlays.
  6350. These are overlays with the `invisible' property value `outline'.
  6351. The return value is a list of cons cells, with start and stop
  6352. positions for each overlay.
  6353. If USE-MARKERS is set, return the positions as markers."
  6354. (let (beg end)
  6355. (org-with-wide-buffer
  6356. (delq nil
  6357. (mapcar (lambda (o)
  6358. (when (eq (overlay-get o 'invisible) 'outline)
  6359. (setq beg (overlay-start o)
  6360. end (overlay-end o))
  6361. (and beg end (> end beg)
  6362. (if use-markers
  6363. (cons (copy-marker beg)
  6364. (copy-marker end t))
  6365. (cons beg end)))))
  6366. (overlays-in (point-min) (point-max)))))))
  6367. (defun org-set-outline-overlay-data (data)
  6368. "Create visibility overlays for all positions in DATA.
  6369. DATA should have been made by `org-outline-overlay-data'."
  6370. (org-with-wide-buffer
  6371. (outline-show-all)
  6372. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6373. ;;; Folding of blocks
  6374. (defvar-local org-hide-block-overlays nil
  6375. "Overlays hiding blocks.")
  6376. (defun org-block-map (function &optional start end)
  6377. "Call FUNCTION at the head of all source blocks in the current buffer.
  6378. Optional arguments START and END can be used to limit the range."
  6379. (let ((start (or start (point-min)))
  6380. (end (or end (point-max))))
  6381. (save-excursion
  6382. (goto-char start)
  6383. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6384. (save-excursion
  6385. (save-match-data
  6386. (goto-char (match-beginning 0))
  6387. (funcall function)))))))
  6388. (defun org-hide-block-toggle-all ()
  6389. "Toggle the visibility of all blocks in the current buffer."
  6390. (org-block-map 'org-hide-block-toggle))
  6391. (defun org-hide-block-all ()
  6392. "Fold all blocks in the current buffer."
  6393. (interactive)
  6394. (org-show-block-all)
  6395. (org-block-map 'org-hide-block-toggle-maybe))
  6396. (defun org-show-block-all ()
  6397. "Unfold all blocks in the current buffer."
  6398. (interactive)
  6399. (mapc #'delete-overlay org-hide-block-overlays)
  6400. (setq org-hide-block-overlays nil))
  6401. (defun org-hide-block-toggle-maybe ()
  6402. "Toggle visibility of block at point.
  6403. Unlike to `org-hide-block-toggle', this function does not throw
  6404. an error. Return a non-nil value when toggling is successful."
  6405. (interactive)
  6406. (ignore-errors (org-hide-block-toggle)))
  6407. (defun org-hide-block-toggle (&optional force)
  6408. "Toggle the visibility of the current block.
  6409. When optional argument FORCE is `off', make block visible. If it
  6410. is non-nil, hide it unconditionally. Throw an error when not at
  6411. a block. Return a non-nil value when toggling is successful."
  6412. (interactive)
  6413. (let ((element (org-element-at-point)))
  6414. (unless (memq (org-element-type element)
  6415. '(center-block comment-block dynamic-block example-block
  6416. export-block quote-block special-block
  6417. src-block verse-block))
  6418. (user-error "Not at a block"))
  6419. (let* ((start (save-excursion
  6420. (goto-char (org-element-property :post-affiliated element))
  6421. (line-end-position)))
  6422. (end (save-excursion
  6423. (goto-char (org-element-property :end element))
  6424. (skip-chars-backward " \r\t\n")
  6425. (line-end-position)))
  6426. (overlays (overlays-at start)))
  6427. (cond
  6428. ;; Do nothing when not before or at the block opening line or
  6429. ;; at the block closing line.
  6430. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6431. ((and (not (eq force 'off))
  6432. (not (memq t (mapcar
  6433. (lambda (o)
  6434. (eq (overlay-get o 'invisible) 'org-hide-block))
  6435. overlays))))
  6436. (let ((ov (make-overlay start end)))
  6437. (overlay-put ov 'invisible 'org-hide-block)
  6438. ;; Make the block accessible to `isearch'.
  6439. (overlay-put
  6440. ov 'isearch-open-invisible
  6441. (lambda (ov)
  6442. (when (memq ov org-hide-block-overlays)
  6443. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6444. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6445. (delete-overlay ov))))
  6446. (push ov org-hide-block-overlays)
  6447. ;; When the block is hidden away, make sure point is left in
  6448. ;; a visible part of the buffer.
  6449. (when (> (line-beginning-position) start)
  6450. (goto-char start)
  6451. (beginning-of-line))
  6452. ;; Signal successful toggling.
  6453. t))
  6454. ((or (not force) (eq force 'off))
  6455. (dolist (ov overlays t)
  6456. (when (memq ov org-hide-block-overlays)
  6457. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6458. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6459. (delete-overlay ov))))))))
  6460. ;; Remove overlays when changing major mode
  6461. (add-hook 'org-mode-hook
  6462. (lambda () (add-hook 'change-major-mode-hook
  6463. 'org-show-block-all 'append 'local)))
  6464. ;;; Indirect buffer display of subtrees
  6465. (defvar org-indirect-dedicated-frame nil
  6466. "This is the frame being used for indirect tree display.")
  6467. (defvar org-last-indirect-buffer nil)
  6468. (defun org-tree-to-indirect-buffer (&optional arg)
  6469. "Create indirect buffer and narrow it to current subtree.
  6470. With a numerical prefix ARG, go up to this level and then take that tree.
  6471. If ARG is negative, go up that many levels.
  6472. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6473. indirect buffer previously made with this command, to avoid proliferation of
  6474. indirect buffers. However, when you call the command with a \
  6475. `\\[universal-argument]' prefix, or
  6476. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6477. so that you can work with several indirect buffers at the same time. If
  6478. `org-indirect-buffer-display' is `dedicated-frame', the \
  6479. `\\[universal-argument]' prefix also
  6480. requests that a new frame be made for the new buffer, so that the dedicated
  6481. frame is not changed."
  6482. (interactive "P")
  6483. (let ((cbuf (current-buffer))
  6484. (cwin (selected-window))
  6485. (pos (point))
  6486. beg end level heading ibuf)
  6487. (save-excursion
  6488. (org-back-to-heading t)
  6489. (when (numberp arg)
  6490. (setq level (org-outline-level))
  6491. (when (< arg 0) (setq arg (+ level arg)))
  6492. (while (> (setq level (org-outline-level)) arg)
  6493. (org-up-heading-safe)))
  6494. (setq beg (point)
  6495. heading (org-get-heading 'no-tags))
  6496. (org-end-of-subtree t t)
  6497. (when (org-at-heading-p) (backward-char 1))
  6498. (setq end (point)))
  6499. (when (and (buffer-live-p org-last-indirect-buffer)
  6500. (not (eq org-indirect-buffer-display 'new-frame))
  6501. (not arg))
  6502. (kill-buffer org-last-indirect-buffer))
  6503. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6504. org-last-indirect-buffer ibuf)
  6505. (cond
  6506. ((or (eq org-indirect-buffer-display 'new-frame)
  6507. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6508. (select-frame (make-frame))
  6509. (delete-other-windows)
  6510. (pop-to-buffer-same-window ibuf)
  6511. (org-set-frame-title heading))
  6512. ((eq org-indirect-buffer-display 'dedicated-frame)
  6513. (raise-frame
  6514. (select-frame (or (and org-indirect-dedicated-frame
  6515. (frame-live-p org-indirect-dedicated-frame)
  6516. org-indirect-dedicated-frame)
  6517. (setq org-indirect-dedicated-frame (make-frame)))))
  6518. (delete-other-windows)
  6519. (pop-to-buffer-same-window ibuf)
  6520. (org-set-frame-title (concat "Indirect: " heading)))
  6521. ((eq org-indirect-buffer-display 'current-window)
  6522. (pop-to-buffer-same-window ibuf))
  6523. ((eq org-indirect-buffer-display 'other-window)
  6524. (pop-to-buffer ibuf))
  6525. (t (error "Invalid value")))
  6526. (narrow-to-region beg end)
  6527. (outline-show-all)
  6528. (goto-char pos)
  6529. (run-hook-with-args 'org-cycle-hook 'all)
  6530. (and (window-live-p cwin) (select-window cwin))))
  6531. (defun org-get-indirect-buffer (&optional buffer heading)
  6532. (setq buffer (or buffer (current-buffer)))
  6533. (let ((n 1) (base (buffer-name buffer)) bname)
  6534. (while (buffer-live-p
  6535. (get-buffer
  6536. (setq bname
  6537. (concat base "-"
  6538. (if heading (concat heading "-" (number-to-string n))
  6539. (number-to-string n))))))
  6540. (setq n (1+ n)))
  6541. (condition-case nil
  6542. (make-indirect-buffer buffer bname 'clone)
  6543. (error (make-indirect-buffer buffer bname)))))
  6544. (defun org-set-frame-title (title)
  6545. "Set the title of the current frame to the string TITLE."
  6546. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6547. ;;;; Structure editing
  6548. ;;; Inserting headlines
  6549. (defun org--line-empty-p (n)
  6550. "Is the Nth next line empty?
  6551. Counts the current line as N = 1 and the previous line as N = 0;
  6552. see `beginning-of-line'."
  6553. (save-excursion
  6554. (and (not (bobp))
  6555. (or (beginning-of-line n) t)
  6556. (save-match-data
  6557. (looking-at "[ \t]*$")))))
  6558. (defun org-previous-line-empty-p ()
  6559. "Is the previous line a blank line?
  6560. When NEXT is non-nil, check the next line instead."
  6561. (org--line-empty-p 0))
  6562. (defun org-next-line-empty-p ()
  6563. "Is the previous line a blank line?
  6564. When NEXT is non-nil, check the next line instead."
  6565. (org--line-empty-p 2))
  6566. (defun org--blank-before-heading-p (&optional parent)
  6567. "Non-nil when an empty line should precede a new heading here.
  6568. When optional argument PARENT is non-nil, consider parent
  6569. headline instead of current one."
  6570. (pcase (assq 'heading org-blank-before-new-entry)
  6571. (`(heading . auto)
  6572. (save-excursion
  6573. (org-with-limited-levels
  6574. (unless (and (org-before-first-heading-p)
  6575. (not (outline-next-heading)))
  6576. (org-back-to-heading t)
  6577. (when parent (org-up-heading-safe))
  6578. (cond ((not (bobp))
  6579. (org-previous-line-empty-p))
  6580. ((outline-next-heading)
  6581. (org-previous-line-empty-p))
  6582. ;; Ignore trailing spaces on last buffer line.
  6583. ((progn (skip-chars-backward " \t") (bolp))
  6584. (org-previous-line-empty-p))
  6585. (t nil))))))
  6586. (`(heading . ,value) value)
  6587. (_ nil)))
  6588. (defun org-insert-heading (&optional arg invisible-ok top)
  6589. "Insert a new heading or an item with the same depth at point.
  6590. If point is at the beginning of a heading, insert a new heading
  6591. or a new headline above the current one. When at the beginning
  6592. of a regular line of text, turn it into a heading.
  6593. If point is in the middle of a line, split it and create a new
  6594. headline with the text in the current line after point (see
  6595. `org-M-RET-may-split-line' on how to modify this behavior). As
  6596. a special case, on a headline, splitting can only happen on the
  6597. title itself. E.g., this excludes breaking stars or tags.
  6598. With a `\\[universal-argument]' prefix, set \
  6599. `org-insert-heading-respect-content' to
  6600. a non-nil value for the duration of the command. This forces the
  6601. insertion of a heading after the current subtree, independently
  6602. on the location of point.
  6603. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6604. insert the heading at the end of the tree
  6605. above the current heading. For example, if point is within a
  6606. 2nd-level heading, then it will insert a 2nd-level heading at
  6607. the end of the 1st-level parent subtree.
  6608. When INVISIBLE-OK is set, stop at invisible headlines when going
  6609. back. This is important for non-interactive uses of the
  6610. command.
  6611. When optional argument TOP is non-nil, insert a level 1 heading,
  6612. unconditionally."
  6613. (interactive "P")
  6614. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6615. (level (org-current-level))
  6616. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6617. (cond
  6618. ((or org-insert-heading-respect-content
  6619. (member arg '((4) (16)))
  6620. (and (not invisible-ok)
  6621. (invisible-p (max (1- (point)) (point-min)))))
  6622. ;; Position point at the location of insertion.
  6623. (if (not level) ;before first headline
  6624. (org-with-limited-levels (outline-next-heading))
  6625. ;; Make sure we end up on a visible headline if INVISIBLE-OK
  6626. ;; is nil.
  6627. (org-with-limited-levels (org-back-to-heading invisible-ok))
  6628. (cond ((equal arg '(16))
  6629. (org-up-heading-safe)
  6630. (org-end-of-subtree t t))
  6631. (t
  6632. (org-end-of-subtree t t))))
  6633. (unless (bolp) (insert "\n")) ;ensure final newline
  6634. (unless (and blank? (org-previous-line-empty-p))
  6635. (org-N-empty-lines-before-current (if blank? 1 0)))
  6636. (insert stars " \n")
  6637. (forward-char -1))
  6638. ;; At a headline...
  6639. ((org-at-heading-p)
  6640. (cond ((bolp)
  6641. (when blank? (save-excursion (insert "\n")))
  6642. (save-excursion (insert stars " \n"))
  6643. (unless (and blank? (org-previous-line-empty-p))
  6644. (org-N-empty-lines-before-current (if blank? 1 0)))
  6645. (end-of-line))
  6646. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6647. (org-match-line org-complex-heading-regexp)
  6648. (org-pos-in-match-range (point) 4))
  6649. ;; Grab the text that should moved to the new headline.
  6650. ;; Preserve tags.
  6651. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6652. (if (looking-at "[ \t]*$") (replace-match "")
  6653. (org-set-tags nil t))
  6654. (end-of-line)
  6655. (when blank? (insert "\n"))
  6656. (insert "\n" stars " ")
  6657. (when (org-string-nw-p split) (insert split))
  6658. (when (eobp) (save-excursion (insert "\n")))))
  6659. (t
  6660. (end-of-line)
  6661. (when blank? (insert "\n"))
  6662. (insert "\n" stars " ")
  6663. (when (eobp) (save-excursion (insert "\n"))))))
  6664. ;; On regular text, turn line into a headline or split, if
  6665. ;; appropriate.
  6666. ((bolp)
  6667. (insert stars " ")
  6668. (unless (and blank? (org-previous-line-empty-p))
  6669. (org-N-empty-lines-before-current (if blank? 1 0))))
  6670. (t
  6671. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6672. (end-of-line))
  6673. (insert "\n" stars " ")
  6674. (unless (and blank? (org-previous-line-empty-p))
  6675. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6676. (run-hooks 'org-insert-heading-hook))
  6677. (defun org-N-empty-lines-before-current (n)
  6678. "Make the number of empty lines before current exactly N.
  6679. So this will delete or add empty lines."
  6680. (let ((column (current-column)))
  6681. (beginning-of-line)
  6682. (unless (bobp)
  6683. (let ((start (save-excursion
  6684. (skip-chars-backward " \r\t\n")
  6685. (line-end-position))))
  6686. (delete-region start (line-end-position 0))))
  6687. (insert (make-string n ?\n))
  6688. (move-to-column column)))
  6689. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6690. "Return the heading of the current entry, without the stars.
  6691. When NO-TAGS is non-nil, don't include tags.
  6692. When NO-TODO is non-nil, don't include TODO keywords.
  6693. When NO-PRIORITY is non-nil, don't include priority cookie.
  6694. When NO-COMMENT is non-nil, don't include COMMENT string."
  6695. (save-excursion
  6696. (org-back-to-heading t)
  6697. (let ((case-fold-search nil))
  6698. (looking-at org-complex-heading-regexp)
  6699. (let ((todo (and (not no-todo) (match-string 2)))
  6700. (priority (and (not no-priority) (match-string 3)))
  6701. (headline (pcase (match-string 4)
  6702. (`nil "")
  6703. ((and (guard no-comment) h)
  6704. (replace-regexp-in-string
  6705. (eval-when-compile
  6706. (format "\\`%s[ \t]+" org-comment-string))
  6707. "" h))
  6708. (h h)))
  6709. (tags (and (not no-tags) (match-string 5))))
  6710. (mapconcat #'identity
  6711. (delq nil (list todo priority headline tags))
  6712. " ")))))
  6713. (defvar orgstruct-mode) ; defined below
  6714. (defun org-heading-components ()
  6715. "Return the components of the current heading.
  6716. This is a list with the following elements:
  6717. - the level as an integer
  6718. - the reduced level, different if `org-odd-levels-only' is set.
  6719. - the TODO keyword, or nil
  6720. - the priority character, like ?A, or nil if no priority is given
  6721. - the headline text itself, or the tags string if no headline text
  6722. - the tags string, or nil."
  6723. (save-excursion
  6724. (org-back-to-heading t)
  6725. (when (let (case-fold-search)
  6726. (looking-at
  6727. (if orgstruct-mode
  6728. org-heading-regexp
  6729. org-complex-heading-regexp)))
  6730. (if orgstruct-mode
  6731. (list (length (match-string 1))
  6732. (org-reduced-level (length (match-string 1)))
  6733. nil
  6734. nil
  6735. (match-string 2)
  6736. nil)
  6737. (list (length (match-string 1))
  6738. (org-reduced-level (length (match-string 1)))
  6739. (match-string-no-properties 2)
  6740. (and (match-end 3) (aref (match-string 3) 2))
  6741. (match-string-no-properties 4)
  6742. (match-string-no-properties 5))))))
  6743. (defun org-get-entry ()
  6744. "Get the entry text, after heading, entire subtree."
  6745. (save-excursion
  6746. (org-back-to-heading t)
  6747. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6748. (defun org-edit-headline (&optional heading)
  6749. "Edit the current headline.
  6750. Set it to HEADING when provided."
  6751. (interactive)
  6752. (org-with-wide-buffer
  6753. (org-back-to-heading t)
  6754. (let ((case-fold-search nil))
  6755. (when (looking-at org-complex-heading-regexp)
  6756. (let* ((old (match-string-no-properties 4))
  6757. (new (save-match-data
  6758. (org-trim (or heading (read-string "Edit: " old))))))
  6759. (unless (equal old new)
  6760. (if old (replace-match new t t nil 4)
  6761. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6762. (insert " " new))
  6763. (org-set-tags nil t)
  6764. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6765. (defun org-insert-heading-after-current ()
  6766. "Insert a new heading with same level as current, after current subtree."
  6767. (interactive)
  6768. (org-back-to-heading)
  6769. (org-insert-heading)
  6770. (org-move-subtree-down)
  6771. (end-of-line 1))
  6772. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6773. "Insert heading with `org-insert-heading-respect-content' set to t."
  6774. (interactive)
  6775. (org-insert-heading '(4) invisible-ok))
  6776. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6777. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6778. (interactive)
  6779. (org-insert-todo-heading force-state '(4)))
  6780. (defun org-insert-todo-heading (arg &optional force-heading)
  6781. "Insert a new heading with the same level and TODO state as current heading.
  6782. If the heading has no TODO state, or if the state is DONE, use
  6783. the first state (TODO by default). Also with one prefix arg,
  6784. force first state. With two prefix args, force inserting at the
  6785. end of the parent subtree.
  6786. When called at a plain list item, insert a new item with an
  6787. unchecked check box."
  6788. (interactive "P")
  6789. (when (or force-heading (not (org-insert-item 'checkbox)))
  6790. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6791. force-heading))
  6792. (save-excursion
  6793. (org-forward-heading-same-level -1)
  6794. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6795. (let* ((new-mark-x
  6796. (if (or (equal arg '(4))
  6797. (not (match-beginning 2))
  6798. (member (match-string 2) org-done-keywords))
  6799. (car org-todo-keywords-1)
  6800. (match-string 2)))
  6801. (new-mark
  6802. (or
  6803. (run-hook-with-args-until-success
  6804. 'org-todo-get-default-hook new-mark-x nil)
  6805. new-mark-x)))
  6806. (beginning-of-line 1)
  6807. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6808. (if org-treat-insert-todo-heading-as-state-change
  6809. (org-todo new-mark)
  6810. (insert new-mark " "))))
  6811. (when org-provide-todo-statistics
  6812. (org-update-parent-todo-statistics))))
  6813. (defun org-insert-subheading (arg)
  6814. "Insert a new subheading and demote it.
  6815. Works for outline headings and for plain lists alike."
  6816. (interactive "P")
  6817. (org-insert-heading arg)
  6818. (cond
  6819. ((org-at-heading-p) (org-do-demote))
  6820. ((org-at-item-p) (org-indent-item))))
  6821. (defun org-insert-todo-subheading (arg)
  6822. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6823. Works for outline headings and for plain lists alike."
  6824. (interactive "P")
  6825. (org-insert-todo-heading arg)
  6826. (cond
  6827. ((org-at-heading-p) (org-do-demote))
  6828. ((org-at-item-p) (org-indent-item))))
  6829. ;;; Promotion and Demotion
  6830. (defvar org-after-demote-entry-hook nil
  6831. "Hook run after an entry has been demoted.
  6832. The cursor will be at the beginning of the entry.
  6833. When a subtree is being demoted, the hook will be called for each node.")
  6834. (defvar org-after-promote-entry-hook nil
  6835. "Hook run after an entry has been promoted.
  6836. The cursor will be at the beginning of the entry.
  6837. When a subtree is being promoted, the hook will be called for each node.")
  6838. (defun org-promote-subtree ()
  6839. "Promote the entire subtree.
  6840. See also `org-promote'."
  6841. (interactive)
  6842. (save-excursion
  6843. (org-with-limited-levels (org-map-tree 'org-promote)))
  6844. (org-fix-position-after-promote))
  6845. (defun org-demote-subtree ()
  6846. "Demote the entire subtree.
  6847. See `org-demote' and `org-promote'."
  6848. (interactive)
  6849. (save-excursion
  6850. (org-with-limited-levels (org-map-tree 'org-demote)))
  6851. (org-fix-position-after-promote))
  6852. (defun org-do-promote ()
  6853. "Promote the current heading higher up the tree.
  6854. If the region is active in `transient-mark-mode', promote all
  6855. headings in the region."
  6856. (interactive)
  6857. (save-excursion
  6858. (if (org-region-active-p)
  6859. (org-map-region 'org-promote (region-beginning) (region-end))
  6860. (org-promote)))
  6861. (org-fix-position-after-promote))
  6862. (defun org-do-demote ()
  6863. "Demote the current heading lower down the tree.
  6864. If the region is active in `transient-mark-mode', demote all
  6865. headings in the region."
  6866. (interactive)
  6867. (save-excursion
  6868. (if (org-region-active-p)
  6869. (org-map-region 'org-demote (region-beginning) (region-end))
  6870. (org-demote)))
  6871. (org-fix-position-after-promote))
  6872. (defun org-fix-position-after-promote ()
  6873. "Fix cursor position and indentation after demoting/promoting."
  6874. (let ((pos (point)))
  6875. (when (save-excursion
  6876. (beginning-of-line)
  6877. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6878. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6879. (cond ((eobp) (insert " "))
  6880. ((eolp) (insert " "))
  6881. ((equal (char-after) ?\s) (forward-char 1))))))
  6882. (defun org-current-level ()
  6883. "Return the level of the current entry, or nil if before the first headline.
  6884. The level is the number of stars at the beginning of the
  6885. headline. Use `org-reduced-level' to remove the effect of
  6886. `org-odd-levels'. Unlike to `org-outline-level', this function
  6887. ignores inlinetasks."
  6888. (let ((level (org-with-limited-levels (org-outline-level))))
  6889. (and (> level 0) level)))
  6890. (defun org-get-previous-line-level ()
  6891. "Return the outline depth of the last headline before the current line.
  6892. Returns 0 for the first headline in the buffer, and nil if before the
  6893. first headline."
  6894. (and (org-current-level)
  6895. (or (and (/= (line-beginning-position) (point-min))
  6896. (save-excursion (beginning-of-line 0) (org-current-level)))
  6897. 0)))
  6898. (defun org-reduced-level (l)
  6899. "Compute the effective level of a heading.
  6900. This takes into account the setting of `org-odd-levels-only'."
  6901. (cond
  6902. ((zerop l) 0)
  6903. (org-odd-levels-only (1+ (floor (/ l 2))))
  6904. (t l)))
  6905. (defun org-level-increment ()
  6906. "Return the number of stars that will be added or removed at a
  6907. time to headlines when structure editing, based on the value of
  6908. `org-odd-levels-only'."
  6909. (if org-odd-levels-only 2 1))
  6910. (defun org-get-valid-level (level &optional change)
  6911. "Rectify a level change under the influence of `org-odd-levels-only'.
  6912. LEVEL is a current level, CHANGE is by how much the level should
  6913. be modified. Even if CHANGE is nil, LEVEL may be returned
  6914. modified because even level numbers will become the next higher
  6915. odd number. Returns values greater than 0."
  6916. (if org-odd-levels-only
  6917. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6918. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6919. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6920. (max 1 (+ level (or change 0)))))
  6921. (defun org-promote ()
  6922. "Promote the current heading higher up the tree."
  6923. (org-with-wide-buffer
  6924. (org-back-to-heading t)
  6925. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6926. after-change-functions))
  6927. (level (save-match-data (funcall outline-level)))
  6928. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6929. (diff (abs (- level (length up-head) -1))))
  6930. (cond
  6931. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6932. (replace-match "# " nil t))
  6933. ((= level 1)
  6934. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6935. (t (replace-match up-head nil t)))
  6936. (unless (= level 1)
  6937. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  6938. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6939. (run-hooks 'org-after-promote-entry-hook))))
  6940. (defun org-demote ()
  6941. "Demote the current heading lower down the tree."
  6942. (org-with-wide-buffer
  6943. (org-back-to-heading t)
  6944. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6945. after-change-functions))
  6946. (level (save-match-data (funcall outline-level)))
  6947. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6948. (diff (abs (- level (length down-head) -1))))
  6949. (replace-match down-head nil t)
  6950. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  6951. (when org-adapt-indentation (org-fixup-indentation diff))
  6952. (run-hooks 'org-after-demote-entry-hook))))
  6953. (defun org-cycle-level ()
  6954. "Cycle the level of an empty headline through possible states.
  6955. This goes first to child, then to parent, level, then up the hierarchy.
  6956. After top level, it switches back to sibling level."
  6957. (interactive)
  6958. (let ((org-adapt-indentation nil))
  6959. (when (org-point-at-end-of-empty-headline)
  6960. (setq this-command 'org-cycle-level) ; Only needed for caching
  6961. (let ((cur-level (org-current-level))
  6962. (prev-level (org-get-previous-line-level)))
  6963. (cond
  6964. ;; If first headline in file, promote to top-level.
  6965. ((= prev-level 0)
  6966. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6967. do (org-do-promote)))
  6968. ;; If same level as prev, demote one.
  6969. ((= prev-level cur-level)
  6970. (org-do-demote))
  6971. ;; If parent is top-level, promote to top level if not already.
  6972. ((= prev-level 1)
  6973. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6974. do (org-do-promote)))
  6975. ;; If top-level, return to prev-level.
  6976. ((= cur-level 1)
  6977. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6978. do (org-do-demote)))
  6979. ;; If less than prev-level, promote one.
  6980. ((< cur-level prev-level)
  6981. (org-do-promote))
  6982. ;; If deeper than prev-level, promote until higher than
  6983. ;; prev-level.
  6984. ((> cur-level prev-level)
  6985. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6986. do (org-do-promote))))
  6987. t))))
  6988. (defun org-map-tree (fun)
  6989. "Call FUN for every heading underneath the current one."
  6990. (org-back-to-heading t)
  6991. (let ((level (funcall outline-level)))
  6992. (save-excursion
  6993. (funcall fun)
  6994. (while (and (progn
  6995. (outline-next-heading)
  6996. (> (funcall outline-level) level))
  6997. (not (eobp)))
  6998. (funcall fun)))))
  6999. (defun org-map-region (fun beg end)
  7000. "Call FUN for every heading between BEG and END."
  7001. (let ((org-ignore-region t))
  7002. (save-excursion
  7003. (setq end (copy-marker end))
  7004. (goto-char beg)
  7005. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7006. (< (point) end))
  7007. (funcall fun))
  7008. (while (and (progn
  7009. (outline-next-heading)
  7010. (< (point) end))
  7011. (not (eobp)))
  7012. (funcall fun)))))
  7013. (defun org-fixup-indentation (diff)
  7014. "Change the indentation in the current entry by DIFF.
  7015. DIFF is an integer. Indentation is done according to the
  7016. following rules:
  7017. - Planning information and property drawers are always indented
  7018. according to the new level of the headline;
  7019. - Footnote definitions and their contents are ignored;
  7020. - Inlinetasks' boundaries are not shifted;
  7021. - Empty lines are ignored;
  7022. - Other lines' indentation are shifted by DIFF columns, unless
  7023. it would introduce a structural change in the document, in
  7024. which case no shifting is done at all.
  7025. Assume point is at a heading or an inlinetask beginning."
  7026. (org-with-wide-buffer
  7027. (narrow-to-region (line-beginning-position)
  7028. (save-excursion
  7029. (if (org-with-limited-levels (org-at-heading-p))
  7030. (org-with-limited-levels (outline-next-heading))
  7031. (org-inlinetask-goto-end))
  7032. (point)))
  7033. (forward-line)
  7034. ;; Indent properly planning info and property drawer.
  7035. (when (looking-at-p org-planning-line-re)
  7036. (org-indent-line)
  7037. (forward-line))
  7038. (when (looking-at org-property-drawer-re)
  7039. (goto-char (match-end 0))
  7040. (forward-line)
  7041. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7042. (catch 'no-shift
  7043. (when (zerop diff) (throw 'no-shift nil))
  7044. ;; If DIFF is negative, first check if a shift is possible at all
  7045. ;; (e.g., it doesn't break structure). This can only happen if
  7046. ;; some contents are not properly indented.
  7047. (let ((case-fold-search t))
  7048. (when (< diff 0)
  7049. (let ((diff (- diff))
  7050. (forbidden-re (concat org-outline-regexp
  7051. "\\|"
  7052. (substring org-footnote-definition-re 1))))
  7053. (save-excursion
  7054. (while (not (eobp))
  7055. (cond
  7056. ((looking-at-p "[ \t]*$") (forward-line))
  7057. ((and (looking-at-p org-footnote-definition-re)
  7058. (let ((e (org-element-at-point)))
  7059. (and (eq (org-element-type e) 'footnote-definition)
  7060. (goto-char (org-element-property :end e))))))
  7061. ((looking-at-p org-outline-regexp) (forward-line))
  7062. ;; Give up if shifting would move before column 0 or
  7063. ;; if it would introduce a headline or a footnote
  7064. ;; definition.
  7065. (t
  7066. (skip-chars-forward " \t")
  7067. (let ((ind (current-column)))
  7068. (when (or (< ind diff)
  7069. (and (= ind diff) (looking-at-p forbidden-re)))
  7070. (throw 'no-shift nil)))
  7071. ;; Ignore contents of example blocks and source
  7072. ;; blocks if their indentation is meant to be
  7073. ;; preserved. Jump to block's closing line.
  7074. (beginning-of-line)
  7075. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7076. (let ((e (org-element-at-point)))
  7077. (and (memq (org-element-type e)
  7078. '(example-block src-block))
  7079. (or org-src-preserve-indentation
  7080. (org-element-property :preserve-indent e))
  7081. (goto-char (org-element-property :end e))
  7082. (progn (skip-chars-backward " \r\t\n")
  7083. (beginning-of-line)
  7084. t))))
  7085. (forward-line))))))))
  7086. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7087. ;; by DIFF. Also skip contents of source or example blocks
  7088. ;; when indentation is meant to be preserved.
  7089. (while (not (eobp))
  7090. (cond
  7091. ((and (looking-at-p org-footnote-definition-re)
  7092. (let ((e (org-element-at-point)))
  7093. (and (eq (org-element-type e) 'footnote-definition)
  7094. (goto-char (org-element-property :end e))))))
  7095. ((looking-at-p org-outline-regexp) (forward-line))
  7096. ((looking-at-p "[ \t]*$") (forward-line))
  7097. (t
  7098. (indent-line-to (+ (org-get-indentation) diff))
  7099. (beginning-of-line)
  7100. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7101. (let ((e (org-element-at-point)))
  7102. (and (memq (org-element-type e)
  7103. '(example-block src-block))
  7104. (or org-src-preserve-indentation
  7105. (org-element-property :preserve-indent e))
  7106. (goto-char (org-element-property :end e))
  7107. (progn (skip-chars-backward " \r\t\n")
  7108. (beginning-of-line)
  7109. t))))
  7110. (forward-line)))))))))
  7111. (defun org-convert-to-odd-levels ()
  7112. "Convert an Org file with all levels allowed to one with odd levels.
  7113. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7114. level 5 etc."
  7115. (interactive)
  7116. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7117. (let ((outline-level 'org-outline-level)
  7118. (org-odd-levels-only nil) n)
  7119. (save-excursion
  7120. (goto-char (point-min))
  7121. (while (re-search-forward "^\\*\\*+ " nil t)
  7122. (setq n (- (length (match-string 0)) 2))
  7123. (while (>= (setq n (1- n)) 0)
  7124. (org-demote))
  7125. (end-of-line 1))))))
  7126. (defun org-convert-to-oddeven-levels ()
  7127. "Convert an Org file with only odd levels to one with odd/even levels.
  7128. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7129. file contains a section with an even level, conversion would
  7130. destroy the structure of the file. An error is signaled in this
  7131. case."
  7132. (interactive)
  7133. (goto-char (point-min))
  7134. ;; First check if there are no even levels
  7135. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7136. (org-show-set-visibility 'canonical)
  7137. (error "Not all levels are odd in this file. Conversion not possible"))
  7138. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7139. (let ((outline-regexp org-outline-regexp)
  7140. (outline-level 'org-outline-level)
  7141. (org-odd-levels-only nil) n)
  7142. (save-excursion
  7143. (goto-char (point-min))
  7144. (while (re-search-forward "^\\*\\*+ " nil t)
  7145. (setq n (/ (1- (length (match-string 0))) 2))
  7146. (while (>= (setq n (1- n)) 0)
  7147. (org-promote))
  7148. (end-of-line 1))))))
  7149. (defun org-tr-level (n)
  7150. "Make N odd if required."
  7151. (if org-odd-levels-only (1+ (/ n 2)) n))
  7152. ;;; Vertical tree motion, cutting and pasting of subtrees
  7153. (defun org-move-subtree-up (&optional arg)
  7154. "Move the current subtree up past ARG headlines of the same level."
  7155. (interactive "p")
  7156. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7157. (defun org-move-subtree-down (&optional arg)
  7158. "Move the current subtree down past ARG headlines of the same level."
  7159. (interactive "p")
  7160. (setq arg (prefix-numeric-value arg))
  7161. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7162. 'org-get-last-sibling))
  7163. (ins-point (make-marker))
  7164. (cnt (abs arg))
  7165. (col (current-column))
  7166. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7167. ;; Select the tree
  7168. (org-back-to-heading)
  7169. (setq beg0 (point))
  7170. (save-excursion
  7171. (setq ne-beg (org-back-over-empty-lines))
  7172. (setq beg (point)))
  7173. (save-match-data
  7174. (save-excursion (outline-end-of-heading)
  7175. (setq folded (org-invisible-p)))
  7176. (progn (org-end-of-subtree nil t)
  7177. (unless (eobp) (backward-char))))
  7178. (outline-next-heading)
  7179. (setq ne-end (org-back-over-empty-lines))
  7180. (setq end (point))
  7181. (goto-char beg0)
  7182. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7183. ;; include less whitespace
  7184. (save-excursion
  7185. (goto-char beg)
  7186. (forward-line (- ne-beg ne-end))
  7187. (setq beg (point))))
  7188. ;; Find insertion point, with error handling
  7189. (while (> cnt 0)
  7190. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7191. (progn (goto-char beg0)
  7192. (user-error "Cannot move past superior level or buffer limit")))
  7193. (setq cnt (1- cnt)))
  7194. (when (> arg 0)
  7195. ;; Moving forward - still need to move over subtree
  7196. (org-end-of-subtree t t)
  7197. (save-excursion
  7198. (org-back-over-empty-lines)
  7199. (or (bolp) (newline))))
  7200. (setq ne-ins (org-back-over-empty-lines))
  7201. (move-marker ins-point (point))
  7202. (setq txt (buffer-substring beg end))
  7203. (org-save-markers-in-region beg end)
  7204. (delete-region beg end)
  7205. (org-remove-empty-overlays-at beg)
  7206. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7207. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7208. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7209. (let ((bbb (point)))
  7210. (insert-before-markers txt)
  7211. (org-reinstall-markers-in-region bbb)
  7212. (move-marker ins-point bbb))
  7213. (or (bolp) (insert "\n"))
  7214. (setq ins-end (point))
  7215. (goto-char ins-point)
  7216. (org-skip-whitespace)
  7217. (when (and (< arg 0)
  7218. (org-first-sibling-p)
  7219. (> ne-ins ne-beg))
  7220. ;; Move whitespace back to beginning
  7221. (save-excursion
  7222. (goto-char ins-end)
  7223. (let ((kill-whole-line t))
  7224. (kill-line (- ne-ins ne-beg)) (point)))
  7225. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7226. (move-marker ins-point nil)
  7227. (if folded
  7228. (outline-hide-subtree)
  7229. (org-show-entry)
  7230. (org-show-children)
  7231. (org-cycle-hide-drawers 'children))
  7232. (org-clean-visibility-after-subtree-move)
  7233. ;; move back to the initial column we were at
  7234. (move-to-column col)))
  7235. (defvar org-subtree-clip ""
  7236. "Clipboard for cut and paste of subtrees.
  7237. This is actually only a copy of the kill, because we use the normal kill
  7238. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7239. (defvar org-subtree-clip-folded nil
  7240. "Was the last copied subtree folded?
  7241. This is used to fold the tree back after pasting.")
  7242. (defun org-cut-subtree (&optional n)
  7243. "Cut the current subtree into the clipboard.
  7244. With prefix arg N, cut this many sequential subtrees.
  7245. This is a short-hand for marking the subtree and then cutting it."
  7246. (interactive "p")
  7247. (org-copy-subtree n 'cut))
  7248. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7249. "Copy the current subtree it in the clipboard.
  7250. With prefix arg N, copy this many sequential subtrees.
  7251. This is a short-hand for marking the subtree and then copying it.
  7252. If CUT is non-nil, actually cut the subtree.
  7253. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7254. of some markers in the region, even if CUT is non-nil. This is
  7255. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7256. (interactive "p")
  7257. (let (beg end folded (beg0 (point)))
  7258. (if (called-interactively-p 'any)
  7259. (org-back-to-heading nil) ; take what looks like a subtree
  7260. (org-back-to-heading t)) ; take what is really there
  7261. (setq beg (point))
  7262. (skip-chars-forward " \t\r\n")
  7263. (save-match-data
  7264. (if nosubtrees
  7265. (outline-next-heading)
  7266. (save-excursion (outline-end-of-heading)
  7267. (setq folded (org-invisible-p)))
  7268. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7269. (org-end-of-subtree t t)))
  7270. ;; Include the end of an inlinetask
  7271. (when (and (featurep 'org-inlinetask)
  7272. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7273. "END[ \t]*$")))
  7274. (end-of-line))
  7275. (setq end (point))
  7276. (goto-char beg0)
  7277. (when (> end beg)
  7278. (setq org-subtree-clip-folded folded)
  7279. (when (or cut force-store-markers)
  7280. (org-save-markers-in-region beg end))
  7281. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7282. (setq org-subtree-clip (current-kill 0))
  7283. (message "%s: Subtree(s) with %d characters"
  7284. (if cut "Cut" "Copied")
  7285. (length org-subtree-clip)))))
  7286. (defun org-paste-subtree (&optional level tree for-yank remove)
  7287. "Paste the clipboard as a subtree, with modification of headline level.
  7288. The entire subtree is promoted or demoted in order to match a new headline
  7289. level.
  7290. If the cursor is at the beginning of a headline, the same level as
  7291. that headline is used to paste the tree.
  7292. If not, the new level is derived from the *visible* headings
  7293. before and after the insertion point, and taken to be the inferior headline
  7294. level of the two. So if the previous visible heading is level 3 and the
  7295. next is level 4 (or vice versa), level 4 will be used for insertion.
  7296. This makes sure that the subtree remains an independent subtree and does
  7297. not swallow low level entries.
  7298. You can also force a different level, either by using a numeric prefix
  7299. argument, or by inserting the heading marker by hand. For example, if the
  7300. cursor is after \"*****\", then the tree will be shifted to level 5.
  7301. If optional TREE is given, use this text instead of the kill ring.
  7302. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7303. move back over whitespace before inserting, and move point to the end of
  7304. the inserted text when done.
  7305. When REMOVE is non-nil, remove the subtree from the clipboard."
  7306. (interactive "P")
  7307. (setq tree (or tree (and kill-ring (current-kill 0))))
  7308. (unless (org-kill-is-subtree-p tree)
  7309. (user-error "%s"
  7310. (substitute-command-keys
  7311. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7312. (org-with-limited-levels
  7313. (let* ((visp (not (org-invisible-p)))
  7314. (txt tree)
  7315. (^re_ "\\(\\*+\\)[ \t]*")
  7316. (old-level (if (string-match org-outline-regexp-bol txt)
  7317. (- (match-end 0) (match-beginning 0) 1)
  7318. -1))
  7319. (force-level (cond (level (prefix-numeric-value level))
  7320. ((and (looking-at "[ \t]*$")
  7321. (string-match
  7322. "^\\*+$" (buffer-substring
  7323. (point-at-bol) (point))))
  7324. (- (match-end 0) (match-beginning 0)))
  7325. ((and (bolp)
  7326. (looking-at org-outline-regexp))
  7327. (- (match-end 0) (point) 1))))
  7328. (previous-level (save-excursion
  7329. (condition-case nil
  7330. (progn
  7331. (outline-previous-visible-heading 1)
  7332. (if (looking-at ^re_)
  7333. (- (match-end 0) (match-beginning 0) 1)
  7334. 1))
  7335. (error 1))))
  7336. (next-level (save-excursion
  7337. (condition-case nil
  7338. (progn
  7339. (or (looking-at org-outline-regexp)
  7340. (outline-next-visible-heading 1))
  7341. (if (looking-at ^re_)
  7342. (- (match-end 0) (match-beginning 0) 1)
  7343. 1))
  7344. (error 1))))
  7345. (new-level (or force-level (max previous-level next-level)))
  7346. (shift (if (or (= old-level -1)
  7347. (= new-level -1)
  7348. (= old-level new-level))
  7349. 0
  7350. (- new-level old-level)))
  7351. (delta (if (> shift 0) -1 1))
  7352. (func (if (> shift 0) 'org-demote 'org-promote))
  7353. (org-odd-levels-only nil)
  7354. beg end newend)
  7355. ;; Remove the forced level indicator
  7356. (when force-level
  7357. (delete-region (point-at-bol) (point)))
  7358. ;; Paste
  7359. (beginning-of-line (if (bolp) 1 2))
  7360. (setq beg (point))
  7361. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7362. (insert-before-markers txt)
  7363. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7364. (setq newend (point))
  7365. (org-reinstall-markers-in-region beg)
  7366. (setq end (point))
  7367. (goto-char beg)
  7368. (skip-chars-forward " \t\n\r")
  7369. (setq beg (point))
  7370. (when (and (org-invisible-p) visp)
  7371. (save-excursion (outline-show-heading)))
  7372. ;; Shift if necessary
  7373. (unless (= shift 0)
  7374. (save-restriction
  7375. (narrow-to-region beg end)
  7376. (while (not (= shift 0))
  7377. (org-map-region func (point-min) (point-max))
  7378. (setq shift (+ delta shift)))
  7379. (goto-char (point-min))
  7380. (setq newend (point-max))))
  7381. (when (or (called-interactively-p 'interactive) for-yank)
  7382. (message "Clipboard pasted as level %d subtree" new-level))
  7383. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7384. kill-ring
  7385. (eq org-subtree-clip (current-kill 0))
  7386. org-subtree-clip-folded)
  7387. ;; The tree was folded before it was killed/copied
  7388. (outline-hide-subtree))
  7389. (and for-yank (goto-char newend))
  7390. (and remove (setq kill-ring (cdr kill-ring))))))
  7391. (defun org-kill-is-subtree-p (&optional txt)
  7392. "Check if the current kill is an outline subtree, or a set of trees.
  7393. Returns nil if kill does not start with a headline, or if the first
  7394. headline level is not the largest headline level in the tree.
  7395. So this will actually accept several entries of equal levels as well,
  7396. which is OK for `org-paste-subtree'.
  7397. If optional TXT is given, check this string instead of the current kill."
  7398. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7399. (re (org-get-limited-outline-regexp))
  7400. (^re (concat "^" re))
  7401. (start-level (and kill
  7402. (string-match
  7403. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7404. kill)
  7405. (- (match-end 2) (match-beginning 2) 1)))
  7406. (start (1+ (or (match-beginning 2) -1))))
  7407. (if (not start-level)
  7408. (progn
  7409. nil) ;; does not even start with a heading
  7410. (catch 'exit
  7411. (while (setq start (string-match ^re kill (1+ start)))
  7412. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7413. (throw 'exit nil)))
  7414. t))))
  7415. (defvar org-markers-to-move nil
  7416. "Markers that should be moved with a cut-and-paste operation.
  7417. Those markers are stored together with their positions relative to
  7418. the start of the region.")
  7419. (defun org-save-markers-in-region (beg end)
  7420. "Check markers in region.
  7421. If these markers are between BEG and END, record their position relative
  7422. to BEG, so that after moving the block of text, we can put the markers back
  7423. into place.
  7424. This function gets called just before an entry or tree gets cut from the
  7425. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7426. called immediately, to move the markers with the entries."
  7427. (setq org-markers-to-move nil)
  7428. (when (featurep 'org-clock)
  7429. (org-clock-save-markers-for-cut-and-paste beg end))
  7430. (when (featurep 'org-agenda)
  7431. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7432. (defun org-check-and-save-marker (marker beg end)
  7433. "Check if MARKER is between BEG and END.
  7434. If yes, remember the marker and the distance to BEG."
  7435. (when (and (marker-buffer marker)
  7436. (equal (marker-buffer marker) (current-buffer))
  7437. (>= marker beg) (< marker end))
  7438. (push (cons marker (- marker beg)) org-markers-to-move)))
  7439. (defun org-reinstall-markers-in-region (beg)
  7440. "Move all remembered markers to their position relative to BEG."
  7441. (dolist (x org-markers-to-move)
  7442. (move-marker (car x) (+ beg (cdr x))))
  7443. (setq org-markers-to-move nil))
  7444. (defun org-narrow-to-subtree ()
  7445. "Narrow buffer to the current subtree."
  7446. (interactive)
  7447. (save-excursion
  7448. (save-match-data
  7449. (org-with-limited-levels
  7450. (narrow-to-region
  7451. (progn (org-back-to-heading t) (point))
  7452. (progn (org-end-of-subtree t t)
  7453. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7454. (point)))))))
  7455. (defun org-narrow-to-block ()
  7456. "Narrow buffer to the current block."
  7457. (interactive)
  7458. (let* ((case-fold-search t)
  7459. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7460. "^[ \t]*#\\+end_.*")))
  7461. (if blockp
  7462. (narrow-to-region (car blockp) (cdr blockp))
  7463. (user-error "Not in a block"))))
  7464. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7465. "Clone the task (subtree) at point N times.
  7466. The clones will be inserted as siblings.
  7467. In interactive use, the user will be prompted for the number of
  7468. clones to be produced. If the entry has a timestamp, the user
  7469. will also be prompted for a time shift, which may be a repeater
  7470. as used in time stamps, for example `+3d'. To disable this,
  7471. you can call the function with a universal prefix argument.
  7472. When a valid repeater is given and the entry contains any time
  7473. stamps, the clones will become a sequence in time, with time
  7474. stamps in the subtree shifted for each clone produced. If SHIFT
  7475. is nil or the empty string, time stamps will be left alone. The
  7476. ID property of the original subtree is removed.
  7477. In each clone, all the CLOCK entries will be removed. This
  7478. prevents Org from considering that the clocked times overlap.
  7479. If the original subtree did contain time stamps with a repeater,
  7480. the following will happen:
  7481. - the repeater will be removed in each clone
  7482. - an additional clone will be produced, with the current, unshifted
  7483. date(s) in the entry.
  7484. - the original entry will be placed *after* all the clones, with
  7485. repeater intact.
  7486. - the start days in the repeater in the original entry will be shifted
  7487. to past the last clone.
  7488. In this way you can spell out a number of instances of a repeating task,
  7489. and still retain the repeater to cover future instances of the task.
  7490. As described above, N+1 clones are produced when the original
  7491. subtree has a repeater. Setting N to 0, then, can be used to
  7492. remove the repeater from a subtree and create a shifted clone
  7493. with the original repeater."
  7494. (interactive "nNumber of clones to produce: ")
  7495. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7496. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7497. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7498. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7499. (shift
  7500. (or shift
  7501. (if (and (not (equal current-prefix-arg '(4)))
  7502. (save-excursion
  7503. (goto-char beg)
  7504. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7505. (read-from-minibuffer
  7506. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7507. ""))) ;No time shift
  7508. (doshift
  7509. (and (org-string-nw-p shift)
  7510. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7511. shift)
  7512. (user-error "Invalid shift specification %s" shift)))))
  7513. (goto-char end-of-tree)
  7514. (unless (bolp) (insert "\n"))
  7515. (let* ((end (point))
  7516. (template (buffer-substring beg end))
  7517. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7518. (shift-what (pcase (and doshift (match-string 2 shift))
  7519. (`nil nil)
  7520. ("d" 'day)
  7521. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7522. ("m" 'month)
  7523. ("y" 'year)
  7524. (_ (error "Unsupported time unit"))))
  7525. (nmin 1)
  7526. (nmax n)
  7527. (n-no-remove -1)
  7528. (idprop (org-entry-get nil "ID")))
  7529. (when (and doshift
  7530. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7531. template))
  7532. (delete-region beg end)
  7533. (setq end beg)
  7534. (setq nmin 0)
  7535. (setq nmax (1+ nmax))
  7536. (setq n-no-remove nmax))
  7537. (goto-char end)
  7538. (cl-loop for n from nmin to nmax do
  7539. (insert
  7540. ;; Prepare clone.
  7541. (with-temp-buffer
  7542. (insert template)
  7543. (org-mode)
  7544. (goto-char (point-min))
  7545. (org-show-subtree)
  7546. (and idprop (if org-clone-delete-id
  7547. (org-entry-delete nil "ID")
  7548. (org-id-get-create t)))
  7549. (unless (= n 0)
  7550. (while (re-search-forward org-clock-line-re nil t)
  7551. (delete-region (line-beginning-position)
  7552. (line-beginning-position 2)))
  7553. (goto-char (point-min))
  7554. (while (re-search-forward org-drawer-regexp nil t)
  7555. (org-remove-empty-drawer-at (point))))
  7556. (goto-char (point-min))
  7557. (when doshift
  7558. (while (re-search-forward org-ts-regexp-both nil t)
  7559. (org-timestamp-change (* n shift-n) shift-what))
  7560. (unless (= n n-no-remove)
  7561. (goto-char (point-min))
  7562. (while (re-search-forward org-ts-regexp nil t)
  7563. (save-excursion
  7564. (goto-char (match-beginning 0))
  7565. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7566. (delete-region (match-beginning 1) (match-end 1)))))))
  7567. (buffer-string)))))
  7568. (goto-char beg)))
  7569. ;;; Outline Sorting
  7570. (defun org-sort (&optional with-case)
  7571. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7572. Optional argument WITH-CASE means sort case-sensitively."
  7573. (interactive "P")
  7574. (org-call-with-arg
  7575. (cond ((org-at-table-p) #'org-table-sort-lines)
  7576. ((org-at-item-p) #'org-sort-list)
  7577. (t #'org-sort-entries))
  7578. with-case))
  7579. (defun org-sort-remove-invisible (s)
  7580. "Remove invisible part of links and emphasis markers from string S."
  7581. (remove-text-properties 0 (length s) org-rm-props s)
  7582. (replace-regexp-in-string
  7583. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7584. (replace-regexp-in-string
  7585. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7586. (org-link-display-format s)
  7587. t t) t t))
  7588. (defvar org-priority-regexp) ; defined later in the file
  7589. (defvar org-after-sorting-entries-or-items-hook nil
  7590. "Hook that is run after a bunch of entries or items have been sorted.
  7591. When children are sorted, the cursor is in the parent line when this
  7592. hook gets called. When a region or a plain list is sorted, the cursor
  7593. will be in the first entry of the sorted region/list.")
  7594. (defun org-sort-entries
  7595. (&optional with-case sorting-type getkey-func compare-func property
  7596. interactive?)
  7597. "Sort entries on a certain level of an outline tree.
  7598. If there is an active region, the entries in the region are sorted.
  7599. Else, if the cursor is before the first entry, sort the top-level items.
  7600. Else, the children of the entry at point are sorted.
  7601. Sorting can be alphabetically, numerically, by date/time as given by
  7602. a time stamp, by a property, by priority order, or by a custom function.
  7603. The command prompts for the sorting type unless it has been given to the
  7604. function through the SORTING-TYPE argument, which needs to be a character,
  7605. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7606. the precise meaning of each character:
  7607. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7608. c By creation time, which is assumed to be the first inactive time stamp
  7609. at the beginning of a line.
  7610. d By deadline date/time.
  7611. k By clocking time.
  7612. n Numerically, by converting the beginning of the entry/item to a number.
  7613. o By order of TODO keywords.
  7614. p By priority according to the cookie.
  7615. r By the value of a property.
  7616. s By scheduled date/time.
  7617. t By date/time, either the first active time stamp in the entry, or, if
  7618. none exist, by the first inactive one.
  7619. Capital letters will reverse the sort order.
  7620. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7621. called with point at the beginning of the record. It must return a
  7622. value that is compatible with COMPARE-FUNC, the function used to
  7623. compare entries.
  7624. Comparing entries ignores case by default. However, with an optional argument
  7625. WITH-CASE, the sorting considers case as well.
  7626. Sorting is done against the visible part of the headlines, it ignores hidden
  7627. links.
  7628. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7629. A non-nil value for INTERACTIVE? is used to signal that this
  7630. function is being called interactively."
  7631. (interactive (list current-prefix-arg nil nil nil nil t))
  7632. (let ((case-func (if with-case 'identity 'downcase))
  7633. start beg end stars re re2
  7634. txt what tmp)
  7635. ;; Find beginning and end of region to sort
  7636. (cond
  7637. ((org-region-active-p)
  7638. ;; we will sort the region
  7639. (setq end (region-end)
  7640. what "region")
  7641. (goto-char (region-beginning))
  7642. (unless (org-at-heading-p) (outline-next-heading))
  7643. (setq start (point)))
  7644. ((or (org-at-heading-p)
  7645. (ignore-errors (progn (org-back-to-heading) t)))
  7646. ;; we will sort the children of the current headline
  7647. (org-back-to-heading)
  7648. (setq start (point)
  7649. end (progn (org-end-of-subtree t t)
  7650. (or (bolp) (insert "\n"))
  7651. (when (>= (org-back-over-empty-lines) 1)
  7652. (forward-line 1))
  7653. (point))
  7654. what "children")
  7655. (goto-char start)
  7656. (outline-show-subtree)
  7657. (outline-next-heading))
  7658. (t
  7659. ;; we will sort the top-level entries in this file
  7660. (goto-char (point-min))
  7661. (or (org-at-heading-p) (outline-next-heading))
  7662. (setq start (point))
  7663. (goto-char (point-max))
  7664. (beginning-of-line 1)
  7665. (when (looking-at ".*?\\S-")
  7666. ;; File ends in a non-white line
  7667. (end-of-line 1)
  7668. (insert "\n"))
  7669. (setq end (point-max))
  7670. (setq what "top-level")
  7671. (goto-char start)
  7672. (outline-show-all)))
  7673. (setq beg (point))
  7674. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7675. (looking-at "\\(\\*+\\)")
  7676. (setq stars (match-string 1)
  7677. re (concat "^" (regexp-quote stars) " +")
  7678. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7679. txt (buffer-substring beg end))
  7680. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7681. (when (and (not (equal stars "*")) (string-match re2 txt))
  7682. (user-error "Region to sort contains a level above the first entry"))
  7683. (unless sorting-type
  7684. (message
  7685. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7686. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7687. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7688. what)
  7689. (setq sorting-type (read-char-exclusive)))
  7690. (unless getkey-func
  7691. (and (= (downcase sorting-type) ?f)
  7692. (setq getkey-func
  7693. (or (and interactive?
  7694. (org-read-function
  7695. "Function for extracting keys: "))
  7696. (error "Missing key extractor")))))
  7697. (and (= (downcase sorting-type) ?r)
  7698. (not property)
  7699. (setq property
  7700. (completing-read "Property: "
  7701. (mapcar #'list (org-buffer-property-keys t))
  7702. nil t)))
  7703. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7704. (message "Sorting entries...")
  7705. (save-restriction
  7706. (narrow-to-region start end)
  7707. (let ((restore-clock?
  7708. ;; The clock marker is lost when using `sort-subr'; mark
  7709. ;; the clock with temporary `:org-clock-marker-backup'
  7710. ;; text property.
  7711. (when (and (eq (org-clock-is-active) (current-buffer))
  7712. (<= start (marker-position org-clock-marker))
  7713. (>= end (marker-position org-clock-marker)))
  7714. (org-with-silent-modifications
  7715. (put-text-property (1- org-clock-marker) org-clock-marker
  7716. :org-clock-marker-backup t))
  7717. t))
  7718. (dcst (downcase sorting-type))
  7719. (case-fold-search nil)
  7720. (now (current-time)))
  7721. (sort-subr
  7722. (/= dcst sorting-type)
  7723. ;; This function moves to the beginning character of the "record" to
  7724. ;; be sorted.
  7725. (lambda nil
  7726. (if (re-search-forward re nil t)
  7727. (goto-char (match-beginning 0))
  7728. (goto-char (point-max))))
  7729. ;; This function moves to the last character of the "record" being
  7730. ;; sorted.
  7731. (lambda nil
  7732. (save-match-data
  7733. (condition-case nil
  7734. (outline-forward-same-level 1)
  7735. (error
  7736. (goto-char (point-max))))))
  7737. ;; This function returns the value that gets sorted against.
  7738. (lambda nil
  7739. (cond
  7740. ((= dcst ?n)
  7741. (if (looking-at org-complex-heading-regexp)
  7742. (string-to-number (org-sort-remove-invisible (match-string 4)))
  7743. nil))
  7744. ((= dcst ?a)
  7745. (if (looking-at org-complex-heading-regexp)
  7746. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  7747. nil))
  7748. ((= dcst ?k)
  7749. (or (get-text-property (point) :org-clock-minutes) 0))
  7750. ((= dcst ?t)
  7751. (let ((end (save-excursion (outline-next-heading) (point))))
  7752. (if (or (re-search-forward org-ts-regexp end t)
  7753. (re-search-forward org-ts-regexp-both end t))
  7754. (org-time-string-to-seconds (match-string 0))
  7755. (float-time now))))
  7756. ((= dcst ?c)
  7757. (let ((end (save-excursion (outline-next-heading) (point))))
  7758. (if (re-search-forward
  7759. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7760. end t)
  7761. (org-time-string-to-seconds (match-string 0))
  7762. (float-time now))))
  7763. ((= dcst ?s)
  7764. (let ((end (save-excursion (outline-next-heading) (point))))
  7765. (if (re-search-forward org-scheduled-time-regexp end t)
  7766. (org-time-string-to-seconds (match-string 1))
  7767. (float-time now))))
  7768. ((= dcst ?d)
  7769. (let ((end (save-excursion (outline-next-heading) (point))))
  7770. (if (re-search-forward org-deadline-time-regexp end t)
  7771. (org-time-string-to-seconds (match-string 1))
  7772. (float-time now))))
  7773. ((= dcst ?p)
  7774. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7775. (string-to-char (match-string 2))
  7776. org-default-priority))
  7777. ((= dcst ?r)
  7778. (or (org-entry-get nil property) ""))
  7779. ((= dcst ?o)
  7780. (when (looking-at org-complex-heading-regexp)
  7781. (let* ((m (match-string 2))
  7782. (s (if (member m org-done-keywords) '- '+)))
  7783. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7784. ((= dcst ?f)
  7785. (if getkey-func
  7786. (progn
  7787. (setq tmp (funcall getkey-func))
  7788. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7789. tmp)
  7790. (error "Invalid key function `%s'" getkey-func)))
  7791. (t (error "Invalid sorting type `%c'" sorting-type))))
  7792. nil
  7793. (cond
  7794. ((= dcst ?a) 'string<)
  7795. ((= dcst ?f)
  7796. (or compare-func
  7797. (and interactive?
  7798. (org-read-function
  7799. (concat "Function for comparing keys "
  7800. "(empty for default `sort-subr' predicate): ")
  7801. 'allow-empty))))
  7802. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
  7803. (when restore-clock?
  7804. (move-marker org-clock-marker
  7805. (1+ (next-single-property-change
  7806. start :org-clock-marker-backup)))
  7807. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7808. '(:org-clock-marker-backup t)))))
  7809. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7810. (message "Sorting entries...done")))
  7811. ;;; The orgstruct minor mode
  7812. ;; Define a minor mode which can be used in other modes in order to
  7813. ;; integrate the Org mode structure editing commands.
  7814. ;; This is really a hack, because the Org mode structure commands use
  7815. ;; keys which normally belong to the major mode. Here is how it
  7816. ;; works: The minor mode defines all the keys necessary to operate the
  7817. ;; structure commands, but wraps the commands into a function which
  7818. ;; tests if the cursor is currently at a headline or a plain list
  7819. ;; item. If that is the case, the structure command is used,
  7820. ;; temporarily setting many Org mode variables like regular
  7821. ;; expressions for filling etc. However, when any of those keys is
  7822. ;; used at a different location, function uses `key-binding' to look
  7823. ;; up if the key has an associated command in another currently active
  7824. ;; keymap (minor modes, major mode, global), and executes that
  7825. ;; command. There might be problems if any of the keys is otherwise
  7826. ;; used as a prefix key.
  7827. (defcustom orgstruct-heading-prefix-regexp ""
  7828. "Regexp that matches the custom prefix of Org headlines in
  7829. orgstruct(++)-mode."
  7830. :group 'org
  7831. :version "26.1"
  7832. :package-version '(Org . "8.3")
  7833. :type 'regexp)
  7834. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  7835. (defcustom orgstruct-setup-hook nil
  7836. "Hook run after orgstruct-mode-map is filled."
  7837. :group 'org
  7838. :version "24.4"
  7839. :package-version '(Org . "8.0")
  7840. :type 'hook)
  7841. (defvar orgstruct-initialized nil)
  7842. (defvar org-local-vars nil
  7843. "List of local variables, for use by `orgstruct-mode'.")
  7844. ;;;###autoload
  7845. (define-minor-mode orgstruct-mode
  7846. "Toggle the minor mode `orgstruct-mode'.
  7847. This mode is for using Org mode structure commands in other
  7848. modes. The following keys behave as if Org mode were active, if
  7849. the cursor is on a headline, or on a plain list item (both as
  7850. defined by Org mode)."
  7851. nil " OrgStruct" (make-sparse-keymap)
  7852. (funcall (if orgstruct-mode
  7853. 'add-to-invisibility-spec
  7854. 'remove-from-invisibility-spec)
  7855. '(outline . t))
  7856. (when orgstruct-mode
  7857. (org-load-modules-maybe)
  7858. (unless orgstruct-initialized
  7859. (orgstruct-setup)
  7860. (setq orgstruct-initialized t))))
  7861. ;;;###autoload
  7862. (defun turn-on-orgstruct ()
  7863. "Unconditionally turn on `orgstruct-mode'."
  7864. (orgstruct-mode 1))
  7865. (defvar-local orgstruct-is-++ nil
  7866. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  7867. (defvar-local org-fb-vars nil)
  7868. (defun orgstruct++-mode (&optional arg)
  7869. "Toggle `orgstruct-mode', the enhanced version of it.
  7870. In addition to setting orgstruct-mode, this also exports all
  7871. indentation and autofilling variables from Org mode into the
  7872. buffer. It will also recognize item context in multiline items."
  7873. (interactive "P")
  7874. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  7875. (if (< arg 1)
  7876. (progn (orgstruct-mode -1)
  7877. (dolist (v org-fb-vars)
  7878. (set (make-local-variable (car v))
  7879. (if (eq (car-safe (cadr v)) 'quote)
  7880. (cl-cadadr v)
  7881. (nth 1 v)))))
  7882. (orgstruct-mode 1)
  7883. (setq org-fb-vars nil)
  7884. (unless org-local-vars
  7885. (setq org-local-vars (org-get-local-variables)))
  7886. (let (var val)
  7887. (dolist (x org-local-vars)
  7888. (when (string-match
  7889. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
  7890. \\|fill-prefix\\|indent-\\)"
  7891. (symbol-name (car x)))
  7892. (setq var (car x) val (nth 1 x))
  7893. (push (list var `(quote ,(eval var))) org-fb-vars)
  7894. (set (make-local-variable var)
  7895. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  7896. (setq-local orgstruct-is-++ t))))
  7897. ;;;###autoload
  7898. (defun turn-on-orgstruct++ ()
  7899. "Unconditionally turn on `orgstruct++-mode'."
  7900. (orgstruct++-mode 1))
  7901. (defun orgstruct-error ()
  7902. "Error when there is no default binding for a structure key."
  7903. (interactive)
  7904. (funcall (if (fboundp 'user-error)
  7905. 'user-error
  7906. 'error)
  7907. "This key has no function outside structure elements"))
  7908. (defun orgstruct-setup ()
  7909. "Setup orgstruct keymap."
  7910. (dolist (cell '((org-demote . t)
  7911. (org-metaleft . t)
  7912. (org-metaright . t)
  7913. (org-promote . t)
  7914. (org-shiftmetaleft . t)
  7915. (org-shiftmetaright . t)
  7916. org-backward-element
  7917. org-backward-heading-same-level
  7918. org-ctrl-c-ret
  7919. org-ctrl-c-minus
  7920. org-ctrl-c-star
  7921. org-cycle
  7922. org-force-cycle-archived
  7923. org-forward-heading-same-level
  7924. org-insert-heading
  7925. org-insert-heading-respect-content
  7926. org-kill-note-or-show-branches
  7927. org-mark-subtree
  7928. org-meta-return
  7929. org-metadown
  7930. org-metaup
  7931. org-narrow-to-subtree
  7932. org-promote-subtree
  7933. org-reveal
  7934. org-shiftdown
  7935. org-shiftleft
  7936. org-shiftmetadown
  7937. org-shiftmetaup
  7938. org-shiftright
  7939. org-shifttab
  7940. org-shifttab
  7941. org-shiftup
  7942. org-show-children
  7943. org-show-subtree
  7944. org-sort
  7945. org-up-element
  7946. outline-demote
  7947. outline-next-visible-heading
  7948. outline-previous-visible-heading
  7949. outline-promote
  7950. outline-up-heading))
  7951. (let ((f (or (car-safe cell) cell))
  7952. (disable-when-heading-prefix (cdr-safe cell)))
  7953. (when (fboundp f)
  7954. (let ((new-bindings))
  7955. (dolist (binding (nconc (where-is-internal f org-mode-map)
  7956. (where-is-internal f outline-mode-map)))
  7957. (push binding new-bindings)
  7958. ;; TODO use local-function-key-map
  7959. (dolist (rep '(("<tab>" . "TAB")
  7960. ("<return>" . "RET")
  7961. ("<escape>" . "ESC")
  7962. ("<delete>" . "DEL")))
  7963. (setq binding (read-kbd-macro
  7964. (let ((case-fold-search))
  7965. (replace-regexp-in-string
  7966. (regexp-quote (cdr rep))
  7967. (car rep)
  7968. (key-description binding)))))
  7969. (cl-pushnew binding new-bindings :test 'equal)))
  7970. (dolist (binding new-bindings)
  7971. (let ((key (lookup-key orgstruct-mode-map binding)))
  7972. (when (or (not key) (numberp key))
  7973. (ignore-errors
  7974. (org-defkey orgstruct-mode-map
  7975. binding
  7976. (orgstruct-make-binding
  7977. f binding disable-when-heading-prefix))))))))))
  7978. (run-hooks 'orgstruct-setup-hook))
  7979. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  7980. "Create a function for binding in the structure minor mode.
  7981. FUN is the command to call inside a table. KEY is the key that
  7982. should be checked in for a command to execute outside of tables.
  7983. Non-nil `disable-when-heading-prefix' means to disable the command
  7984. if `orgstruct-heading-prefix-regexp' is not empty."
  7985. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  7986. (let ((nname name)
  7987. (i 0))
  7988. (while (fboundp (intern nname))
  7989. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  7990. (setq name (intern nname)))
  7991. (eval
  7992. (let ((bindings '((org-heading-regexp
  7993. (concat "^"
  7994. orgstruct-heading-prefix-regexp
  7995. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  7996. (org-outline-regexp
  7997. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  7998. (org-outline-regexp-bol
  7999. (concat "^" org-outline-regexp))
  8000. (outline-regexp org-outline-regexp)
  8001. (outline-heading-end-regexp "\n")
  8002. (outline-level 'org-outline-level)
  8003. (outline-heading-alist))))
  8004. `(defun ,name (arg)
  8005. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8006. "Outside of structure, run the binding of `"
  8007. (key-description key) "'."
  8008. (when disable-when-heading-prefix
  8009. (concat
  8010. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8011. "back to the default binding due to limitations of Org's implementation of\n"
  8012. "`" (symbol-name fun) "'.")))
  8013. (interactive "p")
  8014. (let* ((disable
  8015. ,(and disable-when-heading-prefix
  8016. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8017. (fallback
  8018. (or disable
  8019. (not
  8020. (let* ,bindings
  8021. (org-context-p 'headline 'item
  8022. ,(when (memq fun
  8023. '(org-insert-heading
  8024. org-insert-heading-respect-content
  8025. org-meta-return))
  8026. '(when orgstruct-is-++
  8027. 'item-body))))))))
  8028. (if fallback
  8029. (let* ((orgstruct-mode)
  8030. (binding
  8031. (let ((key ,key))
  8032. (catch 'exit
  8033. (dolist
  8034. (rep
  8035. '(nil
  8036. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8037. ("<\\([^>]*\\)return>" . "\\1RET")
  8038. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8039. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8040. nil)
  8041. (when rep
  8042. (setq key (read-kbd-macro
  8043. (let ((case-fold-search))
  8044. (replace-regexp-in-string
  8045. (car rep)
  8046. (cdr rep)
  8047. (key-description key))))))
  8048. (when (key-binding key)
  8049. (throw 'exit (key-binding key))))))))
  8050. (if (keymapp binding)
  8051. (org-set-transient-map binding)
  8052. (let ((func (or binding
  8053. (unless disable
  8054. 'orgstruct-error))))
  8055. (when func
  8056. (call-interactively func)))))
  8057. (org-run-like-in-org-mode
  8058. (lambda ()
  8059. (interactive)
  8060. (let* ,bindings
  8061. (call-interactively ',fun)))))))))
  8062. name))
  8063. (defun org-contextualize-keys (alist contexts)
  8064. "Return valid elements in ALIST depending on CONTEXTS.
  8065. `org-agenda-custom-commands' or `org-capture-templates' are the
  8066. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8067. or `org-capture-templates-contexts' are the associated contexts
  8068. definitions."
  8069. (let ((contexts
  8070. ;; normalize contexts
  8071. (mapcar
  8072. (lambda(c) (cond ((listp (cadr c))
  8073. (list (car c) (car c) (nth 1 c)))
  8074. ((string= "" (cadr c))
  8075. (list (car c) (car c) (nth 2 c)))
  8076. (t c)))
  8077. contexts))
  8078. (a alist) r s)
  8079. ;; loop over all commands or templates
  8080. (dolist (c a)
  8081. (let (vrules repl)
  8082. (cond
  8083. ((not (assoc (car c) contexts))
  8084. (push c r))
  8085. ((and (assoc (car c) contexts)
  8086. (setq vrules (org-contextualize-validate-key
  8087. (car c) contexts)))
  8088. (mapc (lambda (vr)
  8089. (unless (equal (car vr) (cadr vr))
  8090. (setq repl vr)))
  8091. vrules)
  8092. (if (not repl) (push c r)
  8093. (push (cadr repl) s)
  8094. (push
  8095. (cons (car c)
  8096. (cdr (or (assoc (cadr repl) alist)
  8097. (error "Undefined key `%s' as contextual replacement for `%s'"
  8098. (cadr repl) (car c)))))
  8099. r))))))
  8100. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8101. (delq
  8102. nil
  8103. (delete-dups
  8104. (mapcar (lambda (x)
  8105. (let ((tpl (car x)))
  8106. (unless (delq
  8107. nil
  8108. (mapcar (lambda (y)
  8109. (equal y tpl))
  8110. s))
  8111. x)))
  8112. (reverse r))))))
  8113. (defun org-contextualize-validate-key (key contexts)
  8114. "Check CONTEXTS for agenda or capture KEY."
  8115. (let (res)
  8116. (dolist (r contexts)
  8117. (dolist (rr (car (last r)))
  8118. (when
  8119. (and (equal key (car r))
  8120. (if (functionp rr) (funcall rr)
  8121. (or (and (eq (car rr) 'in-file)
  8122. (buffer-file-name)
  8123. (string-match (cdr rr) (buffer-file-name)))
  8124. (and (eq (car rr) 'in-mode)
  8125. (string-match (cdr rr) (symbol-name major-mode)))
  8126. (and (eq (car rr) 'in-buffer)
  8127. (string-match (cdr rr) (buffer-name)))
  8128. (when (and (eq (car rr) 'not-in-file)
  8129. (buffer-file-name))
  8130. (not (string-match (cdr rr) (buffer-file-name))))
  8131. (when (eq (car rr) 'not-in-mode)
  8132. (not (string-match (cdr rr) (symbol-name major-mode))))
  8133. (when (eq (car rr) 'not-in-buffer)
  8134. (not (string-match (cdr rr) (buffer-name)))))))
  8135. (push r res))))
  8136. (delete-dups (delq nil res))))
  8137. (defun org-context-p (&rest contexts)
  8138. "Check if local context is any of CONTEXTS.
  8139. Possible values in the list of contexts are `table', `headline', and `item'."
  8140. (let ((pos (point)))
  8141. (goto-char (point-at-bol))
  8142. (prog1 (or (and (memq 'table contexts)
  8143. (looking-at "[ \t]*|"))
  8144. (and (memq 'headline contexts)
  8145. (looking-at org-outline-regexp))
  8146. (and (memq 'item contexts)
  8147. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8148. (and (memq 'item-body contexts)
  8149. (org-in-item-p)))
  8150. (goto-char pos))))
  8151. ;;;###autoload
  8152. (defun org-run-like-in-org-mode (cmd)
  8153. "Run a command, pretending that the current buffer is in Org mode.
  8154. This will temporarily bind local variables that are typically bound in
  8155. Org mode to the values they have in Org mode, and then interactively
  8156. call CMD."
  8157. (org-load-modules-maybe)
  8158. (unless org-local-vars
  8159. (setq org-local-vars (org-get-local-variables)))
  8160. (let (binds)
  8161. (dolist (var org-local-vars)
  8162. (when (or (not (boundp (car var)))
  8163. (eq (symbol-value (car var))
  8164. (default-value (car var))))
  8165. (push (list (car var) `(quote ,(cadr var))) binds)))
  8166. (eval `(let ,binds
  8167. (call-interactively (quote ,cmd))))))
  8168. (defun org-get-category (&optional pos force-refresh)
  8169. "Get the category applying to position POS."
  8170. (save-match-data
  8171. (when force-refresh (org-refresh-category-properties))
  8172. (let ((pos (or pos (point))))
  8173. (or (get-text-property pos 'org-category)
  8174. (progn (org-refresh-category-properties)
  8175. (get-text-property pos 'org-category))))))
  8176. ;;; Refresh properties
  8177. (defun org-refresh-properties (dprop tprop)
  8178. "Refresh buffer text properties.
  8179. DPROP is the drawer property and TPROP is either the
  8180. corresponding text property to set, or an alist with each element
  8181. being a text property (as a symbol) and a function to apply to
  8182. the value of the drawer property."
  8183. (let* ((case-fold-search t)
  8184. (inhibit-read-only t)
  8185. (inherit? (org-property-inherit-p dprop))
  8186. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  8187. (global (and inherit? (org--property-global-value dprop nil))))
  8188. (org-with-silent-modifications
  8189. (org-with-point-at 1
  8190. ;; Set global values (e.g., values defined through
  8191. ;; "#+PROPERTY:" keywords) to the whole buffer.
  8192. (when global (put-text-property (point-min) (point-max) tprop global))
  8193. ;; Set local values.
  8194. (while (re-search-forward property-re nil t)
  8195. (when (org-at-property-p)
  8196. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  8197. (outline-next-heading))))))
  8198. (defun org-refresh-property (tprop p &optional inherit)
  8199. "Refresh the buffer text property TPROP from the drawer property P.
  8200. The refresh happens only for the current headline, or the whole
  8201. sub-tree if optional argument INHERIT is non-nil."
  8202. (unless (org-before-first-heading-p)
  8203. (save-excursion
  8204. (org-back-to-heading t)
  8205. (let ((start (point))
  8206. (end (save-excursion
  8207. (if inherit (org-end-of-subtree t t)
  8208. (or (outline-next-heading) (point-max))))))
  8209. (if (symbolp tprop)
  8210. ;; TPROP is a text property symbol.
  8211. (put-text-property start end tprop p)
  8212. ;; TPROP is an alist with (property . function) elements.
  8213. (pcase-dolist (`(,prop . ,f) tprop)
  8214. (put-text-property start end prop (funcall f p))))))))
  8215. (defun org-refresh-category-properties ()
  8216. "Refresh category text properties in the buffer."
  8217. (let ((case-fold-search t)
  8218. (inhibit-read-only t)
  8219. (default-category
  8220. (cond ((null org-category)
  8221. (if buffer-file-name
  8222. (file-name-sans-extension
  8223. (file-name-nondirectory buffer-file-name))
  8224. "???"))
  8225. ((symbolp org-category) (symbol-name org-category))
  8226. (t org-category))))
  8227. (org-with-silent-modifications
  8228. (org-with-wide-buffer
  8229. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8230. ;; This is the default category for the buffer. If none is
  8231. ;; found, fall-back to `org-category' or buffer file name.
  8232. (put-text-property
  8233. (point-min) (point-max)
  8234. 'org-category
  8235. (catch 'buffer-category
  8236. (goto-char (point-max))
  8237. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8238. (let ((element (org-element-at-point)))
  8239. (when (eq (org-element-type element) 'keyword)
  8240. (throw 'buffer-category
  8241. (org-element-property :value element)))))
  8242. default-category))
  8243. ;; Set sub-tree specific categories.
  8244. (goto-char (point-min))
  8245. (let ((regexp (org-re-property "CATEGORY")))
  8246. (while (re-search-forward regexp nil t)
  8247. (let ((value (match-string-no-properties 3)))
  8248. (when (org-at-property-p)
  8249. (put-text-property
  8250. (save-excursion (org-back-to-heading t) (point))
  8251. (save-excursion (org-end-of-subtree t t) (point))
  8252. 'org-category
  8253. value)))))))))
  8254. (defun org-refresh-stats-properties ()
  8255. "Refresh stats text properties in the buffer."
  8256. (org-with-silent-modifications
  8257. (org-with-point-at 1
  8258. (let ((regexp (concat org-outline-regexp-bol
  8259. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8260. (while (re-search-forward regexp nil t)
  8261. (let* ((numerator (string-to-number (match-string 1)))
  8262. (denominator (and (match-end 2)
  8263. (string-to-number (match-string 2))))
  8264. (stats (cond ((not denominator) numerator) ;percent
  8265. ((= denominator 0) 0)
  8266. (t (/ (* numerator 100) denominator)))))
  8267. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8268. 'org-stats stats)))))))
  8269. (defun org-refresh-effort-properties ()
  8270. "Refresh effort properties"
  8271. (org-refresh-properties
  8272. org-effort-property
  8273. '((effort . identity)
  8274. (effort-minutes . org-duration-to-minutes))))
  8275. ;;;; Link Stuff
  8276. ;;; Link abbreviations
  8277. (defun org-link-expand-abbrev (link)
  8278. "Apply replacements as defined in `org-link-abbrev-alist'."
  8279. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8280. (let* ((key (match-string 1 link))
  8281. (as (or (assoc key org-link-abbrev-alist-local)
  8282. (assoc key org-link-abbrev-alist)))
  8283. (tag (and (match-end 2) (match-string 3 link)))
  8284. rpl)
  8285. (if (not as)
  8286. link
  8287. (setq rpl (cdr as))
  8288. (cond
  8289. ((symbolp rpl) (funcall rpl tag))
  8290. ((string-match "%(\\([^)]+\\))" rpl)
  8291. (replace-match
  8292. (save-match-data
  8293. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8294. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8295. ((string-match "%h" rpl)
  8296. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8297. (t (concat rpl tag)))))
  8298. link))
  8299. ;;; Storing and inserting links
  8300. (defvar org-insert-link-history nil
  8301. "Minibuffer history for links inserted with `org-insert-link'.")
  8302. (defvar org-stored-links nil
  8303. "Contains the links stored with `org-store-link'.")
  8304. (defvar org-store-link-plist nil
  8305. "Plist with info about the most recently link created with `org-store-link'.")
  8306. (defun org-store-link-functions ()
  8307. "Return a list of functions that are called to create and store a link.
  8308. The functions defined in the :store property of
  8309. `org-link-parameters'.
  8310. Each function will be called in turn until one returns a non-nil
  8311. value. Each function should check if it is responsible for
  8312. creating this link (for example by looking at the major mode).
  8313. If not, it must exit and return nil. If yes, it should return
  8314. a non-nil value after calling `org-store-link-props' with a list
  8315. of properties and values. Special properties are:
  8316. :type The link prefix, like \"http\". This must be given.
  8317. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8318. This is obligatory as well.
  8319. :description Optional default description for the second pair
  8320. of brackets in an Org mode link. The user can still change
  8321. this when inserting this link into an Org mode buffer.
  8322. In addition to these, any additional properties can be specified
  8323. and then used in capture templates."
  8324. (cl-loop for link in org-link-parameters
  8325. with store-func
  8326. do (setq store-func (org-link-get-parameter (car link) :store))
  8327. if store-func
  8328. collect store-func))
  8329. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8330. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8331. ;;;###autoload
  8332. (defun org-store-link (arg)
  8333. "Store an org-link to the current location.
  8334. \\<org-mode-map>
  8335. This link is added to `org-stored-links' and can later be inserted
  8336. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8337. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8338. A single
  8339. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8340. `org-gnus-prefer-web-links' for links to Usenet articles.
  8341. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8342. skipping storing functions that are not
  8343. part of Org core.
  8344. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8345. prefix ARG forces storing a link for each line in the
  8346. active region."
  8347. (interactive "P")
  8348. (org-load-modules-maybe)
  8349. (if (and (equal arg '(64)) (org-region-active-p))
  8350. (save-excursion
  8351. (let ((end (region-end)))
  8352. (goto-char (region-beginning))
  8353. (set-mark (point))
  8354. (while (< (point-at-eol) end)
  8355. (move-end-of-line 1) (activate-mark)
  8356. (let (current-prefix-arg)
  8357. (call-interactively 'org-store-link))
  8358. (move-beginning-of-line 2)
  8359. (set-mark (point)))))
  8360. (setq org-store-link-plist nil)
  8361. (let (link cpltxt desc description search
  8362. txt custom-id agenda-link sfuns sfunsn)
  8363. (cond
  8364. ;; Store a link using an external link type
  8365. ((and (not (equal arg '(16)))
  8366. (setq sfuns
  8367. (delq
  8368. nil (mapcar (lambda (f)
  8369. (let (fs) (if (funcall f) (push f fs))))
  8370. (org-store-link-functions)))
  8371. sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
  8372. (or (and (cdr sfuns)
  8373. (funcall (intern
  8374. (completing-read
  8375. "Which function for creating the link? "
  8376. sfunsn nil t (car sfunsn)))))
  8377. (funcall (caar sfuns)))
  8378. (setq link (plist-get org-store-link-plist :link)
  8379. desc (or (plist-get org-store-link-plist
  8380. :description)
  8381. link))))
  8382. ;; Store a link from a source code buffer.
  8383. ((org-src-edit-buffer-p)
  8384. (let ((coderef-format (org-src-coderef-format)))
  8385. (cond ((save-excursion
  8386. (beginning-of-line)
  8387. (looking-at (org-src-coderef-regexp coderef-format)))
  8388. (setq link (format "(%s)" (match-string-no-properties 3))))
  8389. ((called-interactively-p 'any)
  8390. (let ((label (read-string "Code line label: ")))
  8391. (end-of-line)
  8392. (setq link (format coderef-format label))
  8393. (let ((gc (- 79 (length link))))
  8394. (if (< (current-column) gc)
  8395. (org-move-to-column gc t)
  8396. (insert " ")))
  8397. (insert link)
  8398. (setq link (concat "(" label ")"))
  8399. (setq desc nil)))
  8400. (t (setq link nil)))))
  8401. ;; We are in the agenda, link to referenced location
  8402. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8403. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8404. (get-text-property (point) 'org-marker))))
  8405. (when m
  8406. (org-with-point-at m
  8407. (setq agenda-link
  8408. (if (called-interactively-p 'any)
  8409. (call-interactively 'org-store-link)
  8410. (org-store-link nil)))))))
  8411. ((eq major-mode 'calendar-mode)
  8412. (let ((cd (calendar-cursor-to-date)))
  8413. (setq link
  8414. (format-time-string
  8415. (car org-time-stamp-formats)
  8416. (apply 'encode-time
  8417. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8418. nil nil nil))))
  8419. (org-store-link-props :type "calendar" :date cd)))
  8420. ((eq major-mode 'help-mode)
  8421. (setq link (concat "help:" (save-excursion
  8422. (goto-char (point-min))
  8423. (looking-at "^[^ ]+")
  8424. (match-string 0))))
  8425. (org-store-link-props :type "help"))
  8426. ((eq major-mode 'w3-mode)
  8427. (setq cpltxt (if (and (buffer-name)
  8428. (not (string-match "Untitled" (buffer-name))))
  8429. (buffer-name)
  8430. (url-view-url t))
  8431. link (url-view-url t))
  8432. (org-store-link-props :type "w3" :url (url-view-url t)))
  8433. ((eq major-mode 'image-mode)
  8434. (setq cpltxt (concat "file:"
  8435. (abbreviate-file-name buffer-file-name))
  8436. link cpltxt)
  8437. (org-store-link-props :type "image" :file buffer-file-name))
  8438. ;; In dired, store a link to the file of the current line
  8439. ((derived-mode-p 'dired-mode)
  8440. (let ((file (dired-get-filename nil t)))
  8441. (setq file (if file
  8442. (abbreviate-file-name
  8443. (expand-file-name (dired-get-filename nil t)))
  8444. ;; otherwise, no file so use current directory.
  8445. default-directory))
  8446. (setq cpltxt (concat "file:" file)
  8447. link cpltxt)))
  8448. ((setq search (run-hook-with-args-until-success
  8449. 'org-create-file-search-functions))
  8450. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8451. "::" search))
  8452. (setq cpltxt (or description link)))
  8453. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8454. (org-with-limited-levels
  8455. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8456. (cond
  8457. ;; Store a link using the target at point
  8458. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8459. (setq cpltxt
  8460. (concat "file:"
  8461. (abbreviate-file-name
  8462. (buffer-file-name (buffer-base-buffer)))
  8463. "::" (match-string 1))
  8464. link cpltxt))
  8465. ((and (featurep 'org-id)
  8466. (or (eq org-id-link-to-org-use-id t)
  8467. (and (called-interactively-p 'any)
  8468. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8469. (and (eq org-id-link-to-org-use-id
  8470. 'create-if-interactive-and-no-custom-id)
  8471. (not custom-id))))
  8472. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8473. ;; Store a link using the ID at point
  8474. (setq link (condition-case nil
  8475. (prog1 (org-id-store-link)
  8476. (setq desc (or (plist-get org-store-link-plist
  8477. :description)
  8478. "")))
  8479. (error
  8480. ;; Probably before first headline, link only to file
  8481. (concat "file:"
  8482. (abbreviate-file-name
  8483. (buffer-file-name (buffer-base-buffer))))))))
  8484. (t
  8485. ;; Just link to current headline
  8486. (setq cpltxt (concat "file:"
  8487. (abbreviate-file-name
  8488. (buffer-file-name (buffer-base-buffer)))))
  8489. ;; Add a context search string
  8490. (when (org-xor org-context-in-file-links
  8491. (equal arg '(4)))
  8492. (let* ((element (org-element-at-point))
  8493. (name (org-element-property :name element)))
  8494. (setq txt (cond
  8495. ((org-at-heading-p) nil)
  8496. (name)
  8497. ((org-region-active-p)
  8498. (buffer-substring (region-beginning) (region-end)))))
  8499. (when (or (null txt) (string-match "\\S-" txt))
  8500. (setq cpltxt
  8501. (concat cpltxt "::"
  8502. (condition-case nil
  8503. (org-make-org-heading-search-string txt)
  8504. (error "")))
  8505. desc (or name
  8506. (nth 4 (ignore-errors (org-heading-components)))
  8507. "NONE")))))
  8508. (when (string-match "::\\'" cpltxt)
  8509. (setq cpltxt (substring cpltxt 0 -2)))
  8510. (setq link cpltxt)))))
  8511. ((buffer-file-name (buffer-base-buffer))
  8512. ;; Just link to this file here.
  8513. (setq cpltxt (concat "file:"
  8514. (abbreviate-file-name
  8515. (buffer-file-name (buffer-base-buffer)))))
  8516. ;; Add a context string.
  8517. (when (org-xor org-context-in-file-links
  8518. (equal arg '(4)))
  8519. (setq txt (if (org-region-active-p)
  8520. (buffer-substring (region-beginning) (region-end))
  8521. (buffer-substring (point-at-bol) (point-at-eol))))
  8522. ;; Only use search option if there is some text.
  8523. (when (string-match "\\S-" txt)
  8524. (setq cpltxt
  8525. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8526. desc "NONE")))
  8527. (setq link cpltxt))
  8528. ((called-interactively-p 'interactive)
  8529. (user-error "No method for storing a link from this buffer"))
  8530. (t (setq link nil)))
  8531. ;; We're done setting link and desc, clean up
  8532. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8533. (setq link (or link cpltxt)
  8534. desc (or desc cpltxt))
  8535. (cond ((not desc))
  8536. ((equal desc "NONE") (setq desc nil))
  8537. (t (setq desc
  8538. (replace-regexp-in-string
  8539. org-bracket-link-analytic-regexp
  8540. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8541. desc))))
  8542. ;; Return the link
  8543. (if (not (and (or (called-interactively-p 'any)
  8544. executing-kbd-macro)
  8545. link))
  8546. (or agenda-link (and link (org-make-link-string link desc)))
  8547. (push (list link desc) org-stored-links)
  8548. (message "Stored: %s" (or desc link))
  8549. (when custom-id
  8550. (setq link (concat "file:" (abbreviate-file-name
  8551. (buffer-file-name)) "::#" custom-id))
  8552. (push (list link desc) org-stored-links))
  8553. (car org-stored-links)))))
  8554. (defun org-store-link-props (&rest plist)
  8555. "Store link properties.
  8556. The properties are pre-processed by extracting names, addresses
  8557. and dates."
  8558. (let ((x (plist-get plist :from)))
  8559. (when x
  8560. (let ((adr (mail-extract-address-components x)))
  8561. (setq plist (plist-put plist :fromname (car adr)))
  8562. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8563. (let ((x (plist-get plist :to)))
  8564. (when x
  8565. (let ((adr (mail-extract-address-components x)))
  8566. (setq plist (plist-put plist :toname (car adr)))
  8567. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8568. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8569. (when x
  8570. (setq plist (plist-put plist :date-timestamp
  8571. (format-time-string
  8572. (org-time-stamp-format t) x)))
  8573. (setq plist (plist-put plist :date-timestamp-inactive
  8574. (format-time-string
  8575. (org-time-stamp-format t t) x)))))
  8576. (let ((from (plist-get plist :from))
  8577. (to (plist-get plist :to)))
  8578. (when (and from to org-from-is-user-regexp)
  8579. (setq plist
  8580. (plist-put plist :fromto
  8581. (if (string-match org-from-is-user-regexp from)
  8582. (concat "to %t")
  8583. (concat "from %f"))))))
  8584. (setq org-store-link-plist plist))
  8585. (defun org-add-link-props (&rest plist)
  8586. "Add these properties to the link property list."
  8587. (let (key value)
  8588. (while plist
  8589. (setq key (pop plist) value (pop plist))
  8590. (setq org-store-link-plist
  8591. (plist-put org-store-link-plist key value)))))
  8592. (defun org-email-link-description (&optional fmt)
  8593. "Return the description part of an email link.
  8594. This takes information from `org-store-link-plist' and formats it
  8595. according to FMT (default from `org-email-link-description-format')."
  8596. (setq fmt (or fmt org-email-link-description-format))
  8597. (let* ((p org-store-link-plist)
  8598. (to (plist-get p :toaddress))
  8599. (from (plist-get p :fromaddress))
  8600. (table
  8601. (list
  8602. (cons "%c" (plist-get p :fromto))
  8603. (cons "%F" (plist-get p :from))
  8604. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8605. (cons "%T" (plist-get p :to))
  8606. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8607. (cons "%s" (plist-get p :subject))
  8608. (cons "%d" (plist-get p :date))
  8609. (cons "%m" (plist-get p :message-id)))))
  8610. (when (string-match "%c" fmt)
  8611. ;; Check if the user wrote this message
  8612. (if (and org-from-is-user-regexp from to
  8613. (save-match-data (string-match org-from-is-user-regexp from)))
  8614. (setq fmt (replace-match "to %t" t t fmt))
  8615. (setq fmt (replace-match "from %f" t t fmt))))
  8616. (org-replace-escapes fmt table)))
  8617. (defun org-make-org-heading-search-string (&optional string)
  8618. "Make search string for the current headline or STRING."
  8619. (let ((s (or string
  8620. (and (derived-mode-p 'org-mode)
  8621. (save-excursion
  8622. (org-back-to-heading t)
  8623. (org-element-property :raw-value (org-element-at-point))))))
  8624. (lines org-context-in-file-links))
  8625. (unless string (setq s (concat "*" s))) ;Add * for headlines
  8626. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8627. (when (and string (integerp lines) (> lines 0))
  8628. (let ((slines (org-split-string s "\n")))
  8629. (when (< lines (length slines))
  8630. (setq s (mapconcat
  8631. 'identity
  8632. (reverse (nthcdr (- (length slines) lines)
  8633. (reverse slines))) "\n")))))
  8634. (mapconcat #'identity (split-string s) " ")))
  8635. (defun org-make-link-string (link &optional description)
  8636. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8637. (unless (org-string-nw-p link) (error "Empty link"))
  8638. (let ((uri (cond ((string-match org-link-types-re link)
  8639. (concat (match-string 1 link)
  8640. (org-link-escape (substring link (match-end 1)))))
  8641. ;; For readability, url-encode internal links only
  8642. ;; when absolutely needed (i.e, when they contain
  8643. ;; square brackets). File links however, are
  8644. ;; encoded since, e.g., spaces are significant.
  8645. ((or (file-name-absolute-p link)
  8646. (string-match-p "\\`\\.\\.?/\\|[][]" link))
  8647. (org-link-escape link))
  8648. (t link)))
  8649. (description
  8650. (and (org-string-nw-p description)
  8651. ;; Remove brackets from description, as they are fatal.
  8652. (replace-regexp-in-string
  8653. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8654. (org-trim description)))))
  8655. (format "[[%s]%s]"
  8656. uri
  8657. (if description (format "[%s]" description) ""))))
  8658. (defconst org-link-escape-chars
  8659. ;;%20 %5B %5D %25
  8660. '(?\s ?\[ ?\] ?%)
  8661. "List of characters that should be escaped in a link when stored to Org.
  8662. This is the list that is used for internal purposes.")
  8663. (defun org-link-escape (text &optional table merge)
  8664. "Return percent escaped representation of TEXT.
  8665. TEXT is a string with the text to escape.
  8666. Optional argument TABLE is a list with characters that should be
  8667. escaped. When nil, `org-link-escape-chars' is used.
  8668. If optional argument MERGE is set, merge TABLE into
  8669. `org-link-escape-chars'."
  8670. (let ((characters-to-encode
  8671. (cond ((null table) org-link-escape-chars)
  8672. (merge (append org-link-escape-chars table))
  8673. (t table))))
  8674. (mapconcat
  8675. (lambda (c)
  8676. (if (or (memq c characters-to-encode)
  8677. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8678. (mapconcat (lambda (e) (format "%%%.2X" e))
  8679. (or (encode-coding-char c 'utf-8)
  8680. (error "Unable to percent escape character: %c" c))
  8681. "")
  8682. (char-to-string c)))
  8683. text "")))
  8684. (defun org-link-unescape (str)
  8685. "Unhex hexified Unicode parts in string STR.
  8686. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  8687. reciprocal of `org-link-escape', which see."
  8688. (if (org-string-nw-p str)
  8689. (replace-regexp-in-string
  8690. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  8691. str))
  8692. (defun org-link-unescape-compound (hex)
  8693. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  8694. Note: this function also decodes single byte encodings like
  8695. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  8696. (save-match-data
  8697. (let* ((bytes (cdr (split-string hex "%")))
  8698. (ret "")
  8699. (eat 0)
  8700. (sum 0))
  8701. (while bytes
  8702. (let* ((val (string-to-number (pop bytes) 16))
  8703. (shift-xor
  8704. (if (= 0 eat)
  8705. (cond
  8706. ((>= val 252) (cons 6 252))
  8707. ((>= val 248) (cons 5 248))
  8708. ((>= val 240) (cons 4 240))
  8709. ((>= val 224) (cons 3 224))
  8710. ((>= val 192) (cons 2 192))
  8711. (t (cons 0 0)))
  8712. (cons 6 128))))
  8713. (when (>= val 192) (setq eat (car shift-xor)))
  8714. (setq val (logxor val (cdr shift-xor)))
  8715. (setq sum (+ (lsh sum (car shift-xor)) val))
  8716. (when (> eat 0) (setq eat (- eat 1)))
  8717. (cond
  8718. ((= 0 eat) ;multi byte
  8719. (setq ret (concat ret (char-to-string sum)))
  8720. (setq sum 0))
  8721. ((not bytes) ; single byte(s)
  8722. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  8723. ret)))
  8724. (defun org-link-unescape-single-byte-sequence (hex)
  8725. "Unhexify hex-encoded single byte character sequences."
  8726. (mapconcat (lambda (byte)
  8727. (char-to-string (string-to-number byte 16)))
  8728. (cdr (split-string hex "%")) ""))
  8729. (defun org-fixup-message-id-for-http (s)
  8730. "Replace special characters in a message id, so it can be used in an http query."
  8731. (when (string-match "%" s)
  8732. (setq s (mapconcat (lambda (c)
  8733. (if (eq c ?%)
  8734. "%25"
  8735. (char-to-string c)))
  8736. s "")))
  8737. (while (string-match "<" s)
  8738. (setq s (replace-match "%3C" t t s)))
  8739. (while (string-match ">" s)
  8740. (setq s (replace-match "%3E" t t s)))
  8741. (while (string-match "@" s)
  8742. (setq s (replace-match "%40" t t s)))
  8743. s)
  8744. (defun org-link-prettify (link)
  8745. "Return a human-readable representation of LINK.
  8746. The car of LINK must be a raw link.
  8747. The cdr of LINK must be either a link description or nil."
  8748. (let ((desc (or (cadr link) "<no description>")))
  8749. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  8750. "<" (car link) ">")))
  8751. ;;;###autoload
  8752. (defun org-insert-link-global ()
  8753. "Insert a link like Org mode does.
  8754. This command can be called in any mode to insert a link in Org syntax."
  8755. (interactive)
  8756. (org-load-modules-maybe)
  8757. (org-run-like-in-org-mode 'org-insert-link))
  8758. (defun org-insert-all-links (arg &optional pre post)
  8759. "Insert all links in `org-stored-links'.
  8760. When a universal prefix, do not delete the links from `org-stored-links'.
  8761. When `ARG' is a number, insert the last N link(s).
  8762. `PRE' and `POST' are optional arguments to define a string to
  8763. prepend or to append."
  8764. (interactive "P")
  8765. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  8766. (links (copy-sequence org-stored-links))
  8767. (pr (or pre "- "))
  8768. (po (or post "\n"))
  8769. (cnt 1) l)
  8770. (if (null org-stored-links)
  8771. (message "No link to insert")
  8772. (while (and (or (listp arg) (>= arg cnt))
  8773. (setq l (if (listp arg)
  8774. (pop links)
  8775. (pop org-stored-links))))
  8776. (setq cnt (1+ cnt))
  8777. (insert pr)
  8778. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  8779. (insert po)))))
  8780. (defun org-insert-last-stored-link (arg)
  8781. "Insert the last link stored in `org-stored-links'."
  8782. (interactive "p")
  8783. (org-insert-all-links arg "" "\n"))
  8784. (defun org-link-fontify-links-to-this-file ()
  8785. "Fontify links to the current file in `org-stored-links'."
  8786. (let ((f (buffer-file-name)) a b)
  8787. (setq a (mapcar (lambda(l)
  8788. (let ((ll (car l)))
  8789. (when (and (string-match "^file:\\(.+\\)::" ll)
  8790. (equal f (expand-file-name (match-string 1 ll))))
  8791. ll)))
  8792. org-stored-links))
  8793. (when (featurep 'org-id)
  8794. (setq b (mapcar (lambda(l)
  8795. (let ((ll (car l)))
  8796. (when (and (string-match "^id:\\(.+\\)$" ll)
  8797. (equal f (expand-file-name
  8798. (or (org-id-find-id-file
  8799. (match-string 1 ll)) ""))))
  8800. ll)))
  8801. org-stored-links)))
  8802. (mapcar (lambda(l)
  8803. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  8804. (delq nil (append a b)))))
  8805. (defvar org--links-history nil)
  8806. (defun org-insert-link (&optional complete-file link-location default-description)
  8807. "Insert a link. At the prompt, enter the link.
  8808. Completion can be used to insert any of the link protocol prefixes in use.
  8809. The history can be used to select a link previously stored with
  8810. `org-store-link'. When the empty string is entered (i.e. if you just
  8811. press `RET' at the prompt), the link defaults to the most recently
  8812. stored link. As `SPC' triggers completion in the minibuffer, you need to
  8813. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  8814. You will also be prompted for a description, and if one is given, it will
  8815. be displayed in the buffer instead of the link.
  8816. If there is already a link at point, this command will allow you to edit
  8817. link and description parts.
  8818. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  8819. file name can be
  8820. selected using completion. The path to the file will be relative to the
  8821. current directory if the file is in the current directory or a subdirectory.
  8822. Otherwise, the link will be the absolute path as completed in the minibuffer
  8823. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  8824. option `org-link-file-path-type'.
  8825. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  8826. absolute path even if the file is in
  8827. the current directory or below.
  8828. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8829. prefix negates `org-keep-stored-link-after-insertion'.
  8830. If the LINK-LOCATION parameter is non-nil, this value will be used as
  8831. the link location instead of reading one interactively.
  8832. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  8833. be used as the default description. Otherwise, if
  8834. `org-make-link-description-function' is non-nil, this function
  8835. will be called with the link target, and the result will be the
  8836. default link description."
  8837. (interactive "P")
  8838. (let* ((wcf (current-window-configuration))
  8839. (origbuf (current-buffer))
  8840. (region (when (org-region-active-p)
  8841. (buffer-substring (region-beginning) (region-end))))
  8842. (remove (and region (list (region-beginning) (region-end))))
  8843. (desc region)
  8844. (link link-location)
  8845. (abbrevs org-link-abbrev-alist-local)
  8846. entry all-prefixes auto-desc)
  8847. (cond
  8848. (link-location) ; specified by arg, just use it.
  8849. ((org-in-regexp org-bracket-link-regexp 1)
  8850. ;; We do have a link at point, and we are going to edit it.
  8851. (setq remove (list (match-beginning 0) (match-end 0)))
  8852. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  8853. (setq link (read-string "Link: "
  8854. (org-link-unescape
  8855. (match-string-no-properties 1)))))
  8856. ((or (org-in-regexp org-angle-link-re)
  8857. (org-in-regexp org-plain-link-re))
  8858. ;; Convert to bracket link
  8859. (setq remove (list (match-beginning 0) (match-end 0))
  8860. link (read-string "Link: "
  8861. (org-unbracket-string "<" ">" (match-string 0)))))
  8862. ((member complete-file '((4) (16)))
  8863. ;; Completing read for file names.
  8864. (setq link (org-file-complete-link complete-file)))
  8865. (t
  8866. ;; Read link, with completion for stored links.
  8867. (org-link-fontify-links-to-this-file)
  8868. (org-switch-to-buffer-other-window "*Org Links*")
  8869. (with-current-buffer "*Org Links*"
  8870. (erase-buffer)
  8871. (insert "Insert a link.
  8872. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  8873. (when org-stored-links
  8874. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  8875. (insert (mapconcat 'org-link-prettify
  8876. (reverse org-stored-links) "\n")))
  8877. (goto-char (point-min)))
  8878. (let ((cw (selected-window)))
  8879. (select-window (get-buffer-window "*Org Links*" 'visible))
  8880. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  8881. (unless (pos-visible-in-window-p (point-max))
  8882. (org-fit-window-to-buffer))
  8883. (and (window-live-p cw) (select-window cw)))
  8884. (setq all-prefixes (append (mapcar 'car abbrevs)
  8885. (mapcar 'car org-link-abbrev-alist)
  8886. (org-link-types)))
  8887. (unwind-protect
  8888. ;; Fake a link history, containing the stored links.
  8889. (let ((org--links-history
  8890. (append (mapcar #'car org-stored-links)
  8891. org-insert-link-history)))
  8892. (setq link
  8893. (org-completing-read
  8894. "Link: "
  8895. (append
  8896. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  8897. (mapcar #'car org-stored-links))
  8898. nil nil nil
  8899. 'org--links-history
  8900. (caar org-stored-links)))
  8901. (unless (org-string-nw-p link) (user-error "No link selected"))
  8902. (dolist (l org-stored-links)
  8903. (when (equal link (cadr l))
  8904. (setq link (car l))
  8905. (setq auto-desc t)))
  8906. (when (or (member link all-prefixes)
  8907. (and (equal ":" (substring link -1))
  8908. (member (substring link 0 -1) all-prefixes)
  8909. (setq link (substring link 0 -1))))
  8910. (setq link (with-current-buffer origbuf
  8911. (org-link-try-special-completion link)))))
  8912. (set-window-configuration wcf)
  8913. (kill-buffer "*Org Links*"))
  8914. (setq entry (assoc link org-stored-links))
  8915. (or entry (push link org-insert-link-history))
  8916. (setq desc (or desc (nth 1 entry)))))
  8917. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  8918. (not org-keep-stored-link-after-insertion))
  8919. (setq org-stored-links (delq (assoc link org-stored-links)
  8920. org-stored-links)))
  8921. (when (and (string-match org-plain-link-re link)
  8922. (not (string-match org-ts-regexp link)))
  8923. ;; URL-like link, normalize the use of angular brackets.
  8924. (setq link (org-unbracket-string "<" ">" link)))
  8925. ;; Check if we are linking to the current file with a search
  8926. ;; option If yes, simplify the link by using only the search
  8927. ;; option.
  8928. (when (and buffer-file-name
  8929. (let ((case-fold-search nil))
  8930. (string-match "\\`file:\\(.+?\\)::" link)))
  8931. (let ((path (match-string-no-properties 1 link))
  8932. (search (substring-no-properties link (match-end 0))))
  8933. (save-match-data
  8934. (when (equal (file-truename buffer-file-name) (file-truename path))
  8935. ;; We are linking to this same file, with a search option
  8936. (setq link search)))))
  8937. ;; Check if we can/should use a relative path. If yes, simplify the link
  8938. (let ((case-fold-search nil))
  8939. (when (string-match "\\`\\(file\\|docview\\):" link)
  8940. (let* ((type (match-string-no-properties 0 link))
  8941. (path (substring-no-properties link (match-end 0)))
  8942. (origpath path))
  8943. (cond
  8944. ((or (eq org-link-file-path-type 'absolute)
  8945. (equal complete-file '(16)))
  8946. (setq path (abbreviate-file-name (expand-file-name path))))
  8947. ((eq org-link-file-path-type 'noabbrev)
  8948. (setq path (expand-file-name path)))
  8949. ((eq org-link-file-path-type 'relative)
  8950. (setq path (file-relative-name path)))
  8951. (t
  8952. (save-match-data
  8953. (if (string-match (concat "^" (regexp-quote
  8954. (expand-file-name
  8955. (file-name-as-directory
  8956. default-directory))))
  8957. (expand-file-name path))
  8958. ;; We are linking a file with relative path name.
  8959. (setq path (substring (expand-file-name path)
  8960. (match-end 0)))
  8961. (setq path (abbreviate-file-name (expand-file-name path)))))))
  8962. (setq link (concat type path))
  8963. (when (equal desc origpath)
  8964. (setq desc path)))))
  8965. (unless auto-desc
  8966. (let ((initial-input
  8967. (cond
  8968. (default-description)
  8969. ((not org-make-link-description-function) desc)
  8970. (t (condition-case nil
  8971. (funcall org-make-link-description-function link desc)
  8972. (error
  8973. (message "Can't get link description from `%s'"
  8974. (symbol-name org-make-link-description-function))
  8975. (sit-for 2)
  8976. nil))))))
  8977. (setq desc (read-string "Description: " initial-input))))
  8978. (unless (string-match "\\S-" desc) (setq desc nil))
  8979. (when remove (apply 'delete-region remove))
  8980. (insert (org-make-link-string link desc))
  8981. ;; Redisplay so as the new link has proper invisible characters.
  8982. (sit-for 0)))
  8983. (defun org-link-try-special-completion (type)
  8984. "If there is completion support for link type TYPE, offer it."
  8985. (let ((fun (org-link-get-parameter type :complete)))
  8986. (if (functionp fun)
  8987. (funcall fun)
  8988. (read-string "Link (no completion support): " (concat type ":")))))
  8989. (defun org-file-complete-link (&optional arg)
  8990. "Create a file link using completion."
  8991. (let ((file (read-file-name "File: "))
  8992. (pwd (file-name-as-directory (expand-file-name ".")))
  8993. (pwd1 (file-name-as-directory (abbreviate-file-name
  8994. (expand-file-name ".")))))
  8995. (cond ((equal arg '(16))
  8996. (concat "file:"
  8997. (abbreviate-file-name (expand-file-name file))))
  8998. ((string-match
  8999. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9000. (concat "file:" (match-string 1 file)))
  9001. ((string-match
  9002. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9003. (expand-file-name file))
  9004. (concat "file:"
  9005. (match-string 1 (expand-file-name file))))
  9006. (t (concat "file:" file)))))
  9007. ;;; Opening/following a link
  9008. (defvar org-link-search-failed nil)
  9009. (defvar org-open-link-functions nil
  9010. "Hook for functions finding a plain text link.
  9011. These functions must take a single argument, the link content.
  9012. They will be called for links that look like [[link text][description]]
  9013. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9014. like a filename (e.g. \"./blue.png\").
  9015. These functions will be called *before* Org attempts to resolve the
  9016. link by doing text searches in the current buffer - so if you want a
  9017. link \"[[target]]\" to still find \"<<target>>\", your function should
  9018. handle this as a special case.
  9019. When the function does handle the link, it must return a non-nil value.
  9020. If it decides that it is not responsible for this link, it must return
  9021. nil to indicate that that Org can continue with other options like
  9022. exact and fuzzy text search.")
  9023. (defun org-next-link (&optional search-backward)
  9024. "Move forward to the next link.
  9025. If the link is in hidden text, expose it."
  9026. (interactive "P")
  9027. (when (and org-link-search-failed (eq this-command last-command))
  9028. (goto-char (point-min))
  9029. (message "Link search wrapped back to beginning of buffer"))
  9030. (setq org-link-search-failed nil)
  9031. (let* ((pos (point))
  9032. (ct (org-context))
  9033. (a (assq :link ct))
  9034. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9035. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9036. ((looking-at org-any-link-re)
  9037. ;; Don't stay stuck at link without an org-link face
  9038. (forward-char (if search-backward -1 1))))
  9039. (if (funcall srch-fun org-any-link-re nil t)
  9040. (progn
  9041. (goto-char (match-beginning 0))
  9042. (when (org-invisible-p) (org-show-context)))
  9043. (goto-char pos)
  9044. (setq org-link-search-failed t)
  9045. (message "No further link found"))))
  9046. (defun org-previous-link ()
  9047. "Move backward to the previous link.
  9048. If the link is in hidden text, expose it."
  9049. (interactive)
  9050. (funcall 'org-next-link t))
  9051. (defun org-translate-link (s)
  9052. "Translate a link string if a translation function has been defined."
  9053. (with-temp-buffer
  9054. (insert (org-trim s))
  9055. (org-trim (org-element-interpret-data (org-element-context)))))
  9056. (defun org-translate-link-from-planner (type path)
  9057. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9058. This is still an experimental function, your mileage may vary."
  9059. (cond
  9060. ((member type '("http" "https" "news" "ftp"))
  9061. ;; standard Internet links are the same.
  9062. nil)
  9063. ((and (equal type "irc") (string-match "^//" path))
  9064. ;; Planner has two / at the beginning of an irc link, we have 1.
  9065. ;; We should have zero, actually....
  9066. (setq path (substring path 1)))
  9067. ((and (equal type "lisp") (string-match "^/" path))
  9068. ;; Planner has a slash, we do not.
  9069. (setq type "elisp" path (substring path 1)))
  9070. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9071. ;; A typical message link. Planner has the id after the final slash,
  9072. ;; we separate it with a hash mark
  9073. (setq path (concat (match-string 1 path) "#"
  9074. (org-unbracket-string "<" ">" (match-string 2 path))))))
  9075. (cons type path))
  9076. (defun org-find-file-at-mouse (ev)
  9077. "Open file link or URL at mouse."
  9078. (interactive "e")
  9079. (mouse-set-point ev)
  9080. (org-open-at-point 'in-emacs))
  9081. (defun org-open-at-mouse (ev)
  9082. "Open file link or URL at mouse.
  9083. See the docstring of `org-open-file' for details."
  9084. (interactive "e")
  9085. (mouse-set-point ev)
  9086. (when (eq major-mode 'org-agenda-mode)
  9087. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9088. (org-open-at-point))
  9089. (defvar org-window-config-before-follow-link nil
  9090. "The window configuration before following a link.
  9091. This is saved in case the need arises to restore it.")
  9092. ;;;###autoload
  9093. (defun org-open-at-point-global ()
  9094. "Follow a link or time-stamp like Org mode does.
  9095. This command can be called in any mode to follow an external link
  9096. or a time-stamp that has Org mode syntax. Its behavior is
  9097. undefined when called on internal links (e.g., fuzzy links).
  9098. Raise an error when there is nothing to follow. "
  9099. (interactive)
  9100. (cond ((org-in-regexp org-any-link-re)
  9101. (org-open-link-from-string (match-string-no-properties 0)))
  9102. ((or (org-in-regexp org-ts-regexp-both nil t)
  9103. (org-in-regexp org-tsr-regexp-both nil t))
  9104. (org-follow-timestamp-link))
  9105. (t (user-error "No link found"))))
  9106. ;;;###autoload
  9107. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9108. "Open a link in the string S, as if it was in Org mode."
  9109. (interactive "sLink: \nP")
  9110. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9111. (with-temp-buffer
  9112. (let ((org-inhibit-startup (not reference-buffer)))
  9113. (org-mode)
  9114. (insert s)
  9115. (goto-char (point-min))
  9116. (when reference-buffer
  9117. (setq org-link-abbrev-alist-local
  9118. (with-current-buffer reference-buffer
  9119. org-link-abbrev-alist-local)))
  9120. (org-open-at-point arg reference-buffer)))))
  9121. (defvar org-open-at-point-functions nil
  9122. "Hook that is run when following a link at point.
  9123. Functions in this hook must return t if they identify and follow
  9124. a link at point. If they don't find anything interesting at point,
  9125. they must return nil.")
  9126. (defvar org-link-search-inhibit-query nil)
  9127. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9128. (defun org--open-doi-link (path)
  9129. "Open a \"doi\" type link.
  9130. PATH is a the path to search for, as a string."
  9131. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9132. (defun org--open-elisp-link (path)
  9133. "Open a \"elisp\" type link.
  9134. PATH is the sexp to evaluate, as a string."
  9135. (let ((cmd path))
  9136. (if (or (and (org-string-nw-p
  9137. org-confirm-elisp-link-not-regexp)
  9138. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9139. (not org-confirm-elisp-link-function)
  9140. (funcall org-confirm-elisp-link-function
  9141. (format "Execute \"%s\" as elisp? "
  9142. (org-add-props cmd nil 'face 'org-warning))))
  9143. (message "%s => %s" cmd
  9144. (if (eq (string-to-char cmd) ?\()
  9145. (eval (read cmd))
  9146. (call-interactively (read cmd))))
  9147. (user-error "Abort"))))
  9148. (defun org--open-help-link (path)
  9149. "Open a \"help\" type link.
  9150. PATH is a symbol name, as a string."
  9151. (pcase (intern path)
  9152. ((and (pred fboundp) variable) (describe-function variable))
  9153. ((and (pred boundp) function) (describe-variable function))
  9154. (name (user-error "Unknown function or variable: %s" name))))
  9155. (defun org--open-shell-link (path)
  9156. "Open a \"shell\" type link.
  9157. PATH is the command to execute, as a string."
  9158. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9159. (cmd path))
  9160. (if (or (and (org-string-nw-p
  9161. org-confirm-shell-link-not-regexp)
  9162. (string-match
  9163. org-confirm-shell-link-not-regexp cmd))
  9164. (not org-confirm-shell-link-function)
  9165. (funcall org-confirm-shell-link-function
  9166. (format "Execute \"%s\" in shell? "
  9167. (org-add-props cmd nil
  9168. 'face 'org-warning))))
  9169. (progn
  9170. (message "Executing %s" cmd)
  9171. (shell-command cmd buf)
  9172. (when (featurep 'midnight)
  9173. (setq clean-buffer-list-kill-buffer-names
  9174. (cons (buffer-name buf)
  9175. clean-buffer-list-kill-buffer-names))))
  9176. (user-error "Abort"))))
  9177. (defun org-open-at-point (&optional arg reference-buffer)
  9178. "Open link, timestamp, footnote or tags at point.
  9179. When point is on a link, follow it. Normally, files will be
  9180. opened by an appropriate application. If the optional prefix
  9181. argument ARG is non-nil, Emacs will visit the file. With
  9182. a double prefix argument, try to open outside of Emacs, in the
  9183. application the system uses for this file type.
  9184. When point is on a timestamp, open the agenda at the day
  9185. specified.
  9186. When point is a footnote definition, move to the first reference
  9187. found. If it is on a reference, move to the associated
  9188. definition.
  9189. When point is on a headline, display a list of every link in the
  9190. entry, so it is possible to pick one, or all, of them. If point
  9191. is on a tag, call `org-tags-view' instead.
  9192. When optional argument REFERENCE-BUFFER is non-nil, it should
  9193. specify a buffer from where the link search should happen. This
  9194. is used internally by `org-open-link-from-string'.
  9195. On top of syntactically correct links, this function will also
  9196. try to open links and time-stamps in comments, example
  9197. blocks... i.e., whenever point is on something looking like
  9198. a timestamp or a link."
  9199. (interactive "P")
  9200. ;; On a code block, open block's results.
  9201. (unless (call-interactively 'org-babel-open-src-block-result)
  9202. (org-load-modules-maybe)
  9203. (setq org-window-config-before-follow-link (current-window-configuration))
  9204. (org-remove-occur-highlights nil nil t)
  9205. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9206. (let* ((context
  9207. ;; Only consider supported types, even if they are not
  9208. ;; the closest one.
  9209. (org-element-lineage
  9210. (org-element-context)
  9211. '(clock footnote-definition footnote-reference headline
  9212. inlinetask link timestamp)
  9213. t))
  9214. (type (org-element-type context))
  9215. (value (org-element-property :value context)))
  9216. (cond
  9217. ;; On a headline or an inlinetask, but not on a timestamp,
  9218. ;; a link, a footnote reference.
  9219. ((memq type '(headline inlinetask))
  9220. (org-match-line org-complex-heading-regexp)
  9221. (if (and (match-beginning 5)
  9222. (>= (point) (match-beginning 5))
  9223. (< (point) (match-end 5)))
  9224. ;; On tags.
  9225. (org-tags-view arg (substring (match-string 5) 0 -1))
  9226. ;; Not on tags.
  9227. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  9228. (`(nil . ,_)
  9229. (require 'org-attach)
  9230. (org-attach-reveal 'if-exists))
  9231. (`(,links . ,links-end)
  9232. (dolist (link (if (stringp links) (list links) links))
  9233. (search-forward link nil links-end)
  9234. (goto-char (match-beginning 0))
  9235. (org-open-at-point))))))
  9236. ;; On a footnote reference or at definition's label.
  9237. ((or (eq type 'footnote-reference)
  9238. (and (eq type 'footnote-definition)
  9239. (save-excursion
  9240. ;; Do not validate action when point is on the
  9241. ;; spaces right after the footnote label, in
  9242. ;; order to be on par with behaviour on links.
  9243. (skip-chars-forward " \t")
  9244. (let ((begin
  9245. (org-element-property :contents-begin context)))
  9246. (if begin (< (point) begin)
  9247. (= (org-element-property :post-affiliated context)
  9248. (line-beginning-position)))))))
  9249. (org-footnote-action))
  9250. ;; No valid context. Ignore catch-all types like `headline'.
  9251. ;; If point is on something looking like a link or
  9252. ;; a time-stamp, try opening it. It may be useful in
  9253. ;; comments, example blocks...
  9254. ((memq type '(footnote-definition headline inlinetask nil))
  9255. (call-interactively #'org-open-at-point-global))
  9256. ;; On a clock line, make sure point is on the timestamp
  9257. ;; before opening it.
  9258. ((and (eq type 'clock)
  9259. value
  9260. (>= (point) (org-element-property :begin value))
  9261. (<= (point) (org-element-property :end value)))
  9262. (org-follow-timestamp-link))
  9263. ;; Do nothing on white spaces after an object.
  9264. ((>= (point)
  9265. (save-excursion
  9266. (goto-char (org-element-property :end context))
  9267. (skip-chars-backward " \t")
  9268. (point)))
  9269. (user-error "No link found"))
  9270. ((eq type 'timestamp) (org-follow-timestamp-link))
  9271. ((eq type 'link)
  9272. (let ((type (org-element-property :type context))
  9273. (path (org-link-unescape (org-element-property :path context))))
  9274. ;; Switch back to REFERENCE-BUFFER needed when called in
  9275. ;; a temporary buffer through `org-open-link-from-string'.
  9276. (with-current-buffer (or reference-buffer (current-buffer))
  9277. (cond
  9278. ((equal type "file")
  9279. (if (string-match "[*?{]" (file-name-nondirectory path))
  9280. (dired path)
  9281. ;; Look into `org-link-parameters' in order to find
  9282. ;; a DEDICATED-FUNCTION to open file. The function
  9283. ;; will be applied on raw link instead of parsed
  9284. ;; link due to the limitation in `org-add-link-type'
  9285. ;; ("open" function called with a single argument).
  9286. ;; If no such function is found, fallback to
  9287. ;; `org-open-file'.
  9288. (let* ((option (org-element-property :search-option context))
  9289. (app (org-element-property :application context))
  9290. (dedicated-function
  9291. (org-link-get-parameter
  9292. (if app (concat type "+" app) type)
  9293. :follow)))
  9294. (if dedicated-function
  9295. (funcall dedicated-function
  9296. (concat path
  9297. (and option (concat "::" option))))
  9298. (apply #'org-open-file
  9299. path
  9300. (cond (arg)
  9301. ((equal app "emacs") 'emacs)
  9302. ((equal app "sys") 'system))
  9303. (cond ((not option) nil)
  9304. ((string-match-p "\\`[0-9]+\\'" option)
  9305. (list (string-to-number option)))
  9306. (t (list nil
  9307. (org-link-unescape option)))))))))
  9308. ((functionp (org-link-get-parameter type :follow))
  9309. (funcall (org-link-get-parameter type :follow) path))
  9310. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9311. (unless (run-hook-with-args-until-success
  9312. 'org-open-link-functions path)
  9313. (if (not arg) (org-mark-ring-push)
  9314. (switch-to-buffer-other-window
  9315. (org-get-buffer-for-internal-link (current-buffer))))
  9316. (let ((destination
  9317. (org-with-wide-buffer
  9318. (if (equal type "radio")
  9319. (org-search-radio-target
  9320. (org-element-property :path context))
  9321. (org-link-search
  9322. (if (member type '("custom-id" "coderef"))
  9323. (org-element-property :raw-link context)
  9324. path)
  9325. ;; Prevent fuzzy links from matching
  9326. ;; themselves.
  9327. (and (equal type "fuzzy")
  9328. (+ 2 (org-element-property :begin context)))))
  9329. (point))))
  9330. (unless (and (<= (point-min) destination)
  9331. (>= (point-max) destination))
  9332. (widen))
  9333. (goto-char destination))))
  9334. (t (browse-url-at-point))))))
  9335. (t (user-error "No link found")))))
  9336. (run-hook-with-args 'org-follow-link-hook)))
  9337. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9338. "Offer links in the current entry and return the selected link.
  9339. If there is only one link, return it.
  9340. If NTH is an integer, return the NTH link found.
  9341. If ZERO is a string, check also this string for a link, and if
  9342. there is one, return it."
  9343. (with-current-buffer buffer
  9344. (org-with-wide-buffer
  9345. (goto-char marker)
  9346. (let ((cnt ?0)
  9347. have-zero end links link c)
  9348. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9349. (push (match-string 0 zero) links)
  9350. (setq cnt (1- cnt) have-zero t))
  9351. (save-excursion
  9352. (org-back-to-heading t)
  9353. (setq end (save-excursion (outline-next-heading) (point)))
  9354. (while (re-search-forward org-any-link-re end t)
  9355. (push (match-string 0) links))
  9356. (setq links (org-uniquify (reverse links))))
  9357. (cond
  9358. ((null links)
  9359. (message "No links"))
  9360. ((equal (length links) 1)
  9361. (setq link (car links)))
  9362. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9363. (setq link (nth (if have-zero nth (1- nth)) links)))
  9364. (t ; we have to select a link
  9365. (save-excursion
  9366. (save-window-excursion
  9367. (delete-other-windows)
  9368. (with-output-to-temp-buffer "*Select Link*"
  9369. (dolist (l links)
  9370. (cond
  9371. ((not (string-match org-bracket-link-regexp l))
  9372. (princ (format "[%c] %s\n" (cl-incf cnt)
  9373. (org-unbracket-string "<" ">" l))))
  9374. ((match-end 3)
  9375. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9376. (match-string 3 l) (match-string 1 l))))
  9377. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9378. (match-string 1 l)))))))
  9379. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9380. (message "Select link to open, RET to open all:")
  9381. (setq c (read-char-exclusive))
  9382. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9383. (when (equal c ?q) (user-error "Abort"))
  9384. (if (equal c ?\C-m)
  9385. (setq link links)
  9386. (setq nth (- c ?0))
  9387. (when have-zero (setq nth (1+ nth)))
  9388. (unless (and (integerp nth) (>= (length links) nth))
  9389. (user-error "Invalid link selection"))
  9390. (setq link (nth (1- nth) links)))))
  9391. (cons link end)))))
  9392. ;; TODO: These functions are deprecated since `org-open-at-point'
  9393. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9394. (defun org-open-file-with-system (path)
  9395. "Open file at PATH using the system way of opening it."
  9396. (org-open-file path 'system))
  9397. (defun org-open-file-with-emacs (path)
  9398. "Open file at PATH in Emacs."
  9399. (org-open-file path 'emacs))
  9400. ;;; File search
  9401. (defvar org-create-file-search-functions nil
  9402. "List of functions to construct the right search string for a file link.
  9403. These functions are called in turn with point at the location to
  9404. which the link should point.
  9405. A function in the hook should first test if it would like to
  9406. handle this file type, for example by checking the `major-mode'
  9407. or the file extension. If it decides not to handle this file, it
  9408. should just return nil to give other functions a chance. If it
  9409. does handle the file, it must return the search string to be used
  9410. when following the link. The search string will be part of the
  9411. file link, given after a double colon, and `org-open-at-point'
  9412. will automatically search for it. If special measures must be
  9413. taken to make the search successful, another function should be
  9414. added to the companion hook `org-execute-file-search-functions',
  9415. which see.
  9416. A function in this hook may also use `setq' to set the variable
  9417. `description' to provide a suggestion for the descriptive text to
  9418. be used for this link when it gets inserted into an Org buffer
  9419. with \\[org-insert-link].")
  9420. (defvar org-execute-file-search-functions nil
  9421. "List of functions to execute a file search triggered by a link.
  9422. Functions added to this hook must accept a single argument, the
  9423. search string that was part of the file link, the part after the
  9424. double colon. The function must first check if it would like to
  9425. handle this search, for example by checking the `major-mode' or
  9426. the file extension. If it decides not to handle this search, it
  9427. should just return nil to give other functions a chance. If it
  9428. does handle the search, it must return a non-nil value to keep
  9429. other functions from trying.
  9430. Each function can access the current prefix argument through the
  9431. variable `current-prefix-arg'. Note that a single prefix is used
  9432. to force opening a link in Emacs, so it may be good to only use a
  9433. numeric or double prefix to guide the search function.
  9434. In case this is needed, a function in this hook can also restore
  9435. the window configuration before `org-open-at-point' was called using:
  9436. (set-window-configuration org-window-config-before-follow-link)")
  9437. (defun org-search-radio-target (target)
  9438. "Search a radio target matching TARGET in current buffer.
  9439. White spaces are not significant."
  9440. (let ((re (format "<<<%s>>>"
  9441. (mapconcat #'regexp-quote
  9442. (split-string target)
  9443. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9444. (origin (point)))
  9445. (goto-char (point-min))
  9446. (catch :radio-match
  9447. (while (re-search-forward re nil t)
  9448. (backward-char)
  9449. (let ((object (org-element-context)))
  9450. (when (eq (org-element-type object) 'radio-target)
  9451. (goto-char (org-element-property :begin object))
  9452. (org-show-context 'link-search)
  9453. (throw :radio-match nil))))
  9454. (goto-char origin)
  9455. (user-error "No match for radio target: %s" target))))
  9456. (defun org-link-search (s &optional avoid-pos stealth)
  9457. "Search for a search string S.
  9458. If S starts with \"#\", it triggers a custom ID search.
  9459. If S is enclosed within parenthesis, it initiates a coderef
  9460. search.
  9461. If S is surrounded by forward slashes, it is interpreted as
  9462. a regular expression. In Org mode files, this will create an
  9463. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9464. to list matches. If the current buffer is in `dired-mode', grep
  9465. will be used to search in all files.
  9466. When AVOID-POS is given, ignore matches near that position.
  9467. When optional argument STEALTH is non-nil, do not modify
  9468. visibility around point, thus ignoring `org-show-context-detail'
  9469. variable.
  9470. Search is case-insensitive and ignores white spaces. Return type
  9471. of matched result, which is either `dedicated' or `fuzzy'."
  9472. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9473. (let* ((case-fold-search t)
  9474. (origin (point))
  9475. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9476. (starred (eq (string-to-char normalized) ?*))
  9477. (words (split-string (if starred (substring s 1) s)))
  9478. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9479. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9480. type)
  9481. (cond
  9482. ;; Check if there are any special search functions.
  9483. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9484. ((eq (string-to-char s) ?#)
  9485. ;; Look for a custom ID S if S starts with "#".
  9486. (let* ((id (substring normalized 1))
  9487. (match (org-find-property "CUSTOM_ID" id)))
  9488. (if match (progn (goto-char match) (setf type 'dedicated))
  9489. (error "No match for custom ID: %s" id))))
  9490. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9491. ;; Look for coderef targets if S is enclosed within parenthesis.
  9492. (let ((coderef (match-string-no-properties 1 normalized))
  9493. (re (substring s-single-re 1 -1)))
  9494. (goto-char (point-min))
  9495. (catch :coderef-match
  9496. (while (re-search-forward re nil t)
  9497. (let ((element (org-element-at-point)))
  9498. (when (and (memq (org-element-type element)
  9499. '(example-block src-block))
  9500. ;; Build proper regexp according to current
  9501. ;; block's label format.
  9502. (let ((label-fmt
  9503. (regexp-quote
  9504. (or (org-element-property :label-fmt element)
  9505. org-coderef-label-format))))
  9506. (save-excursion
  9507. (beginning-of-line)
  9508. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9509. (format label-fmt coderef))))))
  9510. (setq type 'dedicated)
  9511. (goto-char (match-beginning 1))
  9512. (throw :coderef-match nil))))
  9513. (goto-char origin)
  9514. (error "No match for coderef: %s" coderef))))
  9515. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9516. ;; Look for a regular expression.
  9517. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9518. (match-string 1 s)))
  9519. ;; From here, we handle fuzzy links.
  9520. ;;
  9521. ;; Look for targets, only if not in a headline search.
  9522. ((and (not starred)
  9523. (let ((target (format "<<%s>>" s-multi-re)))
  9524. (catch :target-match
  9525. (goto-char (point-min))
  9526. (while (re-search-forward target nil t)
  9527. (backward-char)
  9528. (let ((context (org-element-context)))
  9529. (when (eq (org-element-type context) 'target)
  9530. (setq type 'dedicated)
  9531. (goto-char (org-element-property :begin context))
  9532. (throw :target-match t))))
  9533. nil))))
  9534. ;; Look for elements named after S, only if not in a headline
  9535. ;; search.
  9536. ((and (not starred)
  9537. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9538. (catch :name-match
  9539. (goto-char (point-min))
  9540. (while (re-search-forward name nil t)
  9541. (let ((element (org-element-at-point)))
  9542. (when (equal words
  9543. (split-string
  9544. (org-element-property :name element)))
  9545. (setq type 'dedicated)
  9546. (beginning-of-line)
  9547. (throw :name-match t))))
  9548. nil))))
  9549. ;; Regular text search. Prefer headlines in Org mode buffers.
  9550. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9551. ;; statistics cookies and tags.
  9552. ((and (derived-mode-p 'org-mode)
  9553. (let ((title-re
  9554. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9555. org-outline-regexp-bol
  9556. org-comment-string
  9557. (mapconcat #'regexp-quote words ".+")))
  9558. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9559. (comment-re (eval-when-compile
  9560. (format "\\`%s[ \t]+" org-comment-string))))
  9561. (goto-char (point-min))
  9562. (catch :found
  9563. (while (re-search-forward title-re nil t)
  9564. (when (equal words
  9565. (split-string
  9566. (replace-regexp-in-string
  9567. cookie-re ""
  9568. (replace-regexp-in-string
  9569. comment-re "" (org-get-heading t t t)))))
  9570. (throw :found t)))
  9571. nil)))
  9572. (beginning-of-line)
  9573. (setq type 'dedicated))
  9574. ;; Offer to create non-existent headline depending on
  9575. ;; `org-link-search-must-match-exact-headline'.
  9576. ((and (derived-mode-p 'org-mode)
  9577. (not org-link-search-inhibit-query)
  9578. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9579. (yes-or-no-p "No match - create this as a new heading? "))
  9580. (goto-char (point-max))
  9581. (unless (bolp) (newline))
  9582. (org-insert-heading nil t t)
  9583. (insert s "\n")
  9584. (beginning-of-line 0))
  9585. ;; Only headlines are looked after. No need to process
  9586. ;; further: throw an error.
  9587. ((and (derived-mode-p 'org-mode)
  9588. (or starred org-link-search-must-match-exact-headline))
  9589. (goto-char origin)
  9590. (error "No match for fuzzy expression: %s" normalized))
  9591. ;; Regular text search.
  9592. ((catch :fuzzy-match
  9593. (goto-char (point-min))
  9594. (while (re-search-forward s-multi-re nil t)
  9595. ;; Skip match if it contains AVOID-POS or it is included in
  9596. ;; a link with a description but outside the description.
  9597. (unless (or (and avoid-pos
  9598. (<= (match-beginning 0) avoid-pos)
  9599. (> (match-end 0) avoid-pos))
  9600. (and (save-match-data
  9601. (org-in-regexp org-bracket-link-regexp))
  9602. (match-beginning 3)
  9603. (or (> (match-beginning 3) (point))
  9604. (<= (match-end 3) (point)))
  9605. (org-element-lineage
  9606. (save-match-data (org-element-context))
  9607. '(link) t)))
  9608. (goto-char (match-beginning 0))
  9609. (setq type 'fuzzy)
  9610. (throw :fuzzy-match t)))
  9611. nil))
  9612. ;; All failed. Throw an error.
  9613. (t (goto-char origin)
  9614. (error "No match for fuzzy expression: %s" normalized)))
  9615. ;; Disclose surroundings of match, if appropriate.
  9616. (when (and (derived-mode-p 'org-mode) (not stealth))
  9617. (org-show-context 'link-search))
  9618. type))
  9619. (defun org-get-buffer-for-internal-link (buffer)
  9620. "Return a buffer to be used for displaying the link target of internal links."
  9621. (cond
  9622. ((not org-display-internal-link-with-indirect-buffer)
  9623. buffer)
  9624. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9625. (message "Buffer is already a clone, not making another one")
  9626. ;; we also do not modify visibility in this case
  9627. buffer)
  9628. (t ; make a new indirect buffer for displaying the link
  9629. (let* ((bn (buffer-name buffer))
  9630. (ibn (concat bn "(Clone)"))
  9631. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9632. (with-current-buffer ib (org-overview))
  9633. ib))))
  9634. (defun org-do-occur (regexp &optional cleanup)
  9635. "Call the Emacs command `occur'.
  9636. If CLEANUP is non-nil, remove the printout of the regular expression
  9637. in the *Occur* buffer. This is useful if the regex is long and not useful
  9638. to read."
  9639. (occur regexp)
  9640. (when cleanup
  9641. (let ((cwin (selected-window)) win beg end)
  9642. (when (setq win (get-buffer-window "*Occur*"))
  9643. (select-window win))
  9644. (goto-char (point-min))
  9645. (when (re-search-forward "match[a-z]+" nil t)
  9646. (setq beg (match-end 0))
  9647. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9648. (setq end (1- (match-beginning 0)))))
  9649. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9650. (goto-char (point-min))
  9651. (select-window cwin))))
  9652. ;;; The mark ring for links jumps
  9653. (defvar org-mark-ring nil
  9654. "Mark ring for positions before jumps in Org mode.")
  9655. (defvar org-mark-ring-last-goto nil
  9656. "Last position in the mark ring used to go back.")
  9657. ;; Fill and close the ring
  9658. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  9659. (dotimes (_ org-mark-ring-length)
  9660. (push (make-marker) org-mark-ring))
  9661. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  9662. org-mark-ring)
  9663. (defun org-mark-ring-push (&optional pos buffer)
  9664. "Put the current position or POS into the mark ring and rotate it."
  9665. (interactive)
  9666. (setq pos (or pos (point)))
  9667. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  9668. (move-marker (car org-mark-ring)
  9669. (or pos (point))
  9670. (or buffer (current-buffer)))
  9671. (message "%s"
  9672. (substitute-command-keys
  9673. "Position saved to mark ring, go back with \
  9674. `\\[org-mark-ring-goto]'.")))
  9675. (defun org-mark-ring-goto (&optional n)
  9676. "Jump to the previous position in the mark ring.
  9677. With prefix arg N, jump back that many stored positions. When
  9678. called several times in succession, walk through the entire ring.
  9679. Org mode commands jumping to a different position in the current file,
  9680. or to another Org file, automatically push the old position onto the ring."
  9681. (interactive "p")
  9682. (let (p m)
  9683. (if (eq last-command this-command)
  9684. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  9685. (setq p org-mark-ring))
  9686. (setq org-mark-ring-last-goto p)
  9687. (setq m (car p))
  9688. (pop-to-buffer-same-window (marker-buffer m))
  9689. (goto-char m)
  9690. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  9691. (defun org-add-angle-brackets (s)
  9692. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  9693. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  9694. s)
  9695. ;;; Following specific links
  9696. (defvar org-agenda-buffer-tmp-name)
  9697. (defvar org-agenda-start-on-weekday)
  9698. (defun org-follow-timestamp-link ()
  9699. "Open an agenda view for the time-stamp date/range at point."
  9700. (cond
  9701. ((org-at-date-range-p t)
  9702. (let ((org-agenda-start-on-weekday)
  9703. (t1 (match-string 1))
  9704. (t2 (match-string 2)) tt1 tt2)
  9705. (setq tt1 (time-to-days (org-time-string-to-time t1))
  9706. tt2 (time-to-days (org-time-string-to-time t2)))
  9707. (let ((org-agenda-buffer-tmp-name
  9708. (format "*Org Agenda(a:%s)"
  9709. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  9710. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  9711. ((org-at-timestamp-p 'lax)
  9712. (let ((org-agenda-buffer-tmp-name
  9713. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  9714. (org-agenda-list nil (time-to-days (org-time-string-to-time
  9715. (substring (match-string 1) 0 10)))
  9716. 1)))
  9717. (t (error "This should not happen"))))
  9718. ;;; Following file links
  9719. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  9720. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  9721. (declare-function mailcap-mime-info
  9722. "mailcap" (string &optional request no-decode))
  9723. (defvar org-wait nil)
  9724. (defun org-open-file (path &optional in-emacs line search)
  9725. "Open the file at PATH.
  9726. First, this expands any special file name abbreviations. Then the
  9727. configuration variable `org-file-apps' is checked if it contains an
  9728. entry for this file type, and if yes, the corresponding command is launched.
  9729. If no application is found, Emacs simply visits the file.
  9730. With optional prefix argument IN-EMACS, Emacs will visit the file.
  9731. With a double \\[universal-argument] \\[universal-argument] \
  9732. prefix arg, Org tries to avoid opening in Emacs
  9733. and to use an external application to visit the file.
  9734. Optional LINE specifies a line to go to, optional SEARCH a string
  9735. to search for. If LINE or SEARCH is given, the file will be
  9736. opened in Emacs, unless an entry from org-file-apps that makes
  9737. use of groups in a regexp matches.
  9738. If you want to change the way frames are used when following a
  9739. link, please customize `org-link-frame-setup'.
  9740. If the file does not exist, an error is thrown."
  9741. (let* ((file (if (equal path "")
  9742. buffer-file-name
  9743. (substitute-in-file-name (expand-file-name path))))
  9744. (file-apps (append org-file-apps (org-default-apps)))
  9745. (apps (cl-remove-if
  9746. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9747. (apps-dlink (cl-remove-if-not
  9748. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9749. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  9750. (dirp (unless remp (file-directory-p file)))
  9751. (file (if (and dirp org-open-directory-means-index-dot-org)
  9752. (concat (file-name-as-directory file) "index.org")
  9753. file))
  9754. (a-m-a-p (assq 'auto-mode apps))
  9755. (dfile (downcase file))
  9756. ;; Reconstruct the original link from the PATH, LINE and
  9757. ;; SEARCH args.
  9758. (link (cond (line (concat file "::" (number-to-string line)))
  9759. (search (concat file "::" search))
  9760. (t file)))
  9761. (dlink (downcase link))
  9762. (ext
  9763. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  9764. (match-string 1 dfile)))
  9765. (save-position-maybe
  9766. (let ((old-buffer (current-buffer))
  9767. (old-pos (point))
  9768. (old-mode major-mode))
  9769. (lambda ()
  9770. (and (derived-mode-p 'org-mode)
  9771. (eq old-mode 'org-mode)
  9772. (or (not (eq old-buffer (current-buffer)))
  9773. (not (eq old-pos (point))))
  9774. (org-mark-ring-push old-pos old-buffer)))))
  9775. cmd link-match-data)
  9776. (cond
  9777. ((member in-emacs '((16) system))
  9778. (setq cmd (cdr (assq 'system apps))))
  9779. (in-emacs (setq cmd 'emacs))
  9780. (t
  9781. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  9782. (and dirp (cdr (assq 'directory apps)))
  9783. ;; First, try matching against apps-dlink if we
  9784. ;; get a match here, store the match data for
  9785. ;; later.
  9786. (let ((match (assoc-default dlink apps-dlink
  9787. 'string-match)))
  9788. (if match
  9789. (progn (setq link-match-data (match-data))
  9790. match)
  9791. (progn (setq in-emacs (or in-emacs line search))
  9792. nil))) ; if we have no match in apps-dlink,
  9793. ; always open the file in emacs if line or search
  9794. ; is given (for backwards compatibility)
  9795. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  9796. 'string-match)
  9797. (cdr (assoc ext apps))
  9798. (cdr (assq t apps))))))
  9799. (when (eq cmd 'system)
  9800. (setq cmd (cdr (assq 'system apps))))
  9801. (when (eq cmd 'default)
  9802. (setq cmd (cdr (assoc t apps))))
  9803. (when (eq cmd 'mailcap)
  9804. (require 'mailcap)
  9805. (mailcap-parse-mailcaps)
  9806. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  9807. (command (mailcap-mime-info mime-type)))
  9808. (if (stringp command)
  9809. (setq cmd command)
  9810. (setq cmd 'emacs))))
  9811. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  9812. (not (file-exists-p file))
  9813. (not org-open-non-existing-files))
  9814. (user-error "No such file: %s" file))
  9815. (cond
  9816. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  9817. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  9818. (while (string-match "['\"]%s['\"]" cmd)
  9819. (setq cmd (replace-match "%s" t t cmd)))
  9820. (setq cmd (replace-regexp-in-string
  9821. "%s"
  9822. (shell-quote-argument (convert-standard-filename file))
  9823. cmd
  9824. nil t))
  9825. ;; Replace "%1", "%2" etc. in command with group matches from regex
  9826. (save-match-data
  9827. (let ((match-index 1)
  9828. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  9829. (set-match-data link-match-data)
  9830. (while (<= match-index number-of-groups)
  9831. (let ((regex (concat "%" (number-to-string match-index)))
  9832. (replace-with (match-string match-index dlink)))
  9833. (while (string-match regex cmd)
  9834. (setq cmd (replace-match replace-with t t cmd))))
  9835. (setq match-index (+ match-index 1)))))
  9836. (save-window-excursion
  9837. (message "Running %s...done" cmd)
  9838. (start-process-shell-command cmd nil cmd)
  9839. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  9840. ((or (stringp cmd)
  9841. (eq cmd 'emacs))
  9842. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  9843. (widen)
  9844. (cond (line (org-goto-line line)
  9845. (when (derived-mode-p 'org-mode) (org-reveal)))
  9846. (search (condition-case err
  9847. (org-link-search search)
  9848. ;; Save position before error-ing out so user
  9849. ;; can easily move back to the original buffer.
  9850. (error (funcall save-position-maybe)
  9851. (error (nth 1 err)))))))
  9852. ((functionp cmd)
  9853. (save-match-data
  9854. (set-match-data link-match-data)
  9855. (condition-case nil
  9856. (funcall cmd file link)
  9857. ;; FIXME: Remove this check when most default installations
  9858. ;; of Emacs have at least Org 9.0.
  9859. ((debug wrong-number-of-arguments wrong-type-argument
  9860. invalid-function)
  9861. (user-error "Please see Org News for version 9.0 about \
  9862. `org-file-apps'--Lisp error: %S" cmd)))))
  9863. ((consp cmd)
  9864. ;; FIXME: Remove this check when most default installations of
  9865. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  9866. ;; fall back to `org-link-frame-setup' for an old usage of
  9867. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  9868. (user-error "Please see Org News for version 9.0 about \
  9869. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  9870. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  9871. (funcall save-position-maybe)))
  9872. (defun org-file-apps-entry-match-against-dlink-p (entry)
  9873. "This function returns non-nil if `entry' uses a regular
  9874. expression which should be matched against the whole link by
  9875. org-open-file.
  9876. It assumes that is the case when the entry uses a regular
  9877. expression which has at least one grouping construct and the
  9878. action is either a lisp form or a command string containing
  9879. `%1', i.e. using at least one subexpression match as a
  9880. parameter."
  9881. (let ((selector (car entry))
  9882. (action (cdr entry)))
  9883. (if (stringp selector)
  9884. (and (> (regexp-opt-depth selector) 0)
  9885. (or (and (stringp action)
  9886. (string-match "%[0-9]" action))
  9887. (consp action)))
  9888. nil)))
  9889. (defun org-default-apps ()
  9890. "Return the default applications for this operating system."
  9891. (cond
  9892. ((eq system-type 'darwin)
  9893. org-file-apps-defaults-macosx)
  9894. ((eq system-type 'windows-nt)
  9895. org-file-apps-defaults-windowsnt)
  9896. (t org-file-apps-defaults-gnu)))
  9897. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  9898. "Convert extensions to regular expressions in the cars of LIST.
  9899. Also, weed out any non-string entries, because the return value is used
  9900. only for regexp matching.
  9901. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  9902. point to the symbol `emacs', indicating that the file should
  9903. be opened in Emacs."
  9904. (append
  9905. (delq nil
  9906. (mapcar (lambda (x)
  9907. (unless (not (stringp (car x)))
  9908. (if (string-match "\\W" (car x))
  9909. x
  9910. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  9911. list))
  9912. (when add-auto-mode
  9913. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  9914. (defvar ange-ftp-name-format)
  9915. (defun org-file-remote-p (file)
  9916. "Test whether FILE specifies a location on a remote system.
  9917. Return non-nil if the location is indeed remote.
  9918. For example, the filename \"/user@host:/foo\" specifies a location
  9919. on the system \"/user@host:\"."
  9920. (cond ((fboundp 'file-remote-p)
  9921. (file-remote-p file))
  9922. ((fboundp 'tramp-handle-file-remote-p)
  9923. (tramp-handle-file-remote-p file))
  9924. ((and (boundp 'ange-ftp-name-format)
  9925. (string-match (car ange-ftp-name-format) file))
  9926. t)))
  9927. ;;;; Refiling
  9928. (defun org-get-org-file ()
  9929. "Read a filename, with default directory `org-directory'."
  9930. (let ((default (or org-default-notes-file remember-data-file)))
  9931. (read-file-name (format "File name [%s]: " default)
  9932. (file-name-as-directory org-directory)
  9933. default)))
  9934. (defun org-notes-order-reversed-p ()
  9935. "Check if the current file should receive notes in reversed order."
  9936. (cond
  9937. ((not org-reverse-note-order) nil)
  9938. ((eq t org-reverse-note-order) t)
  9939. ((not (listp org-reverse-note-order)) nil)
  9940. (t (catch 'exit
  9941. (dolist (entry org-reverse-note-order)
  9942. (when (string-match (car entry) buffer-file-name)
  9943. (throw 'exit (cdr entry))))))))
  9944. (defvar org-refile-target-table nil
  9945. "The list of refile targets, created by `org-refile'.")
  9946. (defvar org-agenda-new-buffers nil
  9947. "Buffers created to visit agenda files.")
  9948. (defvar org-refile-cache nil
  9949. "Cache for refile targets.")
  9950. (defvar org-refile-markers nil
  9951. "All the markers used for caching refile locations.")
  9952. (defun org-refile-marker (pos)
  9953. "Get a new refile marker, but only if caching is in use."
  9954. (if (not org-refile-use-cache)
  9955. pos
  9956. (let ((m (make-marker)))
  9957. (move-marker m pos)
  9958. (push m org-refile-markers)
  9959. m)))
  9960. (defun org-refile-cache-clear ()
  9961. "Clear the refile cache and disable all the markers."
  9962. (dolist (m org-refile-markers) (move-marker m nil))
  9963. (setq org-refile-markers nil)
  9964. (setq org-refile-cache nil)
  9965. (message "Refile cache has been cleared"))
  9966. (defun org-refile-cache-check-set (set)
  9967. "Check if all the markers in the cache still have live buffers."
  9968. (let (marker)
  9969. (catch 'exit
  9970. (while (and set (setq marker (nth 3 (pop set))))
  9971. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  9972. (when (and marker (null (marker-buffer marker)))
  9973. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  9974. (sit-for 3)
  9975. (throw 'exit nil)))
  9976. t)))
  9977. (defun org-refile-cache-put (set &rest identifiers)
  9978. "Push the refile targets SET into the cache, under IDENTIFIERS."
  9979. (let* ((key (sha1 (prin1-to-string identifiers)))
  9980. (entry (assoc key org-refile-cache)))
  9981. (if entry
  9982. (setcdr entry set)
  9983. (push (cons key set) org-refile-cache))))
  9984. (defun org-refile-cache-get (&rest identifiers)
  9985. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  9986. (cond
  9987. ((not org-refile-cache) nil)
  9988. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  9989. (t
  9990. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  9991. org-refile-cache))))
  9992. (and set (org-refile-cache-check-set set) set)))))
  9993. (defvar org-outline-path-cache nil
  9994. "Alist between buffer positions and outline paths.
  9995. It value is an alist (POSITION . PATH) where POSITION is the
  9996. buffer position at the beginning of an entry and PATH is a list
  9997. of strings describing the outline path for that entry, in reverse
  9998. order.")
  9999. (defun org-refile-get-targets (&optional default-buffer)
  10000. "Produce a table with refile targets."
  10001. (let ((case-fold-search nil)
  10002. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10003. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10004. targets tgs files desc descre)
  10005. (message "Getting targets...")
  10006. (with-current-buffer (or default-buffer (current-buffer))
  10007. (dolist (entry entries)
  10008. (setq files (car entry) desc (cdr entry))
  10009. (cond
  10010. ((null files) (setq files (list (current-buffer))))
  10011. ((eq files 'org-agenda-files)
  10012. (setq files (org-agenda-files 'unrestricted)))
  10013. ((and (symbolp files) (fboundp files))
  10014. (setq files (funcall files)))
  10015. ((and (symbolp files) (boundp files))
  10016. (setq files (symbol-value files))))
  10017. (when (stringp files) (setq files (list files)))
  10018. (cond
  10019. ((eq (car desc) :tag)
  10020. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10021. ((eq (car desc) :todo)
  10022. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10023. ((eq (car desc) :regexp)
  10024. (setq descre (cdr desc)))
  10025. ((eq (car desc) :level)
  10026. (setq descre (concat "^\\*\\{" (number-to-string
  10027. (if org-odd-levels-only
  10028. (1- (* 2 (cdr desc)))
  10029. (cdr desc)))
  10030. "\\}[ \t]")))
  10031. ((eq (car desc) :maxlevel)
  10032. (setq descre (concat "^\\*\\{1," (number-to-string
  10033. (if org-odd-levels-only
  10034. (1- (* 2 (cdr desc)))
  10035. (cdr desc)))
  10036. "\\}[ \t]")))
  10037. (t (error "Bad refiling target description %s" desc)))
  10038. (dolist (f files)
  10039. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  10040. (or
  10041. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10042. (progn
  10043. (when (bufferp f)
  10044. (setq f (buffer-file-name (buffer-base-buffer f))))
  10045. (setq f (and f (expand-file-name f)))
  10046. (when (eq org-refile-use-outline-path 'file)
  10047. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10048. (when (eq org-refile-use-outline-path 'buffer-name)
  10049. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  10050. (when (eq org-refile-use-outline-path 'full-file-path)
  10051. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  10052. (org-with-wide-buffer
  10053. (goto-char (point-min))
  10054. (setq org-outline-path-cache nil)
  10055. (while (re-search-forward descre nil t)
  10056. (beginning-of-line)
  10057. (let ((case-fold-search nil))
  10058. (looking-at org-complex-heading-regexp))
  10059. (let ((begin (point))
  10060. (heading (match-string-no-properties 4)))
  10061. (unless (or (and
  10062. org-refile-target-verify-function
  10063. (not
  10064. (funcall org-refile-target-verify-function)))
  10065. (not heading))
  10066. (let ((re (format org-complex-heading-regexp-format
  10067. (regexp-quote heading)))
  10068. (target
  10069. (if (not org-refile-use-outline-path) heading
  10070. (mapconcat
  10071. #'identity
  10072. (append
  10073. (pcase org-refile-use-outline-path
  10074. (`file (list (file-name-nondirectory
  10075. (buffer-file-name
  10076. (buffer-base-buffer)))))
  10077. (`full-file-path
  10078. (list (buffer-file-name
  10079. (buffer-base-buffer))))
  10080. (`buffer-name
  10081. (list (buffer-name
  10082. (buffer-base-buffer))))
  10083. (_ nil))
  10084. (mapcar (lambda (s) (replace-regexp-in-string
  10085. "/" "\\/" s nil t))
  10086. (org-get-outline-path t t)))
  10087. "/"))))
  10088. (push (list target f re (org-refile-marker (point)))
  10089. tgs)))
  10090. (when (= (point) begin)
  10091. ;; Verification function has not moved point.
  10092. (end-of-line)))))))
  10093. (when org-refile-use-cache
  10094. (org-refile-cache-put tgs (buffer-file-name) descre))
  10095. (setq targets (append tgs targets))))))
  10096. (message "Getting targets...done")
  10097. (delete-dups (nreverse targets))))
  10098. (defun org--get-outline-path-1 (&optional use-cache)
  10099. "Return outline path to current headline.
  10100. Outline path is a list of strings, in reverse order. When
  10101. optional argument USE-CACHE is non-nil, make use of a cache. See
  10102. `org-get-outline-path' for details.
  10103. Assume buffer is widened and point is on a headline."
  10104. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10105. (let ((p (point))
  10106. (heading (let ((case-fold-search nil))
  10107. (looking-at org-complex-heading-regexp)
  10108. (if (not (match-end 4)) ""
  10109. ;; Remove statistics cookies.
  10110. (org-trim
  10111. (org-link-display-format
  10112. (replace-regexp-in-string
  10113. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10114. (match-string-no-properties 4))))))))
  10115. (if (org-up-heading-safe)
  10116. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10117. (when use-cache
  10118. (push (cons p path) org-outline-path-cache))
  10119. path)
  10120. ;; This is a new root node. Since we assume we are moving
  10121. ;; forward, we can drop previous cache so as to limit number
  10122. ;; of associations there.
  10123. (let ((path (list heading)))
  10124. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10125. path)))))
  10126. (defun org-get-outline-path (&optional with-self use-cache)
  10127. "Return the outline path to the current entry.
  10128. An outline path is a list of ancestors for current headline, as
  10129. a list of strings. Statistics cookies are removed and links are
  10130. replaced with their description, if any, or their path otherwise.
  10131. When optional argument WITH-SELF is non-nil, the path also
  10132. includes the current headline.
  10133. When optional argument USE-CACHE is non-nil, cache outline paths
  10134. between calls to this function so as to avoid backtracking. This
  10135. argument is useful when planning to find more than one outline
  10136. path in the same document. In that case, there are two
  10137. conditions to satisfy:
  10138. - `org-outline-path-cache' is set to nil before starting the
  10139. process;
  10140. - outline paths are computed by increasing buffer positions."
  10141. (org-with-wide-buffer
  10142. (and (or (and with-self (org-back-to-heading t))
  10143. (org-up-heading-safe))
  10144. (reverse (org--get-outline-path-1 use-cache)))))
  10145. (defun org-format-outline-path (path &optional width prefix separator)
  10146. "Format the outline path PATH for display.
  10147. WIDTH is the maximum number of characters that is available.
  10148. PREFIX is a prefix to be included in the returned string,
  10149. such as the file name.
  10150. SEPARATOR is inserted between the different parts of the path,
  10151. the default is \"/\"."
  10152. (setq width (or width 79))
  10153. (setq path (delq nil path))
  10154. (unless (> width 0)
  10155. (user-error "Argument `width' must be positive"))
  10156. (setq separator (or separator "/"))
  10157. (let* ((org-odd-levels-only nil)
  10158. (fpath (concat
  10159. prefix (and prefix path separator)
  10160. (mapconcat
  10161. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10162. (cl-loop for head in path
  10163. for n from 0
  10164. collect (org-add-props
  10165. head nil 'face
  10166. (nth (% n org-n-level-faces) org-level-faces)))
  10167. separator))))
  10168. (when (> (length fpath) width)
  10169. (if (< width 7)
  10170. ;; It's unlikely that `width' will be this small, but don't
  10171. ;; waste characters by adding ".." if it is.
  10172. (setq fpath (substring fpath 0 width))
  10173. (setf (substring fpath (- width 2)) "..")))
  10174. fpath))
  10175. (defun org-display-outline-path (&optional file current separator just-return-string)
  10176. "Display the current outline path in the echo area.
  10177. If FILE is non-nil, prepend the output with the file name.
  10178. If CURRENT is non-nil, append the current heading to the output.
  10179. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10180. the different parts of the path and defaults to \"/\".
  10181. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10182. (interactive "P")
  10183. (let* (case-fold-search
  10184. (bfn (buffer-file-name (buffer-base-buffer)))
  10185. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10186. res)
  10187. (when current (setq path (append path
  10188. (save-excursion
  10189. (org-back-to-heading t)
  10190. (when (looking-at org-complex-heading-regexp)
  10191. (list (match-string 4)))))))
  10192. (setq res
  10193. (org-format-outline-path
  10194. path
  10195. (1- (frame-width))
  10196. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10197. separator))
  10198. (if just-return-string
  10199. (org-no-properties res)
  10200. (org-unlogged-message "%s" res))))
  10201. (defvar org-refile-history nil
  10202. "History for refiling operations.")
  10203. (defvar org-after-refile-insert-hook nil
  10204. "Hook run after `org-refile' has inserted its stuff at the new location.
  10205. Note that this is still *before* the stuff will be removed from
  10206. the *old* location.")
  10207. (defvar org-capture-last-stored-marker)
  10208. (defvar org-refile-keep nil
  10209. "Non-nil means `org-refile' will copy instead of refile.")
  10210. (defun org-copy ()
  10211. "Like `org-refile', but copy."
  10212. (interactive)
  10213. (let ((org-refile-keep t))
  10214. (funcall 'org-refile nil nil nil "Copy")))
  10215. (defun org-refile (&optional arg default-buffer rfloc msg)
  10216. "Move the entry or entries at point to another heading.
  10217. The list of target headings is compiled using the information in
  10218. `org-refile-targets', which see.
  10219. At the target location, the entry is filed as a subitem of the
  10220. target heading. Depending on `org-reverse-note-order', the new
  10221. subitem will either be the first or the last subitem.
  10222. If there is an active region, all entries in that region will be
  10223. refiled. However, the region must fulfill the requirement that
  10224. the first heading sets the top-level of the moved text.
  10225. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10226. location
  10227. and not actually move anything.
  10228. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10229. location where the last
  10230. refiling operation has put the subtree.
  10231. With a numeric prefix argument of `2', refile to the running clock.
  10232. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10233. being set to t and copy to the target location, don't move it.
  10234. Beware that keeping refiled entries may result in duplicated ID
  10235. properties.
  10236. RFLOC can be a refile location obtained in a different way.
  10237. MSG is a string to replace \"Refile\" in the default prompt with
  10238. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10239. See also `org-refile-use-outline-path'.
  10240. If you are using target caching (see `org-refile-use-cache'), you
  10241. have to clear the target cache in order to find new targets.
  10242. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10243. prefix argument (`C-u C-u C-u C-c C-w')."
  10244. (interactive "P")
  10245. (if (member arg '(0 (64)))
  10246. (org-refile-cache-clear)
  10247. (let* ((actionmsg (cond (msg msg)
  10248. ((equal arg 3) "Refile (and keep)")
  10249. (t "Refile")))
  10250. (regionp (org-region-active-p))
  10251. (region-start (and regionp (region-beginning)))
  10252. (region-end (and regionp (region-end)))
  10253. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10254. pos it nbuf file level reversed)
  10255. (setq last-command nil)
  10256. (when regionp
  10257. (goto-char region-start)
  10258. (or (bolp) (goto-char (point-at-bol)))
  10259. (setq region-start (point))
  10260. (unless (or (org-kill-is-subtree-p
  10261. (buffer-substring region-start region-end))
  10262. (prog1 org-refile-active-region-within-subtree
  10263. (let ((s (point-at-eol)))
  10264. (org-toggle-heading)
  10265. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10266. (user-error "The region is not a (sequence of) subtree(s)")))
  10267. (if (equal arg '(16))
  10268. (org-refile-goto-last-stored)
  10269. (when (or
  10270. (and (equal arg 2)
  10271. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10272. (prog1
  10273. (setq it (list (or org-clock-heading "running clock")
  10274. (buffer-file-name
  10275. (marker-buffer org-clock-hd-marker))
  10276. ""
  10277. (marker-position org-clock-hd-marker)))
  10278. (setq arg nil)))
  10279. (setq it
  10280. (or rfloc
  10281. (let (heading-text)
  10282. (save-excursion
  10283. (unless (and arg (listp arg))
  10284. (org-back-to-heading t)
  10285. (setq heading-text
  10286. (replace-regexp-in-string
  10287. org-bracket-link-regexp
  10288. "\\3"
  10289. (or (nth 4 (org-heading-components))
  10290. ""))))
  10291. (org-refile-get-location
  10292. (cond ((and arg (listp arg)) "Goto")
  10293. (regionp (concat actionmsg " region to"))
  10294. (t (concat actionmsg " subtree \""
  10295. heading-text "\" to")))
  10296. default-buffer
  10297. (and (not (equal '(4) arg))
  10298. org-refile-allow-creating-parent-nodes)))))))
  10299. (setq file (nth 1 it)
  10300. pos (nth 3 it))
  10301. (when (and (not arg)
  10302. pos
  10303. (equal (buffer-file-name) file)
  10304. (if regionp
  10305. (and (>= pos region-start)
  10306. (<= pos region-end))
  10307. (and (>= pos (point))
  10308. (< pos (save-excursion
  10309. (org-end-of-subtree t t))))))
  10310. (error "Cannot refile to position inside the tree or region"))
  10311. (setq nbuf (or (find-buffer-visiting file)
  10312. (find-file-noselect file)))
  10313. (if (and arg (not (equal arg 3)))
  10314. (progn
  10315. (pop-to-buffer-same-window nbuf)
  10316. (goto-char (cond (pos)
  10317. ((org-notes-order-reversed-p) (point-min))
  10318. (t (point-max))))
  10319. (org-show-context 'org-goto))
  10320. (if regionp
  10321. (progn
  10322. (org-kill-new (buffer-substring region-start region-end))
  10323. (org-save-markers-in-region region-start region-end))
  10324. (org-copy-subtree 1 nil t))
  10325. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10326. (find-file-noselect file)))
  10327. (setq reversed (org-notes-order-reversed-p))
  10328. (org-with-wide-buffer
  10329. (if pos
  10330. (progn
  10331. (goto-char pos)
  10332. (setq level (org-get-valid-level (funcall outline-level) 1))
  10333. (goto-char
  10334. (if reversed
  10335. (or (outline-next-heading) (point-max))
  10336. (or (save-excursion (org-get-next-sibling))
  10337. (org-end-of-subtree t t)
  10338. (point-max)))))
  10339. (setq level 1)
  10340. (if (not reversed)
  10341. (goto-char (point-max))
  10342. (goto-char (point-min))
  10343. (or (outline-next-heading) (goto-char (point-max)))))
  10344. (unless (bolp) (newline))
  10345. (org-paste-subtree level nil nil t)
  10346. (when org-log-refile
  10347. (org-add-log-setup 'refile nil nil org-log-refile)
  10348. (unless (eq org-log-refile 'note)
  10349. (save-excursion (org-add-log-note))))
  10350. (and org-auto-align-tags
  10351. (let ((org-loop-over-headlines-in-active-region nil))
  10352. (org-set-tags nil t)))
  10353. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10354. :last-refile)))
  10355. (when bookmark-name
  10356. (with-demoted-errors
  10357. (bookmark-set bookmark-name))))
  10358. ;; If we are refiling for capture, make sure that the
  10359. ;; last-capture pointers point here
  10360. (when (bound-and-true-p org-capture-is-refiling)
  10361. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10362. :last-capture-marker)))
  10363. (when bookmark-name
  10364. (with-demoted-errors
  10365. (bookmark-set bookmark-name))))
  10366. (move-marker org-capture-last-stored-marker (point)))
  10367. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10368. (run-hooks 'org-after-refile-insert-hook)))
  10369. (unless org-refile-keep
  10370. (if regionp
  10371. (delete-region (point) (+ (point) (- region-end region-start)))
  10372. (delete-region
  10373. (and (org-back-to-heading t) (point))
  10374. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10375. (when (featurep 'org-inlinetask)
  10376. (org-inlinetask-remove-END-maybe))
  10377. (setq org-markers-to-move nil)
  10378. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10379. (defun org-refile-goto-last-stored ()
  10380. "Go to the location where the last refile was stored."
  10381. (interactive)
  10382. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10383. (message "This is the location of the last refile"))
  10384. (defun org-refile--get-location (refloc tbl)
  10385. "When user refile to REFLOC, find the associated target in TBL.
  10386. Also check `org-refile-target-table'."
  10387. (car (delq
  10388. nil
  10389. (mapcar
  10390. (lambda (r) (or (assoc r tbl)
  10391. (assoc r org-refile-target-table)))
  10392. (list (replace-regexp-in-string "/$" "" refloc)
  10393. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10394. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10395. "Prompt the user for a refile location, using PROMPT.
  10396. PROMPT should not be suffixed with a colon and a space, because
  10397. this function appends the default value from
  10398. `org-refile-history' automatically, if that is not empty."
  10399. (let ((org-refile-targets org-refile-targets)
  10400. (org-refile-use-outline-path org-refile-use-outline-path))
  10401. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10402. (unless org-refile-target-table
  10403. (user-error "No refile targets"))
  10404. (let* ((cbuf (current-buffer))
  10405. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10406. (cfunc (if (and org-refile-use-outline-path
  10407. org-outline-path-complete-in-steps)
  10408. #'org-olpath-completing-read
  10409. #'completing-read))
  10410. (extra (if org-refile-use-outline-path "/" ""))
  10411. (cbnex (concat (buffer-name) extra))
  10412. (filename (and cfn (expand-file-name cfn)))
  10413. (tbl (mapcar
  10414. (lambda (x)
  10415. (if (and (not (member org-refile-use-outline-path
  10416. '(file full-file-path)))
  10417. (not (equal filename (nth 1 x))))
  10418. (cons (concat (car x) extra " ("
  10419. (file-name-nondirectory (nth 1 x)) ")")
  10420. (cdr x))
  10421. (cons (concat (car x) extra) (cdr x))))
  10422. org-refile-target-table))
  10423. (completion-ignore-case t)
  10424. cdef
  10425. (prompt (concat prompt
  10426. (or (and (car org-refile-history)
  10427. (concat " (default " (car org-refile-history) ")"))
  10428. (and (assoc cbnex tbl) (setq cdef cbnex)
  10429. (concat " (default " cbnex ")"))) ": "))
  10430. pa answ parent-target child parent old-hist)
  10431. (setq old-hist org-refile-history)
  10432. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10433. nil 'org-refile-history (or cdef (car org-refile-history))))
  10434. (if (setq pa (org-refile--get-location answ tbl))
  10435. (progn
  10436. (org-refile-check-position pa)
  10437. (when (or (not org-refile-history)
  10438. (not (eq old-hist org-refile-history))
  10439. (not (equal (car pa) (car org-refile-history))))
  10440. (setq org-refile-history
  10441. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10442. org-refile-history
  10443. (cdr org-refile-history))))
  10444. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10445. (pop org-refile-history)))
  10446. pa)
  10447. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10448. (progn
  10449. (setq parent (match-string 1 answ)
  10450. child (match-string 2 answ))
  10451. (setq parent-target (org-refile--get-location parent tbl))
  10452. (when (and parent-target
  10453. (or (eq new-nodes t)
  10454. (and (eq new-nodes 'confirm)
  10455. (y-or-n-p (format "Create new node \"%s\"? "
  10456. child)))))
  10457. (org-refile-new-child parent-target child)))
  10458. (user-error "Invalid target location")))))
  10459. (declare-function org-string-nw-p "org-macs" (s))
  10460. (defun org-refile-check-position (refile-pointer)
  10461. "Check if the refile pointer matches the headline to which it points."
  10462. (let* ((file (nth 1 refile-pointer))
  10463. (re (nth 2 refile-pointer))
  10464. (pos (nth 3 refile-pointer))
  10465. buffer)
  10466. (if (and (not (markerp pos)) (not file))
  10467. (user-error "Please indicate a target file in the refile path")
  10468. (when (org-string-nw-p re)
  10469. (setq buffer (if (markerp pos)
  10470. (marker-buffer pos)
  10471. (or (find-buffer-visiting file)
  10472. (find-file-noselect file))))
  10473. (with-current-buffer buffer
  10474. (org-with-wide-buffer
  10475. (goto-char pos)
  10476. (beginning-of-line 1)
  10477. (unless (looking-at-p re)
  10478. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10479. (defun org-refile-new-child (parent-target child)
  10480. "Use refile target PARENT-TARGET to add new CHILD below it."
  10481. (unless parent-target
  10482. (error "Cannot find parent for new node"))
  10483. (let ((file (nth 1 parent-target))
  10484. (pos (nth 3 parent-target))
  10485. level)
  10486. (with-current-buffer (or (find-buffer-visiting file)
  10487. (find-file-noselect file))
  10488. (org-with-wide-buffer
  10489. (if pos
  10490. (goto-char pos)
  10491. (goto-char (point-max))
  10492. (unless (bolp) (newline)))
  10493. (when (looking-at org-outline-regexp)
  10494. (setq level (funcall outline-level))
  10495. (org-end-of-subtree t t))
  10496. (org-back-over-empty-lines)
  10497. (insert "\n" (make-string
  10498. (if pos (org-get-valid-level level 1) 1) ?*)
  10499. " " child "\n")
  10500. (beginning-of-line 0)
  10501. (list (concat (car parent-target) "/" child) file "" (point))))))
  10502. (defun org-olpath-completing-read (prompt collection &rest args)
  10503. "Read an outline path like a file name."
  10504. (let ((thetable collection))
  10505. (apply #'completing-read
  10506. prompt
  10507. (lambda (string predicate &optional flag)
  10508. (cond
  10509. ((eq flag nil) (try-completion string thetable))
  10510. ((eq flag t)
  10511. (let ((l (length string)))
  10512. (mapcar (lambda (x)
  10513. (let ((r (substring x l))
  10514. (f (if (string-match " ([^)]*)$" x)
  10515. (match-string 0 x)
  10516. "")))
  10517. (if (string-match "/" r)
  10518. (concat string (substring r 0 (match-end 0)) f)
  10519. x)))
  10520. (all-completions string thetable predicate))))
  10521. ;; Exact match?
  10522. ((eq flag 'lambda) (assoc string thetable))))
  10523. args)))
  10524. ;;;; Dynamic blocks
  10525. (defun org-find-dblock (name)
  10526. "Find the first dynamic block with name NAME in the buffer.
  10527. If not found, stay at current position and return nil."
  10528. (let ((case-fold-search t) pos)
  10529. (save-excursion
  10530. (goto-char (point-min))
  10531. (setq pos (and (re-search-forward
  10532. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10533. (match-beginning 0))))
  10534. (when pos (goto-char pos))
  10535. pos))
  10536. (defun org-create-dblock (plist)
  10537. "Create a dynamic block section, with parameters taken from PLIST.
  10538. PLIST must contain a :name entry which is used as the name of the block."
  10539. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10540. (end-of-line 1)
  10541. (newline))
  10542. (let ((col (current-column))
  10543. (name (plist-get plist :name)))
  10544. (insert "#+BEGIN: " name)
  10545. (while plist
  10546. (if (eq (car plist) :name)
  10547. (setq plist (cddr plist))
  10548. (insert " " (prin1-to-string (pop plist)))))
  10549. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10550. (beginning-of-line -2)))
  10551. (defun org-prepare-dblock ()
  10552. "Prepare dynamic block for refresh.
  10553. This empties the block, puts the cursor at the insert position and returns
  10554. the property list including an extra property :name with the block name."
  10555. (unless (looking-at org-dblock-start-re)
  10556. (user-error "Not at a dynamic block"))
  10557. (let* ((begdel (1+ (match-end 0)))
  10558. (name (org-no-properties (match-string 1)))
  10559. (params (append (list :name name)
  10560. (read (concat "(" (match-string 3) ")")))))
  10561. (save-excursion
  10562. (beginning-of-line 1)
  10563. (skip-chars-forward " \t")
  10564. (setq params (plist-put params :indentation-column (current-column))))
  10565. (unless (re-search-forward org-dblock-end-re nil t)
  10566. (error "Dynamic block not terminated"))
  10567. (setq params
  10568. (append params
  10569. (list :content (buffer-substring
  10570. begdel (match-beginning 0)))))
  10571. (delete-region begdel (match-beginning 0))
  10572. (goto-char begdel)
  10573. (open-line 1)
  10574. params))
  10575. (defun org-map-dblocks (&optional command)
  10576. "Apply COMMAND to all dynamic blocks in the current buffer.
  10577. If COMMAND is not given, use `org-update-dblock'."
  10578. (let ((cmd (or command 'org-update-dblock)))
  10579. (save-excursion
  10580. (goto-char (point-min))
  10581. (while (re-search-forward org-dblock-start-re nil t)
  10582. (goto-char (match-beginning 0))
  10583. (save-excursion
  10584. (condition-case nil
  10585. (funcall cmd)
  10586. (error (message "Error during update of dynamic block"))))
  10587. (unless (re-search-forward org-dblock-end-re nil t)
  10588. (error "Dynamic block not terminated"))))))
  10589. (defun org-dblock-update (&optional arg)
  10590. "User command for updating dynamic blocks.
  10591. Update the dynamic block at point. With prefix ARG, update all dynamic
  10592. blocks in the buffer."
  10593. (interactive "P")
  10594. (if arg
  10595. (org-update-all-dblocks)
  10596. (or (looking-at org-dblock-start-re)
  10597. (org-beginning-of-dblock))
  10598. (org-update-dblock)))
  10599. (defun org-update-dblock ()
  10600. "Update the dynamic block at point.
  10601. This means to empty the block, parse for parameters and then call
  10602. the correct writing function."
  10603. (interactive)
  10604. (save-excursion
  10605. (let* ((win (selected-window))
  10606. (pos (point))
  10607. (line (org-current-line))
  10608. (params (org-prepare-dblock))
  10609. (name (plist-get params :name))
  10610. (indent (plist-get params :indentation-column))
  10611. (cmd (intern (concat "org-dblock-write:" name))))
  10612. (message "Updating dynamic block `%s' at line %d..." name line)
  10613. (funcall cmd params)
  10614. (message "Updating dynamic block `%s' at line %d...done" name line)
  10615. (goto-char pos)
  10616. (when (and indent (> indent 0))
  10617. (setq indent (make-string indent ?\ ))
  10618. (save-excursion
  10619. (select-window win)
  10620. (org-beginning-of-dblock)
  10621. (forward-line 1)
  10622. (while (not (looking-at org-dblock-end-re))
  10623. (insert indent)
  10624. (beginning-of-line 2))
  10625. (when (looking-at org-dblock-end-re)
  10626. (and (looking-at "[ \t]+")
  10627. (replace-match ""))
  10628. (insert indent)))))))
  10629. (defun org-beginning-of-dblock ()
  10630. "Find the beginning of the dynamic block at point.
  10631. Error if there is no such block at point."
  10632. (let ((pos (point))
  10633. beg)
  10634. (end-of-line 1)
  10635. (if (and (re-search-backward org-dblock-start-re nil t)
  10636. (setq beg (match-beginning 0))
  10637. (re-search-forward org-dblock-end-re nil t)
  10638. (> (match-end 0) pos))
  10639. (goto-char beg)
  10640. (goto-char pos)
  10641. (error "Not in a dynamic block"))))
  10642. (defun org-update-all-dblocks ()
  10643. "Update all dynamic blocks in the buffer.
  10644. This function can be used in a hook."
  10645. (interactive)
  10646. (when (derived-mode-p 'org-mode)
  10647. (org-map-dblocks 'org-update-dblock)))
  10648. ;;;; Completion
  10649. (declare-function org-export-backend-options "ox" (cl-x) t)
  10650. (defun org-get-export-keywords ()
  10651. "Return a list of all currently understood export keywords.
  10652. Export keywords include options, block names, attributes and
  10653. keywords relative to each registered export back-end."
  10654. (let (keywords)
  10655. (dolist (backend
  10656. (bound-and-true-p org-export-registered-backends)
  10657. (delq nil keywords))
  10658. ;; Back-end name (for keywords, like #+LATEX:)
  10659. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10660. (dolist (option-entry (org-export-backend-options backend))
  10661. ;; Back-end options.
  10662. (push (nth 1 option-entry) keywords)))))
  10663. (defconst org-options-keywords
  10664. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10665. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10666. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10667. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10668. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10669. (defcustom org-structure-template-alist
  10670. '((?a . "export ascii")
  10671. (?c . "center")
  10672. (?C . "comment")
  10673. (?e . "example")
  10674. (?E . "export")
  10675. (?h . "export html")
  10676. (?l . "export latex")
  10677. (?q . "quote")
  10678. (?s . "src")
  10679. (?v . "verse"))
  10680. "Structure completion elements.
  10681. This is an alist of characters and values. When
  10682. `org-insert-structure-template' is called, an additional key is
  10683. read. The key is first looked up in this alist, and the
  10684. corresponding structure is inserted, with \"#+BEGIN_\" and
  10685. \"#+END_\" added automatically."
  10686. :group 'org-completion
  10687. :type '(repeat
  10688. (cons (character :tag "Key")
  10689. (string :tag "Template")))
  10690. :package-version '(Org . "9.2"))
  10691. (defun org-insert-structure-template (type)
  10692. "Insert a block structure of the type #+begin_foo/#+end_foo.
  10693. First read a character, which can be one of the keys in
  10694. `org-structure-template-alist'. When it is <TAB>, prompt the
  10695. user for a string to use. With an active region, wrap the region
  10696. in the block. Otherwise, insert an empty block."
  10697. (interactive
  10698. (list
  10699. (let* ((key (read-key "Key: "))
  10700. (struct-string
  10701. (or (cdr (assq key org-structure-template-alist))
  10702. (and (= key ?\t)
  10703. (read-string "Structure type: "))
  10704. (user-error "`%c' has no structure definition" key))))
  10705. struct-string)))
  10706. (let* ((region? (use-region-p))
  10707. (s (if region? (region-beginning) (point)))
  10708. (e (copy-marker (if region? (region-end) (point)) t))
  10709. column)
  10710. (when (string-match-p
  10711. (concat "\\`" (regexp-opt '("example" "export" "src")))
  10712. type)
  10713. (org-escape-code-in-region s e))
  10714. (goto-char s)
  10715. (setq column (current-indentation))
  10716. (beginning-of-line)
  10717. (indent-to column)
  10718. (insert (format "#+begin_%s\n" type))
  10719. (goto-char e)
  10720. (if (bolp)
  10721. (progn
  10722. (skip-chars-backward " \n\t")
  10723. (forward-line))
  10724. (end-of-line)
  10725. (insert "\n"))
  10726. (indent-to column)
  10727. (insert (format "#+end_%s\n"
  10728. (car (split-string type))))
  10729. (when (or (not region?)
  10730. (string-match-p "src\\|\\`export\\'" type))
  10731. (goto-char s)
  10732. (end-of-line))
  10733. (set-marker e nil)))
  10734. ;;;; TODO, DEADLINE, Comments
  10735. (defun org-toggle-comment ()
  10736. "Change the COMMENT state of an entry."
  10737. (interactive)
  10738. (save-excursion
  10739. (org-back-to-heading)
  10740. (let ((case-fold-search nil))
  10741. (looking-at org-complex-heading-regexp))
  10742. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  10743. (skip-chars-forward " \t")
  10744. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  10745. (if (org-in-commented-heading-p t)
  10746. (delete-region (point)
  10747. (progn (search-forward " " (line-end-position) 'move)
  10748. (skip-chars-forward " \t")
  10749. (point)))
  10750. (insert org-comment-string)
  10751. (unless (eolp) (insert " ")))))
  10752. (defvar org-last-todo-state-is-todo nil
  10753. "This is non-nil when the last TODO state change led to a TODO state.
  10754. If the last change removed the TODO tag or switched to DONE, then
  10755. this is nil.")
  10756. (defvar org-setting-tags nil) ; dynamically skipped
  10757. (defvar org-todo-setup-filter-hook nil
  10758. "Hook for functions that pre-filter todo specs.
  10759. Each function takes a todo spec and returns either nil or the spec
  10760. transformed into canonical form." )
  10761. (defvar org-todo-get-default-hook nil
  10762. "Hook for functions that get a default item for todo.
  10763. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  10764. nil or a string to be used for the todo mark." )
  10765. (defvar org-agenda-headline-snapshot-before-repeat)
  10766. (defun org-current-effective-time ()
  10767. "Return current time adjusted for `org-extend-today-until' variable."
  10768. (let* ((ct (org-current-time))
  10769. (dct (decode-time ct))
  10770. (ct1
  10771. (cond
  10772. (org-use-last-clock-out-time-as-effective-time
  10773. (or (org-clock-get-last-clock-out-time) ct))
  10774. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  10775. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  10776. (t ct))))
  10777. ct1))
  10778. (defun org-todo-yesterday (&optional arg)
  10779. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  10780. (interactive "P")
  10781. (if (eq major-mode 'org-agenda-mode)
  10782. (apply 'org-agenda-todo-yesterday arg)
  10783. (let* ((org-use-effective-time t)
  10784. (hour (nth 2 (decode-time (org-current-time))))
  10785. (org-extend-today-until (1+ hour)))
  10786. (org-todo arg))))
  10787. (defvar org-block-entry-blocking ""
  10788. "First entry preventing the TODO state change.")
  10789. (defun org-cancel-repeater ()
  10790. "Cancel a repeater by setting its numeric value to zero."
  10791. (interactive)
  10792. (save-excursion
  10793. (org-back-to-heading t)
  10794. (let ((bound1 (point))
  10795. (bound0 (save-excursion (outline-next-heading) (point))))
  10796. (when (and (re-search-forward
  10797. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  10798. org-deadline-time-regexp "\\)\\|\\("
  10799. org-ts-regexp "\\)")
  10800. bound0 t)
  10801. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  10802. bound1 t))
  10803. (replace-match "0" t nil nil 1)))))
  10804. (defvar org-state)
  10805. (defvar org-blocked-by-checkboxes)
  10806. (defun org-todo (&optional arg)
  10807. "Change the TODO state of an item.
  10808. The state of an item is given by a keyword at the start of the heading,
  10809. like
  10810. *** TODO Write paper
  10811. *** DONE Call mom
  10812. The different keywords are specified in the variable `org-todo-keywords'.
  10813. By default the available states are \"TODO\" and \"DONE\". So, for this
  10814. example: when the item starts with TODO, it is changed to DONE.
  10815. When it starts with DONE, the DONE is removed. And when neither TODO nor
  10816. DONE are present, add TODO at the beginning of the heading.
  10817. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  10818. state.
  10819. With numeric prefix ARG, switch to that state.
  10820. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  10821. next set of TODO \
  10822. keywords (nextset).
  10823. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  10824. prefix, circumvent any state blocking.
  10825. With a numeric prefix arg of 0, inhibit note taking for the change.
  10826. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  10827. When called through ELisp, arg is also interpreted in the following way:
  10828. `none' -> empty state
  10829. \"\" -> switch to empty state
  10830. `done' -> switch to DONE
  10831. `nextset' -> switch to the next set of keywords
  10832. `previousset' -> switch to the previous set of keywords
  10833. \"WAITING\" -> switch to the specified keyword, but only if it
  10834. really is a member of `org-todo-keywords'."
  10835. (interactive "P")
  10836. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10837. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10838. 'region-start-level 'region))
  10839. org-loop-over-headlines-in-active-region)
  10840. (org-map-entries
  10841. `(org-todo ,arg)
  10842. org-loop-over-headlines-in-active-region
  10843. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  10844. (when (equal arg '(16)) (setq arg 'nextset))
  10845. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  10846. (let ((org-blocker-hook org-blocker-hook)
  10847. commentp
  10848. case-fold-search)
  10849. (when (equal arg '(64))
  10850. (setq arg nil org-blocker-hook nil))
  10851. (when (and org-blocker-hook
  10852. (or org-inhibit-blocking
  10853. (org-entry-get nil "NOBLOCKING")))
  10854. (setq org-blocker-hook nil))
  10855. (save-excursion
  10856. (catch 'exit
  10857. (org-back-to-heading t)
  10858. (when (org-in-commented-heading-p t)
  10859. (org-toggle-comment)
  10860. (setq commentp t))
  10861. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  10862. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  10863. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  10864. (let* ((match-data (match-data))
  10865. (startpos (point-at-bol))
  10866. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  10867. (org-log-done org-log-done)
  10868. (org-log-repeat org-log-repeat)
  10869. (org-todo-log-states org-todo-log-states)
  10870. (org-inhibit-logging
  10871. (if (equal arg 0)
  10872. (progn (setq arg nil) 'note) org-inhibit-logging))
  10873. (this (match-string 1))
  10874. (hl-pos (match-beginning 0))
  10875. (head (org-get-todo-sequence-head this))
  10876. (ass (assoc head org-todo-kwd-alist))
  10877. (interpret (nth 1 ass))
  10878. (done-word (nth 3 ass))
  10879. (final-done-word (nth 4 ass))
  10880. (org-last-state (or this ""))
  10881. (completion-ignore-case t)
  10882. (member (member this org-todo-keywords-1))
  10883. (tail (cdr member))
  10884. (org-state (cond
  10885. ((and org-todo-key-trigger
  10886. (or (and (equal arg '(4))
  10887. (eq org-use-fast-todo-selection 'prefix))
  10888. (and (not arg) org-use-fast-todo-selection
  10889. (not (eq org-use-fast-todo-selection
  10890. 'prefix)))))
  10891. ;; Use fast selection.
  10892. (org-fast-todo-selection))
  10893. ((and (equal arg '(4))
  10894. (or (not org-use-fast-todo-selection)
  10895. (not org-todo-key-trigger)))
  10896. ;; Read a state with completion.
  10897. (completing-read
  10898. "State: " (mapcar #'list org-todo-keywords-1)
  10899. nil t))
  10900. ((eq arg 'right)
  10901. (if this
  10902. (if tail (car tail) nil)
  10903. (car org-todo-keywords-1)))
  10904. ((eq arg 'left)
  10905. (unless (equal member org-todo-keywords-1)
  10906. (if this
  10907. (nth (- (length org-todo-keywords-1)
  10908. (length tail) 2)
  10909. org-todo-keywords-1)
  10910. (org-last org-todo-keywords-1))))
  10911. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  10912. (setq arg nil))) ;hack to fall back to cycling
  10913. (arg
  10914. ;; User or caller requests a specific state.
  10915. (cond
  10916. ((equal arg "") nil)
  10917. ((eq arg 'none) nil)
  10918. ((eq arg 'done) (or done-word (car org-done-keywords)))
  10919. ((eq arg 'nextset)
  10920. (or (car (cdr (member head org-todo-heads)))
  10921. (car org-todo-heads)))
  10922. ((eq arg 'previousset)
  10923. (let ((org-todo-heads (reverse org-todo-heads)))
  10924. (or (car (cdr (member head org-todo-heads)))
  10925. (car org-todo-heads))))
  10926. ((car (member arg org-todo-keywords-1)))
  10927. ((stringp arg)
  10928. (user-error "State `%s' not valid in this file" arg))
  10929. ((nth (1- (prefix-numeric-value arg))
  10930. org-todo-keywords-1))))
  10931. ((null member) (or head (car org-todo-keywords-1)))
  10932. ((equal this final-done-word) nil) ;-> make empty
  10933. ((null tail) nil) ;-> first entry
  10934. ((memq interpret '(type priority))
  10935. (if (eq this-command last-command)
  10936. (car tail)
  10937. (if (> (length tail) 0)
  10938. (or done-word (car org-done-keywords))
  10939. nil)))
  10940. (t
  10941. (car tail))))
  10942. (org-state (or
  10943. (run-hook-with-args-until-success
  10944. 'org-todo-get-default-hook org-state org-last-state)
  10945. org-state))
  10946. (next (if org-state (concat " " org-state " ") " "))
  10947. (change-plist (list :type 'todo-state-change :from this :to org-state
  10948. :position startpos))
  10949. dolog now-done-p)
  10950. (when org-blocker-hook
  10951. (let (org-blocked-by-checkboxes block-reason)
  10952. (setq org-last-todo-state-is-todo
  10953. (not (member this org-done-keywords)))
  10954. (unless (save-excursion
  10955. (save-match-data
  10956. (org-with-wide-buffer
  10957. (run-hook-with-args-until-failure
  10958. 'org-blocker-hook change-plist))))
  10959. (setq block-reason (if org-blocked-by-checkboxes
  10960. "contained checkboxes"
  10961. (format "\"%s\"" org-block-entry-blocking)))
  10962. (if (called-interactively-p 'interactive)
  10963. (user-error "TODO state change from %s to %s blocked (by %s)"
  10964. this org-state block-reason)
  10965. ;; Fail silently.
  10966. (message "TODO state change from %s to %s blocked (by %s)"
  10967. this org-state block-reason)
  10968. (throw 'exit nil)))))
  10969. (store-match-data match-data)
  10970. (replace-match next t t)
  10971. (cond ((equal this org-state)
  10972. (message "TODO state was already %s" (org-trim next)))
  10973. ((not (pos-visible-in-window-p hl-pos))
  10974. (message "TODO state changed to %s" (org-trim next))))
  10975. (unless head
  10976. (setq head (org-get-todo-sequence-head org-state)
  10977. ass (assoc head org-todo-kwd-alist)
  10978. interpret (nth 1 ass)
  10979. done-word (nth 3 ass)
  10980. final-done-word (nth 4 ass)))
  10981. (when (memq arg '(nextset previousset))
  10982. (message "Keyword-Set %d/%d: %s"
  10983. (- (length org-todo-sets) -1
  10984. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  10985. (length org-todo-sets)
  10986. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  10987. (setq org-last-todo-state-is-todo
  10988. (not (member org-state org-done-keywords)))
  10989. (setq now-done-p (and (member org-state org-done-keywords)
  10990. (not (member this org-done-keywords))))
  10991. (and logging (org-local-logging logging))
  10992. (when (and (or org-todo-log-states org-log-done)
  10993. (not (eq org-inhibit-logging t))
  10994. (not (memq arg '(nextset previousset))))
  10995. ;; We need to look at recording a time and note.
  10996. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  10997. (nth 2 (assoc this org-todo-log-states))))
  10998. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  10999. (setq dolog 'time))
  11000. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11001. (and org-state
  11002. (member org-state org-not-done-keywords)
  11003. (not (member this org-not-done-keywords))))
  11004. ;; This is now a todo state and was not one before
  11005. ;; If there was a CLOSED time stamp, get rid of it.
  11006. (org-add-planning-info nil nil 'closed))
  11007. (when (and now-done-p org-log-done)
  11008. ;; It is now done, and it was not done before.
  11009. (org-add-planning-info 'closed (org-current-effective-time))
  11010. (when (and (not dolog) (eq 'note org-log-done))
  11011. (org-add-log-setup 'done org-state this 'note)))
  11012. (when (and org-state dolog)
  11013. ;; This is a non-nil state, and we need to log it.
  11014. (org-add-log-setup 'state org-state this dolog)))
  11015. ;; Fixup tag positioning.
  11016. (org-todo-trigger-tag-changes org-state)
  11017. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11018. (when org-provide-todo-statistics
  11019. (org-update-parent-todo-statistics))
  11020. (run-hooks 'org-after-todo-state-change-hook)
  11021. (when (and arg (not (member org-state org-done-keywords)))
  11022. (setq head (org-get-todo-sequence-head org-state)))
  11023. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11024. ;; Do we need to trigger a repeat?
  11025. (when now-done-p
  11026. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11027. ;; This is for the agenda, take a snapshot of the headline.
  11028. (save-match-data
  11029. (setq org-agenda-headline-snapshot-before-repeat
  11030. (org-get-heading))))
  11031. (org-auto-repeat-maybe org-state))
  11032. ;; Fixup cursor location if close to the keyword.
  11033. (when (and (outline-on-heading-p)
  11034. (not (bolp))
  11035. (save-excursion (beginning-of-line 1)
  11036. (looking-at org-todo-line-regexp))
  11037. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11038. (goto-char (or (match-end 2) (match-end 1)))
  11039. (and (looking-at " ") (just-one-space)))
  11040. (when org-trigger-hook
  11041. (save-excursion
  11042. (run-hook-with-args 'org-trigger-hook change-plist)))
  11043. (when commentp (org-toggle-comment))))))))
  11044. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11045. "Block turning an entry into a TODO, using the hierarchy.
  11046. This checks whether the current task should be blocked from state
  11047. changes. Such blocking occurs when:
  11048. 1. The task has children which are not all in a completed state.
  11049. 2. A task has a parent with the property :ORDERED:, and there
  11050. are siblings prior to the current task with incomplete
  11051. status.
  11052. 3. The parent of the task is blocked because it has siblings that should
  11053. be done first, or is child of a block grandparent TODO entry."
  11054. (if (not org-enforce-todo-dependencies)
  11055. t ; if locally turned off don't block
  11056. (catch 'dont-block
  11057. ;; If this is not a todo state change, or if this entry is already DONE,
  11058. ;; do not block
  11059. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11060. (member (plist-get change-plist :from)
  11061. (cons 'done org-done-keywords))
  11062. (member (plist-get change-plist :to)
  11063. (cons 'todo org-not-done-keywords))
  11064. (not (plist-get change-plist :to)))
  11065. (throw 'dont-block t))
  11066. ;; If this task has children, and any are undone, it's blocked
  11067. (save-excursion
  11068. (org-back-to-heading t)
  11069. (let ((this-level (funcall outline-level)))
  11070. (outline-next-heading)
  11071. (let ((child-level (funcall outline-level)))
  11072. (while (and (not (eobp))
  11073. (> child-level this-level))
  11074. ;; this todo has children, check whether they are all
  11075. ;; completed
  11076. (when (and (not (org-entry-is-done-p))
  11077. (org-entry-is-todo-p))
  11078. (setq org-block-entry-blocking (org-get-heading))
  11079. (throw 'dont-block nil))
  11080. (outline-next-heading)
  11081. (setq child-level (funcall outline-level))))))
  11082. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11083. ;; any previous siblings are undone, it's blocked
  11084. (save-excursion
  11085. (org-back-to-heading t)
  11086. (let* ((pos (point))
  11087. (parent-pos (and (org-up-heading-safe) (point)))
  11088. (case-fold-search nil))
  11089. (unless parent-pos (throw 'dont-block t)) ; no parent
  11090. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11091. (forward-line 1)
  11092. (re-search-forward org-not-done-heading-regexp pos t))
  11093. (setq org-block-entry-blocking (match-string 0))
  11094. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11095. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11096. (while t
  11097. (goto-char parent-pos)
  11098. (unless (looking-at org-not-done-heading-regexp)
  11099. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11100. (setq pos (point))
  11101. (setq parent-pos (and (org-up-heading-safe) (point)))
  11102. (unless parent-pos (throw 'dont-block t)) ; no parent
  11103. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11104. (forward-line 1)
  11105. (re-search-forward org-not-done-heading-regexp pos t)
  11106. (setq org-block-entry-blocking (org-get-heading)))
  11107. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11108. (defcustom org-track-ordered-property-with-tag nil
  11109. "Should the ORDERED property also be shown as a tag?
  11110. The ORDERED property decides if an entry should require subtasks to be
  11111. completed in sequence. Since a property is not very visible, setting
  11112. this option means that toggling the ORDERED property with the command
  11113. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11114. not relevant for the behavior, but it makes things more visible.
  11115. Note that toggling the tag with tags commands will not change the property
  11116. and therefore not influence behavior!
  11117. This can be t, meaning the tag ORDERED should be used, It can also be a
  11118. string to select a different tag for this task."
  11119. :group 'org-todo
  11120. :type '(choice
  11121. (const :tag "No tracking" nil)
  11122. (const :tag "Track with ORDERED tag" t)
  11123. (string :tag "Use other tag")))
  11124. (defun org-toggle-ordered-property ()
  11125. "Toggle the ORDERED property of the current entry.
  11126. For better visibility, you can track the value of this property with a tag.
  11127. See variable `org-track-ordered-property-with-tag'."
  11128. (interactive)
  11129. (let* ((t1 org-track-ordered-property-with-tag)
  11130. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11131. (save-excursion
  11132. (org-back-to-heading)
  11133. (if (org-entry-get nil "ORDERED")
  11134. (progn
  11135. (org-delete-property "ORDERED")
  11136. (and tag (org-toggle-tag tag 'off))
  11137. (message "Subtasks can be completed in arbitrary order"))
  11138. (org-entry-put nil "ORDERED" "t")
  11139. (and tag (org-toggle-tag tag 'on))
  11140. (message "Subtasks must be completed in sequence")))))
  11141. (defun org-block-todo-from-checkboxes (change-plist)
  11142. "Block turning an entry into a TODO, using checkboxes.
  11143. This checks whether the current task should be blocked from state
  11144. changes because there are unchecked boxes in this entry."
  11145. (if (not org-enforce-todo-checkbox-dependencies)
  11146. t ; if locally turned off don't block
  11147. (catch 'dont-block
  11148. ;; If this is not a todo state change, or if this entry is already DONE,
  11149. ;; do not block
  11150. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11151. (member (plist-get change-plist :from)
  11152. (cons 'done org-done-keywords))
  11153. (member (plist-get change-plist :to)
  11154. (cons 'todo org-not-done-keywords))
  11155. (not (plist-get change-plist :to)))
  11156. (throw 'dont-block t))
  11157. ;; If this task has checkboxes that are not checked, it's blocked
  11158. (save-excursion
  11159. (org-back-to-heading t)
  11160. (let ((beg (point)) end)
  11161. (outline-next-heading)
  11162. (setq end (point))
  11163. (goto-char beg)
  11164. (when (org-list-search-forward
  11165. (concat (org-item-beginning-re)
  11166. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11167. "\\[[- ]\\]")
  11168. end t)
  11169. (when (boundp 'org-blocked-by-checkboxes)
  11170. (setq org-blocked-by-checkboxes t))
  11171. (throw 'dont-block nil))))
  11172. t))) ; do not block
  11173. (defun org-entry-blocked-p ()
  11174. "Non-nil if entry at point is blocked."
  11175. (and (not (org-entry-get nil "NOBLOCKING"))
  11176. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11177. (not (run-hook-with-args-until-failure
  11178. 'org-blocker-hook
  11179. (list :type 'todo-state-change
  11180. :position (point)
  11181. :from 'todo
  11182. :to 'done)))))
  11183. (defun org-update-statistics-cookies (all)
  11184. "Update the statistics cookie, either from TODO or from checkboxes.
  11185. This should be called with the cursor in a line with a statistics
  11186. cookie. When called with a \\[universal-argument] prefix, update
  11187. all statistics cookies in the buffer."
  11188. (interactive "P")
  11189. (if all
  11190. (progn
  11191. (org-update-checkbox-count 'all)
  11192. (org-map-entries 'org-update-parent-todo-statistics))
  11193. (if (not (org-at-heading-p))
  11194. (org-update-checkbox-count)
  11195. (let ((pos (point-marker))
  11196. end l1 l2)
  11197. (ignore-errors (org-back-to-heading t))
  11198. (if (not (org-at-heading-p))
  11199. (org-update-checkbox-count)
  11200. (setq l1 (org-outline-level))
  11201. (setq end (save-excursion
  11202. (outline-next-heading)
  11203. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11204. (point)))
  11205. (if (and (save-excursion
  11206. (re-search-forward
  11207. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11208. (not (save-excursion (re-search-forward
  11209. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11210. (org-update-checkbox-count)
  11211. (if (and l2 (> l2 l1))
  11212. (progn
  11213. (goto-char end)
  11214. (org-update-parent-todo-statistics))
  11215. (goto-char pos)
  11216. (beginning-of-line 1)
  11217. (while (re-search-forward
  11218. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11219. (point-at-eol) t)
  11220. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11221. (goto-char pos)
  11222. (move-marker pos nil)))))
  11223. (defvar org-entry-property-inherited-from) ;; defined below
  11224. (defun org-update-parent-todo-statistics ()
  11225. "Update any statistics cookie in the parent of the current headline.
  11226. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11227. the entire subtree and this will travel up the hierarchy and update
  11228. statistics everywhere."
  11229. (let* ((prop (save-excursion (org-up-heading-safe)
  11230. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11231. (recursive (or (not org-hierarchical-todo-statistics)
  11232. (and prop (string-match "\\<recursive\\>" prop))))
  11233. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11234. 0))
  11235. (first t)
  11236. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11237. level ltoggle l1 new ndel
  11238. (cnt-all 0) (cnt-done 0) is-percent kwd
  11239. checkbox-beg cookie-present)
  11240. (catch 'exit
  11241. (save-excursion
  11242. (beginning-of-line 1)
  11243. (setq ltoggle (funcall outline-level))
  11244. ;; Three situations are to consider:
  11245. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11246. ;; to the top-level ancestor on the headline;
  11247. ;; 2. If parent has "recursive" property, repeat up to the
  11248. ;; headline setting that property, taking inheritance into
  11249. ;; account;
  11250. ;; 3. Else, move up to direct parent and proceed only once.
  11251. (while (and (setq level (org-up-heading-safe))
  11252. (or recursive first)
  11253. (>= (point) lim))
  11254. (setq first nil cookie-present nil)
  11255. (unless (and level
  11256. (not (string-match
  11257. "\\<checkbox\\>"
  11258. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11259. "")))))
  11260. (throw 'exit nil))
  11261. (while (re-search-forward box-re (point-at-eol) t)
  11262. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11263. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11264. (save-match-data
  11265. (unless (outline-next-heading) (throw 'exit nil))
  11266. (while (and (looking-at org-complex-heading-regexp)
  11267. (> (setq l1 (length (match-string 1))) level))
  11268. (setq kwd (and (or recursive (= l1 ltoggle))
  11269. (match-string 2)))
  11270. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11271. (and (eq org-provide-todo-statistics t)
  11272. (or (member kwd org-done-keywords)))
  11273. (and (listp org-provide-todo-statistics)
  11274. (stringp (car org-provide-todo-statistics))
  11275. (or (member kwd org-provide-todo-statistics)
  11276. (member kwd org-done-keywords)))
  11277. (and (listp org-provide-todo-statistics)
  11278. (listp (car org-provide-todo-statistics))
  11279. (or (member kwd (car org-provide-todo-statistics))
  11280. (and (member kwd org-done-keywords)
  11281. (member kwd (cadr org-provide-todo-statistics))))))
  11282. (setq cnt-all (1+ cnt-all))
  11283. (and (eq org-provide-todo-statistics t)
  11284. kwd
  11285. (setq cnt-all (1+ cnt-all))))
  11286. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11287. (member kwd org-done-keywords))
  11288. (and (listp org-provide-todo-statistics)
  11289. (listp (car org-provide-todo-statistics))
  11290. (member kwd org-done-keywords)
  11291. (member kwd (cadr org-provide-todo-statistics)))
  11292. (and (listp org-provide-todo-statistics)
  11293. (stringp (car org-provide-todo-statistics))
  11294. (member kwd org-done-keywords)))
  11295. (setq cnt-done (1+ cnt-done)))
  11296. (outline-next-heading)))
  11297. (setq new
  11298. (if is-percent
  11299. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11300. (max 1 cnt-all)))
  11301. (format "[%d/%d]" cnt-done cnt-all))
  11302. ndel (- (match-end 0) checkbox-beg))
  11303. (goto-char checkbox-beg)
  11304. (insert new)
  11305. (delete-region (point) (+ (point) ndel))
  11306. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11307. (when cookie-present
  11308. (run-hook-with-args 'org-after-todo-statistics-hook
  11309. cnt-done (- cnt-all cnt-done))))))
  11310. (run-hooks 'org-todo-statistics-hook)))
  11311. (defvar org-after-todo-statistics-hook nil
  11312. "Hook that is called after a TODO statistics cookie has been updated.
  11313. Each function is called with two arguments: the number of not-done entries
  11314. and the number of done entries.
  11315. For example, the following function, when added to this hook, will switch
  11316. an entry to DONE when all children are done, and back to TODO when new
  11317. entries are set to a TODO status. Note that this hook is only called
  11318. when there is a statistics cookie in the headline!
  11319. (defun org-summary-todo (n-done n-not-done)
  11320. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11321. (let (org-log-done org-log-states) ; turn off logging
  11322. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11323. ")
  11324. (defvar org-todo-statistics-hook nil
  11325. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11326. This hook runs even if there is no statistics cookie present, in which case
  11327. `org-after-todo-statistics-hook' would not run.")
  11328. (defun org-todo-trigger-tag-changes (state)
  11329. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11330. (let ((l org-todo-state-tags-triggers)
  11331. changes)
  11332. (when (or (not state) (equal state ""))
  11333. (setq changes (append changes (cdr (assoc "" l)))))
  11334. (when (and (stringp state) (> (length state) 0))
  11335. (setq changes (append changes (cdr (assoc state l)))))
  11336. (when (member state org-not-done-keywords)
  11337. (setq changes (append changes (cdr (assq 'todo l)))))
  11338. (when (member state org-done-keywords)
  11339. (setq changes (append changes (cdr (assq 'done l)))))
  11340. (dolist (c changes)
  11341. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11342. (defun org-local-logging (value)
  11343. "Get logging settings from a property VALUE."
  11344. ;; Directly set the variables, they are already local.
  11345. (setq org-log-done nil
  11346. org-log-repeat nil
  11347. org-todo-log-states nil)
  11348. (dolist (w (split-string value))
  11349. (let (a)
  11350. (cond
  11351. ((setq a (assoc w org-startup-options))
  11352. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11353. (set (nth 1 a) (nth 2 a))))
  11354. ((setq a (org-extract-log-state-settings w))
  11355. (and (member (car a) org-todo-keywords-1)
  11356. (push a org-todo-log-states)))))))
  11357. (defun org-get-todo-sequence-head (kwd)
  11358. "Return the head of the TODO sequence to which KWD belongs.
  11359. If KWD is not set, check if there is a text property remembering the
  11360. right sequence."
  11361. (let (p)
  11362. (cond
  11363. ((not kwd)
  11364. (or (get-text-property (point-at-bol) 'org-todo-head)
  11365. (progn
  11366. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11367. nil (point-at-eol)))
  11368. (get-text-property p 'org-todo-head))))
  11369. ((not (member kwd org-todo-keywords-1))
  11370. (car org-todo-keywords-1))
  11371. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11372. (defun org-fast-todo-selection ()
  11373. "Fast TODO keyword selection with single keys.
  11374. Returns the new TODO keyword, or nil if no state change should occur."
  11375. (let* ((fulltable org-todo-key-alist)
  11376. (done-keywords org-done-keywords) ;; needed for the faces.
  11377. (maxlen (apply 'max (mapcar
  11378. (lambda (x)
  11379. (if (stringp (car x)) (string-width (car x)) 0))
  11380. fulltable)))
  11381. (expert nil)
  11382. (fwidth (+ maxlen 3 1 3))
  11383. (ncol (/ (- (window-width) 4) fwidth))
  11384. tg cnt e c tbl
  11385. groups ingroup)
  11386. (save-excursion
  11387. (save-window-excursion
  11388. (if expert
  11389. (set-buffer (get-buffer-create " *Org todo*"))
  11390. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11391. (erase-buffer)
  11392. (setq-local org-done-keywords done-keywords)
  11393. (setq tbl fulltable cnt 0)
  11394. (while (setq e (pop tbl))
  11395. (cond
  11396. ((equal e '(:startgroup))
  11397. (push '() groups) (setq ingroup t)
  11398. (unless (= cnt 0)
  11399. (setq cnt 0)
  11400. (insert "\n"))
  11401. (insert "{ "))
  11402. ((equal e '(:endgroup))
  11403. (setq ingroup nil cnt 0)
  11404. (insert "}\n"))
  11405. ((equal e '(:newline))
  11406. (unless (= cnt 0)
  11407. (setq cnt 0)
  11408. (insert "\n")
  11409. (setq e (car tbl))
  11410. (while (equal (car tbl) '(:newline))
  11411. (insert "\n")
  11412. (setq tbl (cdr tbl)))))
  11413. (t
  11414. (setq tg (car e) c (cdr e))
  11415. (when ingroup (push tg (car groups)))
  11416. (setq tg (org-add-props tg nil 'face
  11417. (org-get-todo-face tg)))
  11418. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11419. (insert "[" c "] " tg (make-string
  11420. (- fwidth 4 (length tg)) ?\ ))
  11421. (when (= (setq cnt (1+ cnt)) ncol)
  11422. (insert "\n")
  11423. (when ingroup (insert " "))
  11424. (setq cnt 0)))))
  11425. (insert "\n")
  11426. (goto-char (point-min))
  11427. (unless expert (org-fit-window-to-buffer))
  11428. (message "[a-z..]:Set [SPC]:clear")
  11429. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11430. (cond
  11431. ((or (= c ?\C-g)
  11432. (and (= c ?q) (not (rassoc c fulltable))))
  11433. (setq quit-flag t))
  11434. ((= c ?\ ) nil)
  11435. ((setq e (rassoc c fulltable) tg (car e))
  11436. tg)
  11437. (t (setq quit-flag t)))))))
  11438. (defun org-entry-is-todo-p ()
  11439. (member (org-get-todo-state) org-not-done-keywords))
  11440. (defun org-entry-is-done-p ()
  11441. (member (org-get-todo-state) org-done-keywords))
  11442. (defun org-get-todo-state ()
  11443. "Return the TODO keyword of the current subtree."
  11444. (save-excursion
  11445. (org-back-to-heading t)
  11446. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11447. (match-end 2)
  11448. (match-string 2))))
  11449. (defun org-at-date-range-p (&optional inactive-ok)
  11450. "Non-nil if point is inside a date range.
  11451. When optional argument INACTIVE-OK is non-nil, also consider
  11452. inactive time ranges.
  11453. When this function returns a non-nil value, match data is set
  11454. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11455. on INACTIVE-OK."
  11456. (interactive)
  11457. (save-excursion
  11458. (catch 'exit
  11459. (let ((pos (point)))
  11460. (skip-chars-backward "^[<\r\n")
  11461. (skip-chars-backward "<[")
  11462. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11463. (>= (match-end 0) pos)
  11464. (throw 'exit t))
  11465. (skip-chars-backward "^<[\r\n")
  11466. (skip-chars-backward "<[")
  11467. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11468. (>= (match-end 0) pos)
  11469. (throw 'exit t)))
  11470. nil)))
  11471. (defun org-get-repeat (&optional timestamp)
  11472. "Check if there is a time-stamp with repeater in this entry.
  11473. Return the repeater, as a string, or nil. Also return nil when
  11474. this function is called before first heading.
  11475. When optional argument TIMESTAMP is a string, extract the
  11476. repeater from there instead."
  11477. (save-match-data
  11478. (cond (timestamp
  11479. (and (string-match org-repeat-re timestamp)
  11480. (match-string-no-properties 1 timestamp)))
  11481. ((org-before-first-heading-p) nil)
  11482. (t
  11483. (save-excursion
  11484. (org-back-to-heading t)
  11485. (let ((end (org-entry-end-position)))
  11486. (catch :repeat
  11487. (while (re-search-forward org-repeat-re end t)
  11488. (when (save-match-data (org-at-timestamp-p 'agenda))
  11489. (throw :repeat (match-string-no-properties 1)))))))))))
  11490. (defvar org-last-changed-timestamp)
  11491. (defvar org-last-inserted-timestamp)
  11492. (defvar org-log-post-message)
  11493. (defvar org-log-note-purpose)
  11494. (defvar org-log-note-how nil)
  11495. (defvar org-log-note-extra)
  11496. (defun org-auto-repeat-maybe (done-word)
  11497. "Check if the current headline contains a repeated time-stamp.
  11498. If yes, set TODO state back to what it was and change the base date
  11499. of repeating deadline/scheduled time stamps to new date.
  11500. This function is run automatically after each state change to a DONE state."
  11501. (let* ((repeat (org-get-repeat))
  11502. (aa (assoc org-last-state org-todo-kwd-alist))
  11503. (interpret (nth 1 aa))
  11504. (head (nth 2 aa))
  11505. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11506. (msg "Entry repeats: ")
  11507. (org-log-done nil)
  11508. (org-todo-log-states nil)
  11509. (end (copy-marker (org-entry-end-position))))
  11510. (unwind-protect
  11511. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11512. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11513. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11514. org-todo-repeat-to-state)))
  11515. (org-todo (cond
  11516. ((and to-state (member to-state org-todo-keywords-1))
  11517. to-state)
  11518. ((eq interpret 'type) org-last-state)
  11519. (head)
  11520. (t 'none))))
  11521. (org-back-to-heading t)
  11522. (org-add-planning-info nil nil 'closed)
  11523. ;; When `org-log-repeat' is non-nil or entry contains
  11524. ;; a clock, set LAST_REPEAT property.
  11525. (when (or org-log-repeat
  11526. (catch :clock
  11527. (save-excursion
  11528. (while (re-search-forward org-clock-line-re end t)
  11529. (when (org-at-clock-log-p) (throw :clock t))))))
  11530. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11531. (org-time-stamp-format t t)
  11532. (current-time))))
  11533. (when org-log-repeat
  11534. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11535. (memq 'org-add-log-note post-command-hook))
  11536. ;; We are already setup for some record.
  11537. (when (eq org-log-repeat 'note)
  11538. ;; Make sure we take a note, not only a time stamp.
  11539. (setq org-log-note-how 'note))
  11540. ;; Set up for taking a record.
  11541. (org-add-log-setup 'state
  11542. (or done-word (car org-done-keywords))
  11543. org-last-state
  11544. org-log-repeat)))
  11545. (let ((planning-re (regexp-opt
  11546. (list org-scheduled-string org-deadline-string))))
  11547. (while (re-search-forward org-ts-regexp end t)
  11548. (let* ((ts (match-string 0))
  11549. (planning? (org-at-planning-p))
  11550. (type (if (not planning?) "Plain:"
  11551. (save-excursion
  11552. (re-search-backward
  11553. planning-re (line-beginning-position) t)
  11554. (match-string 0)))))
  11555. (cond
  11556. ;; Ignore fake time-stamps (e.g., within comments).
  11557. ((not (org-at-timestamp-p 'agenda)))
  11558. ;; Time-stamps without a repeater are usually
  11559. ;; skipped. However, a SCHEDULED time-stamp without
  11560. ;; one is removed, as they are no longer relevant.
  11561. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11562. ts))
  11563. (when (equal type org-scheduled-string)
  11564. (org-remove-timestamp-with-keyword type)))
  11565. (t
  11566. (let ((n (string-to-number (match-string 2 ts)))
  11567. (what (match-string 3 ts)))
  11568. (when (equal what "w") (setq n (* n 7) what "d"))
  11569. (when (and (equal what "h")
  11570. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11571. ts)))
  11572. (user-error
  11573. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11574. has been set"
  11575. n))
  11576. ;; Preparation, see if we need to modify the start
  11577. ;; date for the change.
  11578. (when (match-end 1)
  11579. (let ((time (save-match-data
  11580. (org-time-string-to-time ts))))
  11581. (cond
  11582. ((equal (match-string 1 ts) ".")
  11583. ;; Shift starting date to today
  11584. (org-timestamp-change
  11585. (- (org-today) (time-to-days time))
  11586. 'day))
  11587. ((equal (match-string 1 ts) "+")
  11588. (let ((nshiftmax 10)
  11589. (nshift 0))
  11590. (while (or (= nshift 0)
  11591. (not (time-less-p (current-time) time)))
  11592. (when (= (cl-incf nshift) nshiftmax)
  11593. (or (y-or-n-p
  11594. (format "%d repeater intervals were not \
  11595. enough to shift date past today. Continue? "
  11596. nshift))
  11597. (user-error "Abort")))
  11598. (org-timestamp-change n (cdr (assoc what whata)))
  11599. (org-in-regexp org-ts-regexp3)
  11600. (setq ts (match-string 1))
  11601. (setq time
  11602. (save-match-data
  11603. (org-time-string-to-time ts)))))
  11604. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11605. ;; Rematch, so that we have everything in place
  11606. ;; for the real shift.
  11607. (org-in-regexp org-ts-regexp3)
  11608. (setq ts (match-string 1))
  11609. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11610. ts)))))
  11611. (save-excursion
  11612. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11613. (setq msg
  11614. (concat
  11615. msg type " " org-last-changed-timestamp " "))))))))
  11616. (setq org-log-post-message msg)
  11617. (message "%s" msg))
  11618. (set-marker end nil))))
  11619. (defun org-show-todo-tree (arg)
  11620. "Make a compact tree which shows all headlines marked with TODO.
  11621. The tree will show the lines where the regexp matches, and all higher
  11622. headlines above the match.
  11623. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11624. With a numeric prefix N, construct a sparse tree for the Nth element
  11625. of `org-todo-keywords-1'."
  11626. (interactive "P")
  11627. (let ((case-fold-search nil)
  11628. (kwd-re
  11629. (cond ((null arg) org-not-done-regexp)
  11630. ((equal arg '(4))
  11631. (let ((kwd
  11632. (completing-read "Keyword (or KWD1|KWD2|...): "
  11633. (mapcar #'list org-todo-keywords-1))))
  11634. (concat "\\("
  11635. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11636. "\\)\\>")))
  11637. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11638. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11639. org-todo-keywords-1)))
  11640. (t (user-error "Invalid prefix argument: %s" arg)))))
  11641. (message "%d TODO entries found"
  11642. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11643. (defun org--deadline-or-schedule (arg type time)
  11644. "Insert DEADLINE or SCHEDULE information in current entry.
  11645. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11646. `org-schedule' for information about ARG and TIME arguments."
  11647. (let* ((deadline? (eq type 'deadline))
  11648. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11649. (log (if deadline? org-log-redeadline org-log-reschedule))
  11650. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11651. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11652. ;; Save repeater cookie from either TIME or current scheduled
  11653. ;; time stamp. We are going to insert it back at the end of
  11654. ;; the process.
  11655. (repeater (or (and (org-string-nw-p time)
  11656. ;; We use `org-repeat-re' because we need
  11657. ;; to tell the difference between a real
  11658. ;; repeater and a time delta, e.g. "+2d".
  11659. (string-match org-repeat-re time)
  11660. (match-string 1 time))
  11661. (and (org-string-nw-p old-date)
  11662. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11663. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11664. old-date)
  11665. (match-string 1 old-date)))))
  11666. (pcase arg
  11667. (`(4)
  11668. (when (and old-date log)
  11669. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11670. nil old-date log))
  11671. (org-remove-timestamp-with-keyword keyword)
  11672. (message (if deadline? "Item no longer has a deadline."
  11673. "Item is no longer scheduled.")))
  11674. (`(16)
  11675. (save-excursion
  11676. (org-back-to-heading t)
  11677. (let ((regexp (if deadline? org-deadline-time-regexp
  11678. org-scheduled-time-regexp)))
  11679. (if (not (re-search-forward regexp (line-end-position 2) t))
  11680. (user-error (if deadline? "No deadline information to update"
  11681. "No scheduled information to update"))
  11682. (let* ((rpl0 (match-string 1))
  11683. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  11684. (msg (if deadline? "Warn starting from" "Delay until")))
  11685. (replace-match
  11686. (concat keyword
  11687. " <" rpl
  11688. (format " -%dd"
  11689. (abs (- (time-to-days
  11690. (save-match-data
  11691. (org-read-date
  11692. nil t nil msg old-date-time)))
  11693. (time-to-days old-date-time))))
  11694. ">") t t))))))
  11695. (_
  11696. (org-add-planning-info type time 'closed)
  11697. (when (and old-date
  11698. log
  11699. (not (equal old-date org-last-inserted-timestamp)))
  11700. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  11701. org-last-inserted-timestamp
  11702. old-date
  11703. log))
  11704. (when repeater
  11705. (save-excursion
  11706. (org-back-to-heading t)
  11707. (when (re-search-forward
  11708. (concat keyword " " org-last-inserted-timestamp)
  11709. (line-end-position 2)
  11710. t)
  11711. (goto-char (1- (match-end 0)))
  11712. (insert " " repeater)
  11713. (setq org-last-inserted-timestamp
  11714. (concat (substring org-last-inserted-timestamp 0 -1)
  11715. " " repeater
  11716. (substring org-last-inserted-timestamp -1))))))
  11717. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  11718. org-last-inserted-timestamp)))))
  11719. (defun org-deadline (arg &optional time)
  11720. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  11721. With one universal prefix argument, remove any deadline from the item.
  11722. With two universal prefix arguments, prompt for a warning delay.
  11723. With argument TIME, set the deadline at the corresponding date. TIME
  11724. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11725. (interactive "P")
  11726. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11727. (org-map-entries
  11728. (lambda () (org--deadline-or-schedule arg 'deadline time))
  11729. nil
  11730. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11731. 'region-start-level
  11732. 'region)
  11733. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11734. (org--deadline-or-schedule arg 'deadline time)))
  11735. (defun org-schedule (arg &optional time)
  11736. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  11737. With one universal prefix argument, remove any scheduling date from the item.
  11738. With two universal prefix arguments, prompt for a delay cookie.
  11739. With argument TIME, scheduled at the corresponding date. TIME can
  11740. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11741. (interactive "P")
  11742. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11743. (org-map-entries
  11744. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  11745. nil
  11746. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11747. 'region-start-level
  11748. 'region)
  11749. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11750. (org--deadline-or-schedule arg 'scheduled time)))
  11751. (defun org-get-scheduled-time (pom &optional inherit)
  11752. "Get the scheduled time as a time tuple, of a format suitable
  11753. for calling org-schedule with, or if there is no scheduling,
  11754. returns nil."
  11755. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  11756. (when time
  11757. (apply 'encode-time (org-parse-time-string time)))))
  11758. (defun org-get-deadline-time (pom &optional inherit)
  11759. "Get the deadline as a time tuple, of a format suitable for
  11760. calling org-deadline with, or if there is no scheduling, returns
  11761. nil."
  11762. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  11763. (when time
  11764. (apply 'encode-time (org-parse-time-string time)))))
  11765. (defun org-remove-timestamp-with-keyword (keyword)
  11766. "Remove all time stamps with KEYWORD in the current entry."
  11767. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  11768. beg)
  11769. (save-excursion
  11770. (org-back-to-heading t)
  11771. (setq beg (point))
  11772. (outline-next-heading)
  11773. (while (re-search-backward re beg t)
  11774. (replace-match "")
  11775. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  11776. (equal (char-before) ?\ ))
  11777. (backward-delete-char 1)
  11778. (when (string-match "^[ \t]*$" (buffer-substring
  11779. (point-at-bol) (point-at-eol)))
  11780. (delete-region (point-at-bol)
  11781. (min (point-max) (1+ (point-at-eol))))))))))
  11782. (defvar org-time-was-given) ; dynamically scoped parameter
  11783. (defvar org-end-time-was-given) ; dynamically scoped parameter
  11784. (defun org-at-planning-p ()
  11785. "Non-nil when point is on a planning info line."
  11786. ;; This is as accurate and faster than `org-element-at-point' since
  11787. ;; planning info location is fixed in the section.
  11788. (org-with-wide-buffer
  11789. (beginning-of-line)
  11790. (and (looking-at-p org-planning-line-re)
  11791. (eq (point)
  11792. (ignore-errors
  11793. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  11794. (org-back-to-heading t)
  11795. (org-with-limited-levels (org-back-to-heading t)))
  11796. (line-beginning-position 2))))))
  11797. (defun org-add-planning-info (what &optional time &rest remove)
  11798. "Insert new timestamp with keyword in the planning line.
  11799. WHAT indicates what kind of time stamp to add. It is a symbol
  11800. among `closed', `deadline', `scheduled' and nil. TIME indicates
  11801. the time to use. If none is given, the user is prompted for
  11802. a date. REMOVE indicates what kind of entries to remove. An old
  11803. WHAT entry will also be removed."
  11804. (let (org-time-was-given org-end-time-was-given default-time default-input)
  11805. (catch 'exit
  11806. (when (and (memq what '(scheduled deadline))
  11807. (or (not time)
  11808. (and (stringp time)
  11809. (string-match "^[-+]+[0-9]" time))))
  11810. ;; Try to get a default date/time from existing timestamp
  11811. (save-excursion
  11812. (org-back-to-heading t)
  11813. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  11814. (when (re-search-forward (if (eq what 'scheduled)
  11815. org-scheduled-time-regexp
  11816. org-deadline-time-regexp)
  11817. end t)
  11818. (setq ts (match-string 1)
  11819. default-time (apply 'encode-time (org-parse-time-string ts))
  11820. default-input (and ts (org-get-compact-tod ts)))))))
  11821. (when what
  11822. (setq time
  11823. (if (stringp time)
  11824. ;; This is a string (relative or absolute), set
  11825. ;; proper date.
  11826. (apply #'encode-time
  11827. (org-read-date-analyze
  11828. time default-time (decode-time default-time)))
  11829. ;; If necessary, get the time from the user
  11830. (or time (org-read-date nil 'to-time nil nil
  11831. default-time default-input)))))
  11832. (org-with-wide-buffer
  11833. (org-back-to-heading t)
  11834. (forward-line)
  11835. (unless (bolp) (insert "\n"))
  11836. (cond ((looking-at-p org-planning-line-re)
  11837. ;; Move to current indentation.
  11838. (skip-chars-forward " \t")
  11839. ;; Check if we have to remove something.
  11840. (dolist (type (if what (cons what remove) remove))
  11841. (save-excursion
  11842. (when (re-search-forward
  11843. (cl-case type
  11844. (closed org-closed-time-regexp)
  11845. (deadline org-deadline-time-regexp)
  11846. (scheduled org-scheduled-time-regexp)
  11847. (otherwise
  11848. (error "Invalid planning type: %s" type)))
  11849. (line-end-position) t)
  11850. ;; Delete until next keyword or end of line.
  11851. (delete-region
  11852. (match-beginning 0)
  11853. (if (re-search-forward org-keyword-time-not-clock-regexp
  11854. (line-end-position)
  11855. t)
  11856. (match-beginning 0)
  11857. (line-end-position))))))
  11858. ;; If there is nothing more to add and no more keyword
  11859. ;; is left, remove the line completely.
  11860. (if (and (looking-at-p "[ \t]*$") (not what))
  11861. (delete-region (line-beginning-position)
  11862. (line-beginning-position 2))
  11863. ;; If we removed last keyword, do not leave trailing
  11864. ;; white space at the end of line.
  11865. (let ((p (point)))
  11866. (save-excursion
  11867. (end-of-line)
  11868. (unless (= (skip-chars-backward " \t" p) 0)
  11869. (delete-region (point) (line-end-position)))))))
  11870. ((not what) (throw 'exit nil)) ; Nothing to do.
  11871. (t (insert-before-markers "\n")
  11872. (backward-char 1)
  11873. (when org-adapt-indentation
  11874. (indent-to-column (1+ (org-outline-level))))))
  11875. (when what
  11876. ;; Insert planning keyword.
  11877. (insert (cl-case what
  11878. (closed org-closed-string)
  11879. (deadline org-deadline-string)
  11880. (scheduled org-scheduled-string)
  11881. (otherwise (error "Invalid planning type: %s" what)))
  11882. " ")
  11883. ;; Insert associated timestamp.
  11884. (let ((ts (org-insert-time-stamp
  11885. time
  11886. (or org-time-was-given
  11887. (and (eq what 'closed) org-log-done-with-time))
  11888. (eq what 'closed)
  11889. nil nil (list org-end-time-was-given))))
  11890. (unless (eolp) (insert " "))
  11891. ts))))))
  11892. (defvar org-log-note-marker (make-marker)
  11893. "Marker pointing at the entry where the note is to be inserted.")
  11894. (defvar org-log-note-purpose nil)
  11895. (defvar org-log-note-state nil)
  11896. (defvar org-log-note-previous-state nil)
  11897. (defvar org-log-note-extra nil)
  11898. (defvar org-log-note-window-configuration nil)
  11899. (defvar org-log-note-return-to (make-marker))
  11900. (defvar org-log-note-effective-time nil
  11901. "Remembered current time so that dynamically scoped
  11902. `org-extend-today-until' affects timestamps in state change log")
  11903. (defvar org-log-post-message nil
  11904. "Message to be displayed after a log note has been stored.
  11905. The auto-repeater uses this.")
  11906. (defun org-add-note ()
  11907. "Add a note to the current entry.
  11908. This is done in the same way as adding a state change note."
  11909. (interactive)
  11910. (org-add-log-setup 'note))
  11911. (defun org-log-beginning (&optional create)
  11912. "Return expected start of log notes in current entry.
  11913. When optional argument CREATE is non-nil, the function creates
  11914. a drawer to store notes, if necessary. Returned position ignores
  11915. narrowing."
  11916. (org-with-wide-buffer
  11917. (let ((drawer (org-log-into-drawer)))
  11918. (cond
  11919. (drawer
  11920. (org-end-of-meta-data)
  11921. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  11922. (end (if (org-at-heading-p) (point)
  11923. (save-excursion (outline-next-heading) (point))))
  11924. (case-fold-search t))
  11925. (catch 'exit
  11926. ;; Try to find existing drawer.
  11927. (while (re-search-forward regexp end t)
  11928. (let ((element (org-element-at-point)))
  11929. (when (eq (org-element-type element) 'drawer)
  11930. (let ((cend (org-element-property :contents-end element)))
  11931. (when (and (not org-log-states-order-reversed) cend)
  11932. (goto-char cend)))
  11933. (throw 'exit nil))))
  11934. ;; No drawer found. Create one, if permitted.
  11935. (when create
  11936. (unless (bolp) (insert "\n"))
  11937. (let ((beg (point)))
  11938. (insert ":" drawer ":\n:END:\n")
  11939. (org-indent-region beg (point)))
  11940. (end-of-line -1)))))
  11941. (t
  11942. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  11943. (skip-chars-forward " \t\n")
  11944. (beginning-of-line)
  11945. (unless org-log-states-order-reversed
  11946. (org-skip-over-state-notes)
  11947. (skip-chars-backward " \t\n")
  11948. (forward-line)))))
  11949. (if (bolp) (point) (line-beginning-position 2))))
  11950. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  11951. "Set up the post command hook to take a note.
  11952. If this is about to TODO state change, the new state is expected in STATE.
  11953. HOW is an indicator what kind of note should be created.
  11954. EXTRA is additional text that will be inserted into the notes buffer."
  11955. (move-marker org-log-note-marker (point))
  11956. (setq org-log-note-purpose purpose
  11957. org-log-note-state state
  11958. org-log-note-previous-state prev-state
  11959. org-log-note-how how
  11960. org-log-note-extra extra
  11961. org-log-note-effective-time (org-current-effective-time))
  11962. (add-hook 'post-command-hook 'org-add-log-note 'append))
  11963. (defun org-skip-over-state-notes ()
  11964. "Skip past the list of State notes in an entry."
  11965. (when (ignore-errors (goto-char (org-in-item-p)))
  11966. (let* ((struct (org-list-struct))
  11967. (prevs (org-list-prevs-alist struct))
  11968. (regexp
  11969. (concat "[ \t]*- +"
  11970. (replace-regexp-in-string
  11971. " +" " +"
  11972. (org-replace-escapes
  11973. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  11974. `(("%d" . ,org-ts-regexp-inactive)
  11975. ("%D" . ,org-ts-regexp)
  11976. ("%s" . "\"\\S-+\"")
  11977. ("%S" . "\"\\S-+\"")
  11978. ("%t" . ,org-ts-regexp-inactive)
  11979. ("%T" . ,org-ts-regexp)
  11980. ("%u" . ".*?")
  11981. ("%U" . ".*?")))))))
  11982. (while (looking-at-p regexp)
  11983. (goto-char (or (org-list-get-next-item (point) struct prevs)
  11984. (org-list-get-item-end (point) struct)))))))
  11985. (defun org-add-log-note (&optional _purpose)
  11986. "Pop up a window for taking a note, and add this note later."
  11987. (remove-hook 'post-command-hook 'org-add-log-note)
  11988. (setq org-log-note-window-configuration (current-window-configuration))
  11989. (delete-other-windows)
  11990. (move-marker org-log-note-return-to (point))
  11991. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  11992. (goto-char org-log-note-marker)
  11993. (org-switch-to-buffer-other-window "*Org Note*")
  11994. (erase-buffer)
  11995. (if (memq org-log-note-how '(time state))
  11996. (org-store-log-note)
  11997. (let ((org-inhibit-startup t)) (org-mode))
  11998. (insert (format "# Insert note for %s.
  11999. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12000. (cond
  12001. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12002. ((eq org-log-note-purpose 'done) "closed todo item")
  12003. ((eq org-log-note-purpose 'state)
  12004. (format "state change from \"%s\" to \"%s\""
  12005. (or org-log-note-previous-state "")
  12006. (or org-log-note-state "")))
  12007. ((eq org-log-note-purpose 'reschedule)
  12008. "rescheduling")
  12009. ((eq org-log-note-purpose 'delschedule)
  12010. "no longer scheduled")
  12011. ((eq org-log-note-purpose 'redeadline)
  12012. "changing deadline")
  12013. ((eq org-log-note-purpose 'deldeadline)
  12014. "removing deadline")
  12015. ((eq org-log-note-purpose 'refile)
  12016. "refiling")
  12017. ((eq org-log-note-purpose 'note)
  12018. "this entry")
  12019. (t (error "This should not happen")))))
  12020. (when org-log-note-extra (insert org-log-note-extra))
  12021. (setq-local org-finish-function 'org-store-log-note)
  12022. (run-hooks 'org-log-buffer-setup-hook)))
  12023. (defvar org-note-abort nil) ; dynamically scoped
  12024. (defun org-store-log-note ()
  12025. "Finish taking a log note, and insert it to where it belongs."
  12026. (let ((txt (prog1 (buffer-string)
  12027. (kill-buffer)))
  12028. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12029. lines)
  12030. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12031. (setq txt (replace-match "" t t txt)))
  12032. (when (string-match "\\s-+\\'" txt)
  12033. (setq txt (replace-match "" t t txt)))
  12034. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  12035. (when (org-string-nw-p note)
  12036. (setq note
  12037. (org-replace-escapes
  12038. note
  12039. (list (cons "%u" (user-login-name))
  12040. (cons "%U" user-full-name)
  12041. (cons "%t" (format-time-string
  12042. (org-time-stamp-format 'long 'inactive)
  12043. org-log-note-effective-time))
  12044. (cons "%T" (format-time-string
  12045. (org-time-stamp-format 'long nil)
  12046. org-log-note-effective-time))
  12047. (cons "%d" (format-time-string
  12048. (org-time-stamp-format nil 'inactive)
  12049. org-log-note-effective-time))
  12050. (cons "%D" (format-time-string
  12051. (org-time-stamp-format nil nil)
  12052. org-log-note-effective-time))
  12053. (cons "%s" (cond
  12054. ((not org-log-note-state) "")
  12055. ((string-match-p org-ts-regexp
  12056. org-log-note-state)
  12057. (format "\"[%s]\""
  12058. (substring org-log-note-state 1 -1)))
  12059. (t (format "\"%s\"" org-log-note-state))))
  12060. (cons "%S"
  12061. (cond
  12062. ((not org-log-note-previous-state) "")
  12063. ((string-match-p org-ts-regexp
  12064. org-log-note-previous-state)
  12065. (format "\"[%s]\""
  12066. (substring
  12067. org-log-note-previous-state 1 -1)))
  12068. (t (format "\"%s\""
  12069. org-log-note-previous-state)))))))
  12070. (when lines (setq note (concat note " \\\\")))
  12071. (push note lines))
  12072. (when (and lines (not org-note-abort))
  12073. (with-current-buffer (marker-buffer org-log-note-marker)
  12074. (org-with-wide-buffer
  12075. ;; Find location for the new note.
  12076. (goto-char org-log-note-marker)
  12077. (set-marker org-log-note-marker nil)
  12078. ;; Note associated to a clock is to be located right after
  12079. ;; the clock. Do not move point.
  12080. (unless (eq org-log-note-purpose 'clock-out)
  12081. (goto-char (org-log-beginning t)))
  12082. ;; Make sure point is at the beginning of an empty line.
  12083. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12084. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12085. ;; In an existing list, add a new item at the top level.
  12086. ;; Otherwise, indent line like a regular one.
  12087. (let ((itemp (org-in-item-p)))
  12088. (if itemp
  12089. (indent-line-to
  12090. (let ((struct (save-excursion
  12091. (goto-char itemp) (org-list-struct))))
  12092. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12093. (org-indent-line)))
  12094. (insert (org-list-bullet-string "-") (pop lines))
  12095. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12096. (dolist (line lines)
  12097. (insert "\n")
  12098. (indent-line-to ind)
  12099. (insert line)))
  12100. (message "Note stored")
  12101. (org-back-to-heading t)
  12102. (org-cycle-hide-drawers 'children))
  12103. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12104. ;; from within `org-add-log-note' because `buffer-undo-list'
  12105. ;; is then modified outside of `org-with-remote-undo'.
  12106. (when (eq this-command 'org-agenda-todo)
  12107. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12108. ;; Don't add undo information when called from `org-agenda-todo'.
  12109. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12110. (set-window-configuration org-log-note-window-configuration)
  12111. (with-current-buffer (marker-buffer org-log-note-return-to)
  12112. (goto-char org-log-note-return-to))
  12113. (move-marker org-log-note-return-to nil)
  12114. (when org-log-post-message (message "%s" org-log-post-message))))
  12115. (defun org-remove-empty-drawer-at (pos)
  12116. "Remove an empty drawer at position POS.
  12117. POS may also be a marker."
  12118. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12119. (org-with-wide-buffer
  12120. (goto-char pos)
  12121. (let ((drawer (org-element-at-point)))
  12122. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12123. (not (org-element-property :contents-begin drawer)))
  12124. (delete-region (org-element-property :begin drawer)
  12125. (progn (goto-char (org-element-property :end drawer))
  12126. (skip-chars-backward " \r\t\n")
  12127. (forward-line)
  12128. (point))))))))
  12129. (defvar org-ts-type nil)
  12130. (defun org-sparse-tree (&optional arg type)
  12131. "Create a sparse tree, prompt for the details.
  12132. This command can create sparse trees. You first need to select the type
  12133. of match used to create the tree:
  12134. t Show all TODO entries.
  12135. T Show entries with a specific TODO keyword.
  12136. m Show entries selected by a tags/property match.
  12137. p Enter a property name and its value (both with completion on existing
  12138. names/values) and show entries with that property.
  12139. r Show entries matching a regular expression (`/' can be used as well).
  12140. b Show deadlines and scheduled items before a date.
  12141. a Show deadlines and scheduled items after a date.
  12142. d Show deadlines due within `org-deadline-warning-days'.
  12143. D Show deadlines and scheduled items between a date range."
  12144. (interactive "P")
  12145. (setq type (or type org-sparse-tree-default-date-type))
  12146. (setq org-ts-type type)
  12147. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12148. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12149. \[c]ycle through date types: %s"
  12150. (cl-case type
  12151. (all "all timestamps")
  12152. (scheduled "only scheduled")
  12153. (deadline "only deadline")
  12154. (active "only active timestamps")
  12155. (inactive "only inactive timestamps")
  12156. (closed "with a closed time-stamp")
  12157. (otherwise "scheduled/deadline")))
  12158. (let ((answer (read-char-exclusive)))
  12159. (cl-case answer
  12160. (?c
  12161. (org-sparse-tree
  12162. arg
  12163. (cadr
  12164. (memq type '(nil all scheduled deadline active inactive closed)))))
  12165. (?d (call-interactively 'org-check-deadlines))
  12166. (?b (call-interactively 'org-check-before-date))
  12167. (?a (call-interactively 'org-check-after-date))
  12168. (?D (call-interactively 'org-check-dates-range))
  12169. (?t (call-interactively 'org-show-todo-tree))
  12170. (?T (org-show-todo-tree '(4)))
  12171. (?m (call-interactively 'org-match-sparse-tree))
  12172. ((?p ?P)
  12173. (let* ((kwd (completing-read
  12174. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12175. (value (completing-read
  12176. "Value: " (mapcar #'list (org-property-values kwd)))))
  12177. (unless (string-match "\\`{.*}\\'" value)
  12178. (setq value (concat "\"" value "\"")))
  12179. (org-match-sparse-tree arg (concat kwd "=" value))))
  12180. ((?r ?R ?/) (call-interactively 'org-occur))
  12181. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12182. (defvar-local org-occur-highlights nil
  12183. "List of overlays used for occur matches.")
  12184. (defvar-local org-occur-parameters nil
  12185. "Parameters of the active org-occur calls.
  12186. This is a list, each call to org-occur pushes as cons cell,
  12187. containing the regular expression and the callback, onto the list.
  12188. The list can contain several entries if `org-occur' has been called
  12189. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12190. will only contain one set of parameters. When the highlights are
  12191. removed (for example with `C-c C-c', or with the next edit (depending
  12192. on `org-remove-highlights-with-change'), this variable is emptied
  12193. as well.")
  12194. (defun org-occur (regexp &optional keep-previous callback)
  12195. "Make a compact tree which shows all matches of REGEXP.
  12196. The tree will show the lines where the regexp matches, and any other context
  12197. defined in `org-show-context-detail', which see.
  12198. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12199. done by a previous call to `org-occur' will be kept, to allow stacking of
  12200. calls to this command.
  12201. Optional argument CALLBACK can be a function of no argument. In this case,
  12202. it is called with point at the end of the match, match data being set
  12203. accordingly. Current match is shown only if the return value is non-nil.
  12204. The function must neither move point nor alter narrowing."
  12205. (interactive "sRegexp: \nP")
  12206. (when (equal regexp "")
  12207. (user-error "Regexp cannot be empty"))
  12208. (unless keep-previous
  12209. (org-remove-occur-highlights nil nil t))
  12210. (push (cons regexp callback) org-occur-parameters)
  12211. (let ((cnt 0))
  12212. (save-excursion
  12213. (goto-char (point-min))
  12214. (when (or (not keep-previous) ; do not want to keep
  12215. (not org-occur-highlights)) ; no previous matches
  12216. ;; hide everything
  12217. (org-overview))
  12218. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12219. (isearch-no-upper-case-p regexp t)
  12220. org-occur-case-fold-search)))
  12221. (while (re-search-forward regexp nil t)
  12222. (when (or (not callback)
  12223. (save-match-data (funcall callback)))
  12224. (setq cnt (1+ cnt))
  12225. (when org-highlight-sparse-tree-matches
  12226. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12227. (org-show-context 'occur-tree)))))
  12228. (when org-remove-highlights-with-change
  12229. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12230. nil 'local))
  12231. (unless org-sparse-tree-open-archived-trees
  12232. (org-hide-archived-subtrees (point-min) (point-max)))
  12233. (run-hooks 'org-occur-hook)
  12234. (when (called-interactively-p 'interactive)
  12235. (message "%d match(es) for regexp %s" cnt regexp))
  12236. cnt))
  12237. (defun org-occur-next-match (&optional n _reset)
  12238. "Function for `next-error-function' to find sparse tree matches.
  12239. N is the number of matches to move, when negative move backwards.
  12240. This function always goes back to the starting point when no
  12241. match is found."
  12242. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12243. (search-func (if (< n 0)
  12244. 'previous-single-char-property-change
  12245. 'next-single-char-property-change))
  12246. (n (abs n))
  12247. (pos (point))
  12248. p1)
  12249. (catch 'exit
  12250. (while (setq p1 (funcall search-func (point) 'org-type))
  12251. (when (equal p1 limit)
  12252. (goto-char pos)
  12253. (user-error "No more matches"))
  12254. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12255. (setq n (1- n))
  12256. (when (= n 0)
  12257. (goto-char p1)
  12258. (throw 'exit (point))))
  12259. (goto-char p1))
  12260. (goto-char p1)
  12261. (user-error "No more matches"))))
  12262. (defun org-show-context (&optional key)
  12263. "Make sure point and context are visible.
  12264. Optional argument KEY, when non-nil, is a symbol. See
  12265. `org-show-context-detail' for allowed values and how much is to
  12266. be shown."
  12267. (org-show-set-visibility
  12268. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12269. ((cdr (assq key org-show-context-detail)))
  12270. (t (cdr (assq 'default org-show-context-detail))))))
  12271. (defun org-show-set-visibility (detail)
  12272. "Set visibility around point according to DETAIL.
  12273. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12274. `tree', `canonical' or t. See `org-show-context-detail' for more
  12275. information."
  12276. ;; Show current heading and possibly its entry, following headline
  12277. ;; or all children.
  12278. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12279. (org-flag-heading nil)
  12280. (org-show-entry)
  12281. ;; If point is hidden within a drawer or a block, make sure to
  12282. ;; expose it.
  12283. (dolist (o (overlays-at (point)))
  12284. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  12285. (delete-overlay o)))
  12286. (unless (org-before-first-heading-p)
  12287. (org-with-limited-levels
  12288. (cl-case detail
  12289. ((tree canonical t) (org-show-children))
  12290. ((nil minimal ancestors))
  12291. (t (save-excursion
  12292. (outline-next-heading)
  12293. (org-flag-heading nil)))))))
  12294. ;; Show all siblings.
  12295. (when (eq detail 'lineage) (org-show-siblings))
  12296. ;; Show ancestors, possibly with their children.
  12297. (when (memq detail '(ancestors lineage tree canonical t))
  12298. (save-excursion
  12299. (while (org-up-heading-safe)
  12300. (org-flag-heading nil)
  12301. (when (memq detail '(canonical t)) (org-show-entry))
  12302. (when (memq detail '(tree canonical t)) (org-show-children))))))
  12303. (defvar org-reveal-start-hook nil
  12304. "Hook run before revealing a location.")
  12305. (defun org-reveal (&optional siblings)
  12306. "Show current entry, hierarchy above it, and the following headline.
  12307. This can be used to show a consistent set of context around
  12308. locations exposed with `org-show-context'.
  12309. With optional argument SIBLINGS, on each level of the hierarchy all
  12310. siblings are shown. This repairs the tree structure to what it would
  12311. look like when opened with hierarchical calls to `org-cycle'.
  12312. With a \\[universal-argument] \\[universal-argument] prefix, \
  12313. go to the parent and show the entire tree."
  12314. (interactive "P")
  12315. (run-hooks 'org-reveal-start-hook)
  12316. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12317. ((equal siblings '(16))
  12318. (save-excursion
  12319. (when (org-up-heading-safe)
  12320. (org-show-subtree)
  12321. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12322. (t (org-show-set-visibility 'lineage))))
  12323. (defun org-highlight-new-match (beg end)
  12324. "Highlight from BEG to END and mark the highlight is an occur headline."
  12325. (let ((ov (make-overlay beg end)))
  12326. (overlay-put ov 'face 'secondary-selection)
  12327. (overlay-put ov 'org-type 'org-occur)
  12328. (push ov org-occur-highlights)))
  12329. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12330. "Remove the occur highlights from the buffer.
  12331. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12332. from the `before-change-functions' in the current buffer."
  12333. (interactive)
  12334. (unless org-inhibit-highlight-removal
  12335. (mapc #'delete-overlay org-occur-highlights)
  12336. (setq org-occur-highlights nil)
  12337. (setq org-occur-parameters nil)
  12338. (unless noremove
  12339. (remove-hook 'before-change-functions
  12340. 'org-remove-occur-highlights 'local))))
  12341. ;;;; Priorities
  12342. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12343. "Regular expression matching the priority indicator.")
  12344. (defvar org-remove-priority-next-time nil)
  12345. (defun org-priority-up ()
  12346. "Increase the priority of the current item."
  12347. (interactive)
  12348. (org-priority 'up))
  12349. (defun org-priority-down ()
  12350. "Decrease the priority of the current item."
  12351. (interactive)
  12352. (org-priority 'down))
  12353. (defun org-priority (&optional action _show)
  12354. "Change the priority of an item.
  12355. ACTION can be `set', `up', `down', or a character."
  12356. (interactive "P")
  12357. (if (equal action '(4))
  12358. (org-show-priority)
  12359. (unless org-enable-priority-commands
  12360. (user-error "Priority commands are disabled"))
  12361. (setq action (or action 'set))
  12362. (let (current new news have remove)
  12363. (save-excursion
  12364. (org-back-to-heading t)
  12365. (when (looking-at org-priority-regexp)
  12366. (setq current (string-to-char (match-string 2))
  12367. have t))
  12368. (cond
  12369. ((eq action 'remove)
  12370. (setq remove t new ?\ ))
  12371. ((or (eq action 'set)
  12372. (integerp action))
  12373. (if (not (eq action 'set))
  12374. (setq new action)
  12375. (message "Priority %c-%c, SPC to remove: "
  12376. org-highest-priority org-lowest-priority)
  12377. (save-match-data
  12378. (setq new (read-char-exclusive))))
  12379. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12380. (= (upcase org-lowest-priority) org-lowest-priority))
  12381. (setq new (upcase new)))
  12382. (cond ((equal new ?\ ) (setq remove t))
  12383. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12384. (user-error "Priority must be between `%c' and `%c'"
  12385. org-highest-priority org-lowest-priority))))
  12386. ((eq action 'up)
  12387. (setq new (if have
  12388. (1- current) ; normal cycling
  12389. ;; last priority was empty
  12390. (if (eq last-command this-command)
  12391. org-lowest-priority ; wrap around empty to lowest
  12392. ;; default
  12393. (if org-priority-start-cycle-with-default
  12394. org-default-priority
  12395. (1- org-default-priority))))))
  12396. ((eq action 'down)
  12397. (setq new (if have
  12398. (1+ current) ; normal cycling
  12399. ;; last priority was empty
  12400. (if (eq last-command this-command)
  12401. org-highest-priority ; wrap around empty to highest
  12402. ;; default
  12403. (if org-priority-start-cycle-with-default
  12404. org-default-priority
  12405. (1+ org-default-priority))))))
  12406. (t (user-error "Invalid action")))
  12407. (when (or (< (upcase new) org-highest-priority)
  12408. (> (upcase new) org-lowest-priority))
  12409. (if (and (memq action '(up down))
  12410. (not have) (not (eq last-command this-command)))
  12411. ;; `new' is from default priority
  12412. (error
  12413. "The default can not be set, see `org-default-priority' why")
  12414. ;; normal cycling: `new' is beyond highest/lowest priority
  12415. ;; and is wrapped around to the empty priority
  12416. (setq remove t)))
  12417. (setq news (format "%c" new))
  12418. (if have
  12419. (if remove
  12420. (replace-match "" t t nil 1)
  12421. (replace-match news t t nil 2))
  12422. (if remove
  12423. (user-error "No priority cookie found in line")
  12424. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12425. (if (match-end 2)
  12426. (progn
  12427. (goto-char (match-end 2))
  12428. (insert " [#" news "]"))
  12429. (goto-char (match-beginning 3))
  12430. (insert "[#" news "] "))))
  12431. (org-set-tags nil 'align))
  12432. (if remove
  12433. (message "Priority removed")
  12434. (message "Priority of current item set to %s" news)))))
  12435. (defun org-show-priority ()
  12436. "Show the priority of the current item.
  12437. This priority is composed of the main priority given with the [#A] cookies,
  12438. and by additional input from the age of a schedules or deadline entry."
  12439. (interactive)
  12440. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12441. (org-get-at-bol 'priority)
  12442. (save-excursion
  12443. (save-match-data
  12444. (beginning-of-line)
  12445. (and (looking-at org-heading-regexp)
  12446. (org-get-priority (match-string 0))))))))
  12447. (message "Priority is %d" (if pri pri -1000))))
  12448. (defun org-get-priority (s)
  12449. "Find priority cookie and return priority."
  12450. (save-match-data
  12451. (if (functionp org-get-priority-function)
  12452. (funcall org-get-priority-function)
  12453. (if (not (string-match org-priority-regexp s))
  12454. (* 1000 (- org-lowest-priority org-default-priority))
  12455. (* 1000 (- org-lowest-priority
  12456. (string-to-char (match-string 2 s))))))))
  12457. ;;;; Tags
  12458. (defvar org-agenda-archives-mode)
  12459. (defvar org-map-continue-from nil
  12460. "Position from where mapping should continue.
  12461. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12462. (defvar org-scanner-tags nil
  12463. "The current tag list while the tags scanner is running.")
  12464. (defvar org-trust-scanner-tags nil
  12465. "Should `org-get-tags-at' use the tags for the scanner.
  12466. This is for internal dynamical scoping only.
  12467. When this is non-nil, the function `org-get-tags-at' will return the value
  12468. of `org-scanner-tags' instead of building the list by itself. This
  12469. can lead to large speed-ups when the tags scanner is used in a file with
  12470. many entries, and when the list of tags is retrieved, for example to
  12471. obtain a list of properties. Building the tags list for each entry in such
  12472. a file becomes an N^2 operation - but with this variable set, it scales
  12473. as N.")
  12474. (defvar org--matcher-tags-todo-only nil)
  12475. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12476. "Scan headline tags with inheritance and produce output ACTION.
  12477. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12478. or `agenda' to produce an entry list for an agenda view. It can also be
  12479. a Lisp form or a function that should be called at each matched headline, in
  12480. this case the return value is a list of all return values from these calls.
  12481. MATCHER is a function accepting three arguments, returning
  12482. a non-nil value whenever a given set of tags qualifies a headline
  12483. for inclusion. See `org-make-tags-matcher' for more information.
  12484. As a special case, it can also be set to t (respectively nil) in
  12485. order to match all (respectively none) headline.
  12486. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  12487. included in the output.
  12488. START-LEVEL can be a string with asterisks, reducing the scope to
  12489. headlines matching this string."
  12490. (require 'org-agenda)
  12491. (let* ((re (concat "^"
  12492. (if start-level
  12493. ;; Get the correct level to match
  12494. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12495. org-outline-regexp)
  12496. " *\\(\\<\\("
  12497. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  12498. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  12499. (props (list 'face 'default
  12500. 'done-face 'org-agenda-done
  12501. 'undone-face 'default
  12502. 'mouse-face 'highlight
  12503. 'org-not-done-regexp org-not-done-regexp
  12504. 'org-todo-regexp org-todo-regexp
  12505. 'org-complex-heading-regexp org-complex-heading-regexp
  12506. 'help-echo
  12507. (format "mouse-2 or RET jump to org file %s"
  12508. (abbreviate-file-name
  12509. (or (buffer-file-name (buffer-base-buffer))
  12510. (buffer-name (buffer-base-buffer)))))))
  12511. (org-map-continue-from nil)
  12512. lspos tags tags-list
  12513. (tags-alist (list (cons 0 org-file-tags)))
  12514. (llast 0) rtn rtn1 level category i txt
  12515. todo marker entry priority
  12516. ts-date ts-date-type ts-date-pair)
  12517. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12518. (setq action (list 'lambda nil action)))
  12519. (save-excursion
  12520. (goto-char (point-min))
  12521. (when (eq action 'sparse-tree)
  12522. (org-overview)
  12523. (org-remove-occur-highlights))
  12524. (while (let (case-fold-search)
  12525. (re-search-forward re nil t))
  12526. (setq org-map-continue-from nil)
  12527. (catch :skip
  12528. (setq todo
  12529. ;; TODO: is the 1-2 difference a bug?
  12530. (when (match-end 1) (match-string-no-properties 2))
  12531. tags (when (match-end 4) (match-string-no-properties 4)))
  12532. (goto-char (setq lspos (match-beginning 0)))
  12533. (setq level (org-reduced-level (org-outline-level))
  12534. category (org-get-category))
  12535. (when (eq action 'agenda)
  12536. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12537. ts-date (car ts-date-pair)
  12538. ts-date-type (cdr ts-date-pair)))
  12539. (setq i llast llast level)
  12540. ;; remove tag lists from same and sublevels
  12541. (while (>= i level)
  12542. (when (setq entry (assoc i tags-alist))
  12543. (setq tags-alist (delete entry tags-alist)))
  12544. (setq i (1- i)))
  12545. ;; add the next tags
  12546. (when tags
  12547. (setq tags (org-split-string tags ":")
  12548. tags-alist
  12549. (cons (cons level tags) tags-alist)))
  12550. ;; compile tags for current headline
  12551. (setq tags-list
  12552. (if org-use-tag-inheritance
  12553. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12554. tags)
  12555. org-scanner-tags tags-list)
  12556. (when org-use-tag-inheritance
  12557. (setcdr (car tags-alist)
  12558. (mapcar (lambda (x)
  12559. (setq x (copy-sequence x))
  12560. (org-add-prop-inherited x))
  12561. (cdar tags-alist))))
  12562. (when (and tags org-use-tag-inheritance
  12563. (or (not (eq t org-use-tag-inheritance))
  12564. org-tags-exclude-from-inheritance))
  12565. ;; Selective inheritance, remove uninherited ones.
  12566. (setcdr (car tags-alist)
  12567. (org-remove-uninherited-tags (cdar tags-alist))))
  12568. (when (and
  12569. ;; eval matcher only when the todo condition is OK
  12570. (and (or (not todo-only) (member todo org-todo-keywords-1))
  12571. (if (functionp matcher)
  12572. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12573. (funcall matcher todo tags-list level))
  12574. matcher))
  12575. ;; Call the skipper, but return t if it does not
  12576. ;; skip, so that the `and' form continues evaluating.
  12577. (progn
  12578. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12579. t)
  12580. ;; Check if timestamps are deselecting this entry
  12581. (or (not todo-only)
  12582. (and (member todo org-todo-keywords-1)
  12583. (or (not org-agenda-tags-todo-honor-ignore-options)
  12584. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12585. ;; select this headline
  12586. (cond
  12587. ((eq action 'sparse-tree)
  12588. (and org-highlight-sparse-tree-matches
  12589. (org-get-heading) (match-end 0)
  12590. (org-highlight-new-match
  12591. (match-beginning 1) (match-end 1)))
  12592. (org-show-context 'tags-tree))
  12593. ((eq action 'agenda)
  12594. (setq txt (org-agenda-format-item
  12595. ""
  12596. (concat
  12597. (if (eq org-tags-match-list-sublevels 'indented)
  12598. (make-string (1- level) ?.) "")
  12599. (org-get-heading))
  12600. (make-string level ?\s)
  12601. category
  12602. tags-list)
  12603. priority (org-get-priority txt))
  12604. (goto-char lspos)
  12605. (setq marker (org-agenda-new-marker))
  12606. (org-add-props txt props
  12607. 'org-marker marker 'org-hd-marker marker 'org-category category
  12608. 'todo-state todo
  12609. 'ts-date ts-date
  12610. 'priority priority
  12611. 'type (concat "tagsmatch" ts-date-type))
  12612. (push txt rtn))
  12613. ((functionp action)
  12614. (setq org-map-continue-from nil)
  12615. (save-excursion
  12616. (setq rtn1 (funcall action))
  12617. (push rtn1 rtn)))
  12618. (t (user-error "Invalid action")))
  12619. ;; if we are to skip sublevels, jump to end of subtree
  12620. (unless org-tags-match-list-sublevels
  12621. (org-end-of-subtree t)
  12622. (backward-char 1))))
  12623. ;; Get the correct position from where to continue
  12624. (if org-map-continue-from
  12625. (goto-char org-map-continue-from)
  12626. (and (= (point) lspos) (end-of-line 1)))))
  12627. (when (and (eq action 'sparse-tree)
  12628. (not org-sparse-tree-open-archived-trees))
  12629. (org-hide-archived-subtrees (point-min) (point-max)))
  12630. (nreverse rtn)))
  12631. (defun org-remove-uninherited-tags (tags)
  12632. "Remove all tags that are not inherited from the list TAGS."
  12633. (cond
  12634. ((eq org-use-tag-inheritance t)
  12635. (if org-tags-exclude-from-inheritance
  12636. (org-delete-all org-tags-exclude-from-inheritance tags)
  12637. tags))
  12638. ((not org-use-tag-inheritance) nil)
  12639. ((stringp org-use-tag-inheritance)
  12640. (delq nil (mapcar
  12641. (lambda (x)
  12642. (if (and (string-match org-use-tag-inheritance x)
  12643. (not (member x org-tags-exclude-from-inheritance)))
  12644. x nil))
  12645. tags)))
  12646. ((listp org-use-tag-inheritance)
  12647. (delq nil (mapcar
  12648. (lambda (x)
  12649. (if (member x org-use-tag-inheritance) x nil))
  12650. tags)))))
  12651. (defun org-match-sparse-tree (&optional todo-only match)
  12652. "Create a sparse tree according to tags string MATCH.
  12653. MATCH is a string with match syntax. It can contain a selection
  12654. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12655. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12656. those. See the manual for details.
  12657. If optional argument TODO-ONLY is non-nil, only select lines that
  12658. are also TODO tasks."
  12659. (interactive "P")
  12660. (org-agenda-prepare-buffers (list (current-buffer)))
  12661. (let ((org--matcher-tags-todo-only todo-only))
  12662. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12663. org--matcher-tags-todo-only)))
  12664. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12665. (defvar org-cached-props nil)
  12666. (defun org-cached-entry-get (pom property)
  12667. (if (or (eq t org-use-property-inheritance)
  12668. (and (stringp org-use-property-inheritance)
  12669. (let ((case-fold-search t))
  12670. (string-match-p org-use-property-inheritance property)))
  12671. (and (listp org-use-property-inheritance)
  12672. (member-ignore-case property org-use-property-inheritance)))
  12673. ;; Caching is not possible, check it directly.
  12674. (org-entry-get pom property 'inherit)
  12675. ;; Get all properties, so we can do complicated checks easily.
  12676. (cdr (assoc-string property
  12677. (or org-cached-props
  12678. (setq org-cached-props (org-entry-properties pom)))
  12679. t))))
  12680. (defun org-global-tags-completion-table (&optional files)
  12681. "Return the list of all tags in all agenda buffer/files.
  12682. Optional FILES argument is a list of files which can be used
  12683. instead of the agenda files."
  12684. (save-excursion
  12685. (org-uniquify
  12686. (delq nil
  12687. (apply #'append
  12688. (mapcar
  12689. (lambda (file)
  12690. (set-buffer (find-file-noselect file))
  12691. (mapcar (lambda (x)
  12692. (and (stringp (car-safe x))
  12693. (list (car-safe x))))
  12694. (or org-current-tag-alist (org-get-buffer-tags))))
  12695. (if (car-safe files) files
  12696. (org-agenda-files))))))))
  12697. (defun org-make-tags-matcher (match)
  12698. "Create the TAGS/TODO matcher form for the selection string MATCH.
  12699. Returns a cons of the selection string MATCH and a function
  12700. implementing the matcher.
  12701. The matcher is to be called at an Org entry, with point on the
  12702. headline, and returns non-nil if the entry matches the selection
  12703. string MATCH. It must be called with three arguments: the TODO
  12704. keyword at the entry (or nil if none), the list of all tags at
  12705. the entry including inherited ones and the reduced level of the
  12706. headline. Additionally, the category of the entry, if any, must
  12707. be specified as the text property `org-category' on the headline.
  12708. This function sets the variable `org--matcher-tags-todo-only' to
  12709. a non-nil value if the matcher restricts matching to TODO
  12710. entries, otherwise it is not touched.
  12711. See also `org-scan-tags'."
  12712. (unless match
  12713. ;; Get a new match request, with completion against the global
  12714. ;; tags table and the local tags in current buffer.
  12715. (let ((org-last-tags-completion-table
  12716. (org-uniquify
  12717. (delq nil (append (org-get-buffer-tags)
  12718. (org-global-tags-completion-table))))))
  12719. (setq match
  12720. (completing-read
  12721. "Match: "
  12722. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  12723. (let ((match0 match)
  12724. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  12725. (start 0)
  12726. tagsmatch todomatch tagsmatcher todomatcher)
  12727. ;; Expand group tags.
  12728. (setq match (org-tags-expand match))
  12729. ;; Check if there is a TODO part of this match, which would be the
  12730. ;; part after a "/". To make sure that this slash is not part of
  12731. ;; a property value to be matched against, we also check that
  12732. ;; there is no / after that slash. First, find the last slash.
  12733. (let ((s 0))
  12734. (while (string-match "/+" match s)
  12735. (setq start (match-beginning 0))
  12736. (setq s (match-end 0))))
  12737. (if (and (string-match "/+" match start)
  12738. (not (string-match-p "\"" match start)))
  12739. ;; Match contains also a TODO-matching request.
  12740. (progn
  12741. (setq tagsmatch (substring match 0 (match-beginning 0)))
  12742. (setq todomatch (substring match (match-end 0)))
  12743. (when (string-prefix-p "!" todomatch)
  12744. (setq org--matcher-tags-todo-only t)
  12745. (setq todomatch (substring todomatch 1)))
  12746. (when (string-match "\\`\\s-*\\'" todomatch)
  12747. (setq todomatch nil)))
  12748. ;; Only matching tags.
  12749. (setq tagsmatch match)
  12750. (setq todomatch nil))
  12751. ;; Make the tags matcher.
  12752. (when (org-string-nw-p tagsmatch)
  12753. (let ((orlist nil)
  12754. (orterms (org-split-string tagsmatch "|"))
  12755. term)
  12756. (while (setq term (pop orterms))
  12757. (while (and (equal (substring term -1) "\\") orterms)
  12758. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  12759. (while (string-match re term)
  12760. (let* ((rest (substring term (match-end 0)))
  12761. (minus (and (match-end 1)
  12762. (equal (match-string 1 term) "-")))
  12763. (tag (save-match-data
  12764. (replace-regexp-in-string
  12765. "\\\\-" "-" (match-string 2 term))))
  12766. (regexp (eq (string-to-char tag) ?{))
  12767. (levelp (match-end 4))
  12768. (propp (match-end 5))
  12769. (mm
  12770. (cond
  12771. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  12772. (levelp
  12773. `(,(org-op-to-function (match-string 3 term))
  12774. level
  12775. ,(string-to-number (match-string 4 term))))
  12776. (propp
  12777. (let* ((gv (pcase (upcase (match-string 5 term))
  12778. ("CATEGORY"
  12779. '(get-text-property (point) 'org-category))
  12780. ("TODO" 'todo)
  12781. (p `(org-cached-entry-get nil ,p))))
  12782. (pv (match-string 7 term))
  12783. (regexp (eq (string-to-char pv) ?{))
  12784. (strp (eq (string-to-char pv) ?\"))
  12785. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  12786. (po (org-op-to-function (match-string 6 term)
  12787. (if timep 'time strp))))
  12788. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  12789. (when timep (setq pv (org-matcher-time pv)))
  12790. (cond ((and regexp (eq po 'org<>))
  12791. `(not (string-match ,pv (or ,gv ""))))
  12792. (regexp `(string-match ,pv (or ,gv "")))
  12793. (strp `(,po (or ,gv "") ,pv))
  12794. (t
  12795. `(,po
  12796. (string-to-number (or ,gv ""))
  12797. ,(string-to-number pv))))))
  12798. (t `(member ,tag tags-list)))))
  12799. (push (if minus `(not ,mm) mm) tagsmatcher)
  12800. (setq term rest)))
  12801. (push `(and ,@tagsmatcher) orlist)
  12802. (setq tagsmatcher nil))
  12803. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  12804. ;; Make the TODO matcher.
  12805. (when (org-string-nw-p todomatch)
  12806. (let ((orlist nil))
  12807. (dolist (term (org-split-string todomatch "|"))
  12808. (while (string-match re term)
  12809. (let* ((minus (and (match-end 1)
  12810. (equal (match-string 1 term) "-")))
  12811. (kwd (match-string 2 term))
  12812. (regexp (eq (string-to-char kwd) ?{))
  12813. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  12814. `(equal todo ,kwd))))
  12815. (push (if minus `(not ,mm) mm) todomatcher))
  12816. (setq term (substring term (match-end 0))))
  12817. (push (if (> (length todomatcher) 1)
  12818. (cons 'and todomatcher)
  12819. (car todomatcher))
  12820. orlist)
  12821. (setq todomatcher nil))
  12822. (setq todomatcher (cons 'or orlist))))
  12823. ;; Return the string and function of the matcher. If no
  12824. ;; tags-specific or todo-specific matcher exists, match
  12825. ;; everything.
  12826. (let ((matcher (if (and tagsmatcher todomatcher)
  12827. `(and ,tagsmatcher ,todomatcher)
  12828. (or tagsmatcher todomatcher t))))
  12829. (when org--matcher-tags-todo-only
  12830. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  12831. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  12832. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  12833. "Expand group tags in MATCH.
  12834. This replaces every group tag in MATCH with a regexp tag search.
  12835. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  12836. will be replaced like this:
  12837. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12838. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12839. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12840. Replacing by a regexp preserves the structure of the match.
  12841. E.g., this expansion
  12842. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  12843. will match anything tagged with \"Lab\" and \"Home\", or tagged
  12844. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  12845. A group tag in MATCH can contain regular expressions of its own.
  12846. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  12847. will be replaced like this:
  12848. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  12849. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  12850. assumed to be a single group tag, and the function will return
  12851. the list of tags in this group.
  12852. When DOWNCASE is non-nil, expand downcased TAGS."
  12853. (if org-group-tags
  12854. (let* ((case-fold-search t)
  12855. (stable org-mode-syntax-table)
  12856. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  12857. (taggroups (if downcased
  12858. (mapcar (lambda (tg) (mapcar #'downcase tg))
  12859. taggroups)
  12860. taggroups))
  12861. (taggroups-keys (mapcar #'car taggroups))
  12862. (return-match (if downcased (downcase match) match))
  12863. (count 0)
  12864. (work-already-expanded tags-already-expanded)
  12865. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  12866. ;; @ and _ are allowed as word-components in tags.
  12867. (modify-syntax-entry ?@ "w" stable)
  12868. (modify-syntax-entry ?_ "w" stable)
  12869. ;; Temporarily replace regexp-expressions in the match-expression.
  12870. (while (string-match "{.+?}" return-match)
  12871. (cl-incf count)
  12872. (push (match-string 0 return-match) regexps-in-match)
  12873. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  12874. (while (and taggroups-keys
  12875. (with-syntax-table stable
  12876. (string-match
  12877. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  12878. (regexp-opt taggroups-keys) "\\>\\)")
  12879. return-match)))
  12880. (let* ((dir (match-string 1 return-match))
  12881. (tag (match-string 2 return-match))
  12882. (tag (if downcased (downcase tag) tag)))
  12883. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  12884. (member tag work-already-expanded))
  12885. (setq tags-in-group (assoc tag taggroups))
  12886. (push tag work-already-expanded)
  12887. ;; Recursively expand each tag in the group, if the tag hasn't
  12888. ;; already been expanded. Restore the match-data after all recursive calls.
  12889. (save-match-data
  12890. (let (tags-expanded)
  12891. (dolist (x (cdr tags-in-group))
  12892. (if (and (member x taggroups-keys)
  12893. (not (member x work-already-expanded)))
  12894. (setq tags-expanded
  12895. (delete-dups
  12896. (append
  12897. (org-tags-expand x t downcased
  12898. work-already-expanded)
  12899. tags-expanded)))
  12900. (setq tags-expanded
  12901. (append (list x) tags-expanded)))
  12902. (setq work-already-expanded
  12903. (delete-dups
  12904. (append tags-expanded
  12905. work-already-expanded))))
  12906. (setq tags-in-group
  12907. (delete-dups (cons (car tags-in-group)
  12908. tags-expanded)))))
  12909. ;; Filter tag-regexps from tags.
  12910. (setq regexp-in-group-escaped
  12911. (delq nil (mapcar (lambda (x)
  12912. (if (stringp x)
  12913. (and (equal "{" (substring x 0 1))
  12914. (equal "}" (substring x -1))
  12915. x)
  12916. x))
  12917. tags-in-group))
  12918. regexp-in-group
  12919. (mapcar (lambda (x)
  12920. (substring x 1 -1))
  12921. regexp-in-group-escaped)
  12922. tags-in-group
  12923. (delq nil (mapcar (lambda (x)
  12924. (if (stringp x)
  12925. (and (not (equal "{" (substring x 0 1)))
  12926. (not (equal "}" (substring x -1)))
  12927. x)
  12928. x))
  12929. tags-in-group)))
  12930. ;; If single-as-list, do no more in the while-loop.
  12931. (if (not single-as-list)
  12932. (progn
  12933. (when regexp-in-group
  12934. (setq regexp-in-group
  12935. (concat "\\|"
  12936. (mapconcat 'identity regexp-in-group
  12937. "\\|"))))
  12938. (setq tags-in-group
  12939. (concat dir
  12940. "{\\<"
  12941. (regexp-opt tags-in-group)
  12942. "\\>"
  12943. regexp-in-group
  12944. "}"))
  12945. (when (stringp tags-in-group)
  12946. (org-add-props tags-in-group '(grouptag t)))
  12947. (setq return-match
  12948. (replace-match tags-in-group t t return-match)))
  12949. (setq tags-in-group
  12950. (append regexp-in-group-escaped tags-in-group))))
  12951. (setq taggroups-keys (delete tag taggroups-keys))))
  12952. ;; Add the regular expressions back into the match-expression again.
  12953. (while regexps-in-match
  12954. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  12955. (pop regexps-in-match)
  12956. return-match t t))
  12957. (cl-decf count))
  12958. (if single-as-list
  12959. (if tags-in-group tags-in-group (list return-match))
  12960. return-match))
  12961. (if single-as-list
  12962. (list (if downcased (downcase match) match))
  12963. match)))
  12964. (defun org-op-to-function (op &optional stringp)
  12965. "Turn an operator into the appropriate function."
  12966. (setq op
  12967. (cond
  12968. ((equal op "<" ) '(< string< org-time<))
  12969. ((equal op ">" ) '(> org-string> org-time>))
  12970. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  12971. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  12972. ((member op '("=" "==")) '(= string= org-time=))
  12973. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  12974. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  12975. (defun org<> (a b) (not (= a b)))
  12976. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  12977. (defun org-string>= (a b) (not (string< a b)))
  12978. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  12979. (defun org-string<> (a b) (not (string= a b)))
  12980. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  12981. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  12982. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  12983. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  12984. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  12985. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  12986. (defun org-2ft (s)
  12987. "Convert S to a floating point time.
  12988. If S is already a number, just return it. If it is a string, parse
  12989. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  12990. (cond
  12991. ((numberp s) s)
  12992. ((stringp s)
  12993. (condition-case nil
  12994. (float-time (apply #'encode-time (org-parse-time-string s nil t)))
  12995. (error 0.)))
  12996. (t 0.)))
  12997. (defun org-time-today ()
  12998. "Time in seconds today at 0:00.
  12999. Returns the float number of seconds since the beginning of the
  13000. epoch to the beginning of today (00:00)."
  13001. (float-time (apply 'encode-time
  13002. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13003. (defun org-matcher-time (s)
  13004. "Interpret a time comparison value."
  13005. (save-match-data
  13006. (cond
  13007. ((string= s "<now>") (float-time))
  13008. ((string= s "<today>") (org-time-today))
  13009. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13010. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13011. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13012. (+ (org-time-today)
  13013. (* (string-to-number (match-string 1 s))
  13014. (cdr (assoc (match-string 2 s)
  13015. '(("d" . 86400.0) ("w" . 604800.0)
  13016. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13017. (t (org-2ft s)))))
  13018. (defun org-match-any-p (re list)
  13019. "Does re match any element of list?"
  13020. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13021. (delq nil list))
  13022. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13023. (defvar org-tags-overlay (make-overlay 1 1))
  13024. (delete-overlay org-tags-overlay)
  13025. (defun org-get-local-tags-at (&optional pos)
  13026. "Get a list of tags defined in the current headline."
  13027. (org-get-tags-at pos 'local))
  13028. (defun org-get-local-tags ()
  13029. "Get a list of tags defined in the current headline."
  13030. (org-get-tags-at nil 'local))
  13031. (defun org-get-tags-at (&optional pos local)
  13032. "Get a list of all headline tags applicable at POS.
  13033. POS defaults to point. If tags are inherited, the list contains
  13034. the targets in the same sequence as the headlines appear, i.e.
  13035. the tags of the current headline come last.
  13036. When LOCAL is non-nil, only return tags from the current headline,
  13037. ignore inherited ones."
  13038. (interactive)
  13039. (if (and org-trust-scanner-tags
  13040. (or (not pos) (equal pos (point)))
  13041. (not local))
  13042. org-scanner-tags
  13043. (let (tags ltags lastpos parent)
  13044. (save-excursion
  13045. (save-restriction
  13046. (widen)
  13047. (goto-char (or pos (point)))
  13048. (save-match-data
  13049. (catch 'done
  13050. (condition-case nil
  13051. (progn
  13052. (org-back-to-heading t)
  13053. (while (not (equal lastpos (point)))
  13054. (setq lastpos (point))
  13055. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13056. (setq ltags (org-split-string
  13057. (match-string-no-properties 1) ":"))
  13058. (when parent
  13059. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13060. (setq tags (append
  13061. (if parent
  13062. (org-remove-uninherited-tags ltags)
  13063. ltags)
  13064. tags)))
  13065. (or org-use-tag-inheritance (throw 'done t))
  13066. (when local (throw 'done t))
  13067. (or (org-up-heading-safe) (error nil))
  13068. (setq parent t)))
  13069. (error nil)))))
  13070. (if local
  13071. tags
  13072. (reverse (delete-dups
  13073. (reverse (append
  13074. (org-remove-uninherited-tags
  13075. org-file-tags)
  13076. tags)))))))))
  13077. (defun org-add-prop-inherited (s)
  13078. (add-text-properties 0 (length s) '(inherited t) s)
  13079. s)
  13080. (defun org-toggle-tag (tag &optional onoff)
  13081. "Toggle the tag TAG for the current line.
  13082. If ONOFF is `on' or `off', don't toggle but set to this state."
  13083. (save-excursion
  13084. (org-back-to-heading t)
  13085. (let ((current
  13086. (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  13087. (line-end-position) t)
  13088. (let ((tags (match-string 1)))
  13089. ;; Clear current tags.
  13090. (replace-match "")
  13091. ;; Reverse the tags list so any new tag is appended to
  13092. ;; the current list of tags.
  13093. (nreverse (org-split-string tags ":")))))
  13094. res)
  13095. (pcase onoff
  13096. (`off (setq current (delete tag current)))
  13097. ((or `on (guard (not (member tag current))))
  13098. (setq res t)
  13099. (cl-pushnew tag current :test #'equal))
  13100. (_ (setq current (delete tag current))))
  13101. (end-of-line)
  13102. (if current
  13103. (progn
  13104. (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
  13105. (org-set-tags nil t))
  13106. (delete-horizontal-space))
  13107. (run-hooks 'org-after-tags-change-hook)
  13108. res)))
  13109. (defun org--align-tags-here (to-col)
  13110. "Align tags on the current headline to TO-COL.
  13111. Assume point is on a headline."
  13112. (let ((pos (point)))
  13113. (beginning-of-line)
  13114. (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13115. (>= pos (match-beginning 2)))
  13116. ;; No tags or point within tags: do not align.
  13117. (goto-char pos)
  13118. (goto-char (match-beginning 1))
  13119. (let ((shift (max (- (if (>= to-col 0) to-col
  13120. (- (abs to-col) (string-width (match-string 2))))
  13121. (current-column))
  13122. 1)))
  13123. (replace-match (make-string shift ?\s) nil nil nil 1)
  13124. ;; Preserve initial position, if possible. In any case, stop
  13125. ;; before tags.
  13126. (when (< pos (point)) (goto-char pos))))))
  13127. (defun org-set-tags-command (&optional arg just-align)
  13128. "Call the set-tags command for the current entry."
  13129. (interactive "P")
  13130. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13131. (org-set-tags arg just-align)
  13132. (save-excursion
  13133. (unless (and (org-region-active-p)
  13134. org-loop-over-headlines-in-active-region)
  13135. (org-back-to-heading t))
  13136. (org-set-tags arg just-align))))
  13137. (defun org-set-tags-to (data)
  13138. "Set the tags of the current entry to DATA, replacing the current tags.
  13139. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13140. If DATA is nil or the empty string, any tags will be removed."
  13141. (interactive "sTags: ")
  13142. (setq data
  13143. (cond
  13144. ((eq data nil) "")
  13145. ((equal data "") "")
  13146. ((stringp data)
  13147. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13148. ":"))
  13149. ((listp data)
  13150. (concat ":" (mapconcat 'identity data ":") ":"))))
  13151. (when data
  13152. (save-excursion
  13153. (org-back-to-heading t)
  13154. (when (let ((case-fold-search nil))
  13155. (looking-at org-complex-heading-regexp))
  13156. (if (match-end 5)
  13157. (progn
  13158. (goto-char (match-beginning 5))
  13159. (insert data)
  13160. (delete-region (point) (point-at-eol))
  13161. (org-set-tags nil 'align))
  13162. (goto-char (point-at-eol))
  13163. (insert " " data)
  13164. (org-set-tags nil 'align)))
  13165. (beginning-of-line 1)
  13166. (when (looking-at ".*?\\([ \t]+\\)$")
  13167. (delete-region (match-beginning 1) (match-end 1))))))
  13168. (defun org-align-all-tags ()
  13169. "Align the tags in all headings."
  13170. (interactive)
  13171. (save-excursion
  13172. (or (ignore-errors (org-back-to-heading t))
  13173. (outline-next-heading))
  13174. (if (org-at-heading-p)
  13175. (org-set-tags t)
  13176. (message "No headings"))))
  13177. (defvar org-indent-indentation-per-level)
  13178. (defun org-set-tags (&optional arg just-align)
  13179. "Set the tags for the current headline.
  13180. With prefix ARG, realign all tags in headings in the current buffer.
  13181. When JUST-ALIGN is non-nil, only align tags."
  13182. (interactive "P")
  13183. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13184. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13185. 'region-start-level
  13186. 'region))
  13187. org-loop-over-headlines-in-active-region)
  13188. (org-map-entries
  13189. ;; We don't use ARG and JUST-ALIGN here because these args
  13190. ;; are not useful when looping over headlines.
  13191. #'org-set-tags
  13192. org-loop-over-headlines-in-active-region
  13193. cl
  13194. '(when (org-invisible-p) (org-end-of-subtree nil t))))
  13195. (let ((org-setting-tags t))
  13196. (if arg
  13197. (save-excursion
  13198. (goto-char (point-min))
  13199. (while (re-search-forward org-outline-regexp-bol nil t)
  13200. (org-set-tags nil t)
  13201. (end-of-line))
  13202. (message "All tags realigned to column %d" org-tags-column))
  13203. (let* ((current (org-get-tags-string))
  13204. (tags
  13205. (if just-align current
  13206. ;; Get a new set of tags from the user.
  13207. (save-excursion
  13208. (let* ((seen)
  13209. (table
  13210. (setq
  13211. org-last-tags-completion-table
  13212. ;; Uniquify tags in alists, yet preserve
  13213. ;; structure (i.e., keywords).
  13214. (delq nil
  13215. (mapcar
  13216. (lambda (pair)
  13217. (let ((head (car pair)))
  13218. (cond ((symbolp head) pair)
  13219. ((member head seen) nil)
  13220. (t (push head seen)
  13221. pair))))
  13222. (append
  13223. (or org-current-tag-alist
  13224. (org-get-buffer-tags))
  13225. (and
  13226. org-complete-tags-always-offer-all-agenda-tags
  13227. (org-global-tags-completion-table
  13228. (org-agenda-files))))))))
  13229. (current-tags (org-split-string current ":"))
  13230. (inherited-tags
  13231. (nreverse (nthcdr (length current-tags)
  13232. (nreverse (org-get-tags-at))))))
  13233. (replace-regexp-in-string
  13234. "\\([-+&]+\\|,\\)"
  13235. ":"
  13236. (if (or (eq t org-use-fast-tag-selection)
  13237. (and org-use-fast-tag-selection
  13238. (delq nil (mapcar #'cdr table))))
  13239. (org-fast-tag-selection
  13240. current-tags inherited-tags table
  13241. (and org-fast-tag-selection-include-todo
  13242. org-todo-key-alist))
  13243. (let ((org-add-colon-after-tag-completion
  13244. (< 1 (length table))))
  13245. (org-trim
  13246. (completing-read
  13247. "Tags: "
  13248. #'org-tags-completion-function
  13249. nil nil current 'org-tags-history))))))))))
  13250. (when org-tags-sort-function
  13251. (setq tags
  13252. (mapconcat
  13253. #'identity
  13254. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13255. org-tags-sort-function)
  13256. ":")))
  13257. (if (or (string= ":" tags)
  13258. (string= "::" tags))
  13259. (setq tags ""))
  13260. (if (not (org-string-nw-p tags)) (setq tags "")
  13261. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  13262. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  13263. ;; Insert new tags at the correct column.
  13264. (unless (equal current tags)
  13265. (save-excursion
  13266. (beginning-of-line)
  13267. (let ((case-fold-search nil))
  13268. (looking-at org-complex-heading-regexp))
  13269. ;; Remove current tags, if any.
  13270. (when (match-end 5) (replace-match "" nil nil nil 5))
  13271. ;; Insert new tags, if any. Otherwise, remove trailing
  13272. ;; white spaces.
  13273. (end-of-line)
  13274. (if (not (equal tags ""))
  13275. ;; When text is being inserted on an invisible
  13276. ;; region boundary, it can be inadvertently sucked
  13277. ;; into invisibility.
  13278. (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
  13279. (skip-chars-backward " \t")
  13280. (delete-region (point) (line-end-position)))))
  13281. ;; Align tags, if any. Fix tags column if `org-indent-mode'
  13282. ;; is on.
  13283. (unless (equal tags "")
  13284. (let* ((level (save-excursion
  13285. (beginning-of-line)
  13286. (skip-chars-forward "\\*")))
  13287. (offset (if (bound-and-true-p org-indent-mode)
  13288. (* (1- org-indent-indentation-per-level)
  13289. (1- level))
  13290. 0))
  13291. (tags-column
  13292. (+ org-tags-column
  13293. (if (> org-tags-column 0) (- offset) offset))))
  13294. (org--align-tags-here tags-column))))
  13295. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13296. (defun org-change-tag-in-region (beg end tag off)
  13297. "Add or remove TAG for each entry in the region.
  13298. This works in the agenda, and also in an Org buffer."
  13299. (interactive
  13300. (list (region-beginning) (region-end)
  13301. (let ((org-last-tags-completion-table
  13302. (if (derived-mode-p 'org-mode)
  13303. (org-uniquify
  13304. (delq nil (append (org-get-buffer-tags)
  13305. (org-global-tags-completion-table))))
  13306. (org-global-tags-completion-table))))
  13307. (completing-read
  13308. "Tag: " 'org-tags-completion-function nil nil nil
  13309. 'org-tags-history))
  13310. (progn
  13311. (message "[s]et or [r]emove? ")
  13312. (equal (read-char-exclusive) ?r))))
  13313. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13314. (let ((agendap (equal major-mode 'org-agenda-mode))
  13315. l1 l2 m buf pos newhead (cnt 0))
  13316. (goto-char end)
  13317. (setq l2 (1- (org-current-line)))
  13318. (goto-char beg)
  13319. (setq l1 (org-current-line))
  13320. (cl-loop for l from l1 to l2 do
  13321. (org-goto-line l)
  13322. (setq m (get-text-property (point) 'org-hd-marker))
  13323. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13324. (and agendap m))
  13325. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13326. pos (if agendap m (point)))
  13327. (with-current-buffer buf
  13328. (save-excursion
  13329. (save-restriction
  13330. (goto-char pos)
  13331. (setq cnt (1+ cnt))
  13332. (org-toggle-tag tag (if off 'off 'on))
  13333. (setq newhead (org-get-heading)))))
  13334. (and agendap (org-agenda-change-all-lines newhead m))))
  13335. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13336. (defun org-tags-completion-function (string _predicate &optional flag)
  13337. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13338. (confirm (lambda (x) (stringp (car x)))))
  13339. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13340. (setq s1 (match-string 1 string)
  13341. s2 (match-string 2 string))
  13342. (setq s1 "" s2 string))
  13343. (cond
  13344. ((eq flag nil)
  13345. ;; try completion
  13346. (setq rtn (try-completion s2 ctable confirm))
  13347. (when (stringp rtn)
  13348. (setq rtn
  13349. (concat s1 s2 (substring rtn (length s2))
  13350. (if (and org-add-colon-after-tag-completion
  13351. (assoc rtn ctable))
  13352. ":" ""))))
  13353. rtn)
  13354. ((eq flag t)
  13355. ;; all-completions
  13356. (all-completions s2 ctable confirm))
  13357. ((eq flag 'lambda)
  13358. ;; exact match?
  13359. (assoc s2 ctable)))))
  13360. (defun org-fast-tag-insert (kwd tags face &optional end)
  13361. "Insert KDW, and the TAGS, the latter with face FACE.
  13362. Also insert END."
  13363. (insert (format "%-12s" (concat kwd ":"))
  13364. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13365. (or end "")))
  13366. (defun org-fast-tag-show-exit (flag)
  13367. (save-excursion
  13368. (org-goto-line 3)
  13369. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13370. (replace-match ""))
  13371. (when flag
  13372. (end-of-line 1)
  13373. (org-move-to-column (- (window-width) 19) t)
  13374. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13375. (defun org-set-current-tags-overlay (current prefix)
  13376. "Add an overlay to CURRENT tag with PREFIX."
  13377. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13378. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13379. (org-overlay-display org-tags-overlay (concat prefix s))))
  13380. (defvar org-last-tag-selection-key nil)
  13381. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13382. "Fast tag selection with single keys.
  13383. CURRENT is the current list of tags in the headline, INHERITED is the
  13384. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13385. possibly with grouping information. TODO-TABLE is a similar table with
  13386. TODO keywords, should these have keys assigned to them.
  13387. If the keys are nil, a-z are automatically assigned.
  13388. Returns the new tags string, or nil to not change the current settings."
  13389. (let* ((fulltable (append table todo-table))
  13390. (maxlen (apply 'max (mapcar
  13391. (lambda (x)
  13392. (if (stringp (car x)) (string-width (car x)) 0))
  13393. fulltable)))
  13394. (buf (current-buffer))
  13395. (expert (eq org-fast-tag-selection-single-key 'expert))
  13396. (buffer-tags nil)
  13397. (fwidth (+ maxlen 3 1 3))
  13398. (ncol (/ (- (window-width) 4) fwidth))
  13399. (i-face 'org-done)
  13400. (c-face 'org-todo)
  13401. tg cnt e c char c1 c2 ntable tbl rtn
  13402. ov-start ov-end ov-prefix
  13403. (exit-after-next org-fast-tag-selection-single-key)
  13404. (done-keywords org-done-keywords)
  13405. groups ingroup intaggroup)
  13406. (save-excursion
  13407. (beginning-of-line 1)
  13408. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13409. (setq ov-start (match-beginning 1)
  13410. ov-end (match-end 1)
  13411. ov-prefix "")
  13412. (setq ov-start (1- (point-at-eol))
  13413. ov-end (1+ ov-start))
  13414. (skip-chars-forward "^\n\r")
  13415. (setq ov-prefix
  13416. (concat
  13417. (buffer-substring (1- (point)) (point))
  13418. (if (> (current-column) org-tags-column)
  13419. " "
  13420. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13421. (move-overlay org-tags-overlay ov-start ov-end)
  13422. (save-window-excursion
  13423. (if expert
  13424. (set-buffer (get-buffer-create " *Org tags*"))
  13425. (delete-other-windows)
  13426. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13427. (org-switch-to-buffer-other-window " *Org tags*"))
  13428. (erase-buffer)
  13429. (setq-local org-done-keywords done-keywords)
  13430. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13431. (org-fast-tag-insert "Current" current c-face "\n\n")
  13432. (org-fast-tag-show-exit exit-after-next)
  13433. (org-set-current-tags-overlay current ov-prefix)
  13434. (setq tbl fulltable char ?a cnt 0)
  13435. (while (setq e (pop tbl))
  13436. (cond
  13437. ((eq (car e) :startgroup)
  13438. (push '() groups) (setq ingroup t)
  13439. (unless (zerop cnt)
  13440. (setq cnt 0)
  13441. (insert "\n"))
  13442. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13443. ((eq (car e) :endgroup)
  13444. (setq ingroup nil cnt 0)
  13445. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13446. ((eq (car e) :startgrouptag)
  13447. (setq intaggroup t)
  13448. (unless (zerop cnt)
  13449. (setq cnt 0)
  13450. (insert "\n"))
  13451. (insert "[ "))
  13452. ((eq (car e) :endgrouptag)
  13453. (setq intaggroup nil cnt 0)
  13454. (insert "]\n"))
  13455. ((equal e '(:newline))
  13456. (unless (zerop cnt)
  13457. (setq cnt 0)
  13458. (insert "\n")
  13459. (setq e (car tbl))
  13460. (while (equal (car tbl) '(:newline))
  13461. (insert "\n")
  13462. (setq tbl (cdr tbl)))))
  13463. ((equal e '(:grouptags)) (insert " : "))
  13464. (t
  13465. (setq tg (copy-sequence (car e)) c2 nil)
  13466. (if (cdr e)
  13467. (setq c (cdr e))
  13468. ;; automatically assign a character.
  13469. (setq c1 (string-to-char
  13470. (downcase (substring
  13471. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13472. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13473. (while (or (rassoc char ntable) (rassoc char table))
  13474. (setq char (1+ char)))
  13475. (setq c2 c1))
  13476. (setq c (or c2 char)))
  13477. (when ingroup (push tg (car groups)))
  13478. (setq tg (org-add-props tg nil 'face
  13479. (cond
  13480. ((not (assoc tg table))
  13481. (org-get-todo-face tg))
  13482. ((member tg current) c-face)
  13483. ((member tg inherited) i-face))))
  13484. (when (equal (caar tbl) :grouptags)
  13485. (org-add-props tg nil 'face 'org-tag-group))
  13486. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13487. (insert "[" c "] " tg (make-string
  13488. (- fwidth 4 (length tg)) ?\ ))
  13489. (push (cons tg c) ntable)
  13490. (when (= (cl-incf cnt) ncol)
  13491. (insert "\n")
  13492. (when (or ingroup intaggroup) (insert " "))
  13493. (setq cnt 0)))))
  13494. (setq ntable (nreverse ntable))
  13495. (insert "\n")
  13496. (goto-char (point-min))
  13497. (unless expert (org-fit-window-to-buffer))
  13498. (setq rtn
  13499. (catch 'exit
  13500. (while t
  13501. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  13502. (if (not groups) "no " "")
  13503. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13504. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13505. (setq org-last-tag-selection-key c)
  13506. (cond
  13507. ((= c ?\r) (throw 'exit t))
  13508. ((= c ?!)
  13509. (setq groups (not groups))
  13510. (goto-char (point-min))
  13511. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13512. ((= c ?\C-c)
  13513. (if (not expert)
  13514. (org-fast-tag-show-exit
  13515. (setq exit-after-next (not exit-after-next)))
  13516. (setq expert nil)
  13517. (delete-other-windows)
  13518. (set-window-buffer (split-window-vertically) " *Org tags*")
  13519. (org-switch-to-buffer-other-window " *Org tags*")
  13520. (org-fit-window-to-buffer)))
  13521. ((or (= c ?\C-g)
  13522. (and (= c ?q) (not (rassoc c ntable))))
  13523. (delete-overlay org-tags-overlay)
  13524. (setq quit-flag t))
  13525. ((= c ?\ )
  13526. (setq current nil)
  13527. (when exit-after-next (setq exit-after-next 'now)))
  13528. ((= c ?\t)
  13529. (condition-case nil
  13530. (setq tg (completing-read
  13531. "Tag: "
  13532. (or buffer-tags
  13533. (with-current-buffer buf
  13534. (setq buffer-tags
  13535. (org-get-buffer-tags))))))
  13536. (quit (setq tg "")))
  13537. (when (string-match "\\S-" tg)
  13538. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13539. (if (member tg current)
  13540. (setq current (delete tg current))
  13541. (push tg current)))
  13542. (when exit-after-next (setq exit-after-next 'now)))
  13543. ((setq e (rassoc c todo-table) tg (car e))
  13544. (with-current-buffer buf
  13545. (save-excursion (org-todo tg)))
  13546. (when exit-after-next (setq exit-after-next 'now)))
  13547. ((setq e (rassoc c ntable) tg (car e))
  13548. (if (member tg current)
  13549. (setq current (delete tg current))
  13550. (cl-loop for g in groups do
  13551. (when (member tg g)
  13552. (dolist (x g) (setq current (delete x current)))))
  13553. (push tg current))
  13554. (when exit-after-next (setq exit-after-next 'now))))
  13555. ;; Create a sorted list
  13556. (setq current
  13557. (sort current
  13558. (lambda (a b)
  13559. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13560. (when (eq exit-after-next 'now) (throw 'exit t))
  13561. (goto-char (point-min))
  13562. (beginning-of-line 2)
  13563. (delete-region (point) (point-at-eol))
  13564. (org-fast-tag-insert "Current" current c-face)
  13565. (org-set-current-tags-overlay current ov-prefix)
  13566. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  13567. (setq tg (match-string 1))
  13568. (add-text-properties
  13569. (match-beginning 1) (match-end 1)
  13570. (list 'face
  13571. (cond
  13572. ((member tg current) c-face)
  13573. ((member tg inherited) i-face)
  13574. (t (get-text-property (match-beginning 1) 'face))))))
  13575. (goto-char (point-min)))))
  13576. (delete-overlay org-tags-overlay)
  13577. (if rtn
  13578. (mapconcat 'identity current ":")
  13579. nil))))
  13580. (defun org-get-tags-string ()
  13581. "Get the TAGS string in the current headline."
  13582. (unless (org-at-heading-p t)
  13583. (user-error "Not on a heading"))
  13584. (save-excursion
  13585. (beginning-of-line 1)
  13586. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13587. (match-string-no-properties 1)
  13588. "")))
  13589. (defun org-get-tags ()
  13590. "Get the list of tags specified in the current headline."
  13591. (org-split-string (org-get-tags-string) ":"))
  13592. (defun org-get-buffer-tags ()
  13593. "Get a table of all tags used in the buffer, for completion."
  13594. (org-with-wide-buffer
  13595. (goto-char (point-min))
  13596. (let ((tag-re (concat org-outline-regexp-bol
  13597. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  13598. tags)
  13599. (while (re-search-forward tag-re nil t)
  13600. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  13601. (push tag tags)))
  13602. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  13603. ;;;; The mapping API
  13604. (defvar org-agenda-skip-comment-trees)
  13605. (defvar org-agenda-skip-function)
  13606. (defun org-map-entries (func &optional match scope &rest skip)
  13607. "Call FUNC at each headline selected by MATCH in SCOPE.
  13608. FUNC is a function or a lisp form. The function will be called without
  13609. arguments, with the cursor positioned at the beginning of the headline.
  13610. The return values of all calls to the function will be collected and
  13611. returned as a list.
  13612. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13613. does not need to preserve point. After evaluation, the cursor will be
  13614. moved to the end of the line (presumably of the headline of the
  13615. processed entry) and search continues from there. Under some
  13616. circumstances, this may not produce the wanted results. For example,
  13617. if you have removed (e.g. archived) the current (sub)tree it could
  13618. mean that the next entry will be skipped entirely. In such cases, you
  13619. can specify the position from where search should continue by making
  13620. FUNC set the variable `org-map-continue-from' to the desired buffer
  13621. position.
  13622. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13623. Only headlines that are matched by this query will be considered during
  13624. the iteration. When MATCH is nil or t, all headlines will be
  13625. visited by the iteration.
  13626. SCOPE determines the scope of this command. It can be any of:
  13627. nil The current buffer, respecting the restriction if any
  13628. tree The subtree started with the entry at point
  13629. region The entries within the active region, if any
  13630. region-start-level
  13631. The entries within the active region, but only those at
  13632. the same level than the first one.
  13633. file The current buffer, without restriction
  13634. file-with-archives
  13635. The current buffer, and any archives associated with it
  13636. agenda All agenda files
  13637. agenda-with-archives
  13638. All agenda files with any archive files associated with them
  13639. \(file1 file2 ...)
  13640. If this is a list, all files in the list will be scanned
  13641. The remaining args are treated as settings for the skipping facilities of
  13642. the scanner. The following items can be given here:
  13643. archive skip trees with the archive tag
  13644. comment skip trees with the COMMENT keyword
  13645. function or Emacs Lisp form:
  13646. will be used as value for `org-agenda-skip-function', so
  13647. whenever the function returns a position, FUNC will not be
  13648. called for that entry and search will continue from the
  13649. position returned
  13650. If your function needs to retrieve the tags including inherited tags
  13651. at the *current* entry, you can use the value of the variable
  13652. `org-scanner-tags' which will be much faster than getting the value
  13653. with `org-get-tags-at'. If your function gets properties with
  13654. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  13655. to t around the call to `org-entry-properties' to get the same speedup.
  13656. Note that if your function moves around to retrieve tags and properties at
  13657. a *different* entry, you cannot use these techniques."
  13658. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  13659. (not (org-region-active-p)))
  13660. (let* ((org-agenda-archives-mode nil) ; just to make sure
  13661. (org-agenda-skip-archived-trees (memq 'archive skip))
  13662. (org-agenda-skip-comment-trees (memq 'comment skip))
  13663. (org-agenda-skip-function
  13664. (car (org-delete-all '(comment archive) skip)))
  13665. (org-tags-match-list-sublevels t)
  13666. (start-level (eq scope 'region-start-level))
  13667. matcher res
  13668. org-todo-keywords-for-agenda
  13669. org-done-keywords-for-agenda
  13670. org-todo-keyword-alist-for-agenda
  13671. org-tag-alist-for-agenda
  13672. org--matcher-tags-todo-only)
  13673. (cond
  13674. ((eq match t) (setq matcher t))
  13675. ((eq match nil) (setq matcher t))
  13676. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  13677. (save-excursion
  13678. (save-restriction
  13679. (cond ((eq scope 'tree)
  13680. (org-back-to-heading t)
  13681. (org-narrow-to-subtree)
  13682. (setq scope nil))
  13683. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  13684. (org-region-active-p))
  13685. ;; If needed, set start-level to a string like "2"
  13686. (when start-level
  13687. (save-excursion
  13688. (goto-char (region-beginning))
  13689. (unless (org-at-heading-p) (outline-next-heading))
  13690. (setq start-level (org-current-level))))
  13691. (narrow-to-region (region-beginning)
  13692. (save-excursion
  13693. (goto-char (region-end))
  13694. (unless (and (bolp) (org-at-heading-p))
  13695. (outline-next-heading))
  13696. (point)))
  13697. (setq scope nil)))
  13698. (if (not scope)
  13699. (progn
  13700. (org-agenda-prepare-buffers
  13701. (and buffer-file-name (list buffer-file-name)))
  13702. (setq res
  13703. (org-scan-tags
  13704. func matcher org--matcher-tags-todo-only start-level)))
  13705. ;; Get the right scope
  13706. (cond
  13707. ((and scope (listp scope) (symbolp (car scope)))
  13708. (setq scope (eval scope)))
  13709. ((eq scope 'agenda)
  13710. (setq scope (org-agenda-files t)))
  13711. ((eq scope 'agenda-with-archives)
  13712. (setq scope (org-agenda-files t))
  13713. (setq scope (org-add-archive-files scope)))
  13714. ((eq scope 'file)
  13715. (setq scope (and buffer-file-name (list buffer-file-name))))
  13716. ((eq scope 'file-with-archives)
  13717. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  13718. (org-agenda-prepare-buffers scope)
  13719. (dolist (file scope)
  13720. (with-current-buffer (org-find-base-buffer-visiting file)
  13721. (org-with-wide-buffer
  13722. (goto-char (point-min))
  13723. (setq res
  13724. (append
  13725. res
  13726. (org-scan-tags
  13727. func matcher org--matcher-tags-todo-only)))))))))
  13728. res)))
  13729. ;;; Properties API
  13730. (defconst org-special-properties
  13731. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  13732. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  13733. "The special properties valid in Org mode.
  13734. These are properties that are not defined in the property drawer,
  13735. but in some other way.")
  13736. (defconst org-default-properties
  13737. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  13738. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  13739. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  13740. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  13741. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  13742. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  13743. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  13744. "Some properties that are used by Org mode for various purposes.
  13745. Being in this list makes sure that they are offered for completion.")
  13746. (defun org--valid-property-p (property)
  13747. "Non nil when string PROPERTY is a valid property name."
  13748. (not
  13749. (or (equal property "")
  13750. (string-match-p "\\s-" property))))
  13751. (defun org--update-property-plist (key val props)
  13752. "Associate KEY to VAL in alist PROPS.
  13753. Modifications are made by side-effect. Return new alist."
  13754. (let* ((appending (string= (substring key -1) "+"))
  13755. (key (if appending (substring key 0 -1) key))
  13756. (old (assoc-string key props t)))
  13757. (if (not old) (cons (cons key val) props)
  13758. (setcdr old (if appending (concat (cdr old) " " val) val))
  13759. props)))
  13760. (defun org-get-property-block (&optional beg force)
  13761. "Return the (beg . end) range of the body of the property drawer.
  13762. BEG is the beginning of the current subtree, or of the part
  13763. before the first headline. If it is not given, it will be found.
  13764. If the drawer does not exist, create it if FORCE is non-nil, or
  13765. return nil."
  13766. (org-with-wide-buffer
  13767. (when beg (goto-char beg))
  13768. (unless (org-before-first-heading-p)
  13769. (let ((beg (cond (beg)
  13770. ((or (not (featurep 'org-inlinetask))
  13771. (org-inlinetask-in-task-p))
  13772. (org-back-to-heading t))
  13773. (t (org-with-limited-levels (org-back-to-heading t))))))
  13774. (forward-line)
  13775. (when (looking-at-p org-planning-line-re) (forward-line))
  13776. (cond ((looking-at org-property-drawer-re)
  13777. (forward-line)
  13778. (cons (point) (progn (goto-char (match-end 0))
  13779. (line-beginning-position))))
  13780. (force
  13781. (goto-char beg)
  13782. (org-insert-property-drawer)
  13783. (let ((pos (save-excursion (search-forward ":END:")
  13784. (line-beginning-position))))
  13785. (cons pos pos))))))))
  13786. (defun org-at-property-p ()
  13787. "Non-nil when point is inside a property drawer.
  13788. See `org-property-re' for match data, if applicable."
  13789. (save-excursion
  13790. (beginning-of-line)
  13791. (and (looking-at org-property-re)
  13792. (let ((property-drawer (save-match-data (org-get-property-block))))
  13793. (and property-drawer
  13794. (>= (point) (car property-drawer))
  13795. (< (point) (cdr property-drawer)))))))
  13796. (defun org-property-action ()
  13797. "Do an action on properties."
  13798. (interactive)
  13799. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  13800. (let ((c (read-char-exclusive)))
  13801. (cl-case c
  13802. (?s (call-interactively #'org-set-property))
  13803. (?d (call-interactively #'org-delete-property))
  13804. (?D (call-interactively #'org-delete-property-globally))
  13805. (?c (call-interactively #'org-compute-property-at-point))
  13806. (otherwise (user-error "No such property action %c" c)))))
  13807. (defun org-inc-effort ()
  13808. "Increment the value of the effort property in the current entry."
  13809. (interactive)
  13810. (org-set-effort nil t))
  13811. (defvar org-clock-effort) ; Defined in org-clock.el.
  13812. (defvar org-clock-current-task) ; Defined in org-clock.el.
  13813. (defun org-set-effort (&optional value increment)
  13814. "Set the effort property of the current entry.
  13815. With numerical prefix arg, use the nth allowed value, 0 stands for the
  13816. 10th allowed value.
  13817. When INCREMENT is non-nil, set the property to the next allowed value."
  13818. (interactive "P")
  13819. (when (equal value 0) (setq value 10))
  13820. (let* ((completion-ignore-case t)
  13821. (prop org-effort-property)
  13822. (cur (org-entry-get nil prop))
  13823. (allowed (org-property-get-allowed-values nil prop 'table))
  13824. (existing (mapcar 'list (org-property-values prop)))
  13825. (heading (nth 4 (org-heading-components)))
  13826. rpl
  13827. (val (cond
  13828. ((stringp value) value)
  13829. ((and allowed (integerp value))
  13830. (or (car (nth (1- value) allowed))
  13831. (car (org-last allowed))))
  13832. ((and allowed increment)
  13833. (or (cl-caadr (member (list cur) allowed))
  13834. (user-error "Allowed effort values are not set")))
  13835. (allowed
  13836. (message "Select 1-9,0, [RET%s]: %s"
  13837. (if cur (concat "=" cur) "")
  13838. (mapconcat 'car allowed " "))
  13839. (setq rpl (read-char-exclusive))
  13840. (if (equal rpl ?\r)
  13841. cur
  13842. (setq rpl (- rpl ?0))
  13843. (when (equal rpl 0) (setq rpl 10))
  13844. (if (and (> rpl 0) (<= rpl (length allowed)))
  13845. (car (nth (1- rpl) allowed))
  13846. (org-completing-read "Effort: " allowed nil))))
  13847. (t
  13848. (org-completing-read
  13849. (concat "Effort" (and cur (string-match "\\S-" cur)
  13850. (concat " [" cur "]"))
  13851. ": ")
  13852. existing nil nil "" nil cur)))))
  13853. (unless (equal (org-entry-get nil prop) val)
  13854. (org-entry-put nil prop val))
  13855. (org-refresh-property
  13856. '((effort . identity)
  13857. (effort-minutes . org-duration-to-minutes))
  13858. val)
  13859. (when (equal heading (bound-and-true-p org-clock-current-task))
  13860. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  13861. (org-clock-update-mode-line))
  13862. (message "%s is now %s" prop val)))
  13863. (defun org-entry-properties (&optional pom which)
  13864. "Get all properties of the current entry.
  13865. When POM is a buffer position, get all properties from the entry
  13866. there instead.
  13867. This includes the TODO keyword, the tags, time strings for
  13868. deadline, scheduled, and clocking, and any additional properties
  13869. defined in the entry.
  13870. If WHICH is nil or `all', get all properties. If WHICH is
  13871. `special' or `standard', only get that subclass. If WHICH is
  13872. a string, only get that property.
  13873. Return value is an alist. Keys are properties, as upcased
  13874. strings."
  13875. (org-with-point-at pom
  13876. (when (and (derived-mode-p 'org-mode)
  13877. (ignore-errors (org-back-to-heading t)))
  13878. (catch 'exit
  13879. (let* ((beg (point))
  13880. (specific (and (stringp which) (upcase which)))
  13881. (which (cond ((not specific) which)
  13882. ((member specific org-special-properties) 'special)
  13883. (t 'standard)))
  13884. props)
  13885. ;; Get the special properties, like TODO and TAGS.
  13886. (when (memq which '(nil all special))
  13887. (when (or (not specific) (string= specific "CLOCKSUM"))
  13888. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  13889. (when clocksum
  13890. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  13891. props)))
  13892. (when specific (throw 'exit props)))
  13893. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  13894. (let ((clocksumt (get-text-property (point)
  13895. :org-clock-minutes-today)))
  13896. (when clocksumt
  13897. (push (cons "CLOCKSUM_T"
  13898. (org-duration-from-minutes clocksumt))
  13899. props)))
  13900. (when specific (throw 'exit props)))
  13901. (when (or (not specific) (string= specific "ITEM"))
  13902. (let ((case-fold-search nil))
  13903. (when (looking-at org-complex-heading-regexp)
  13904. (push (cons "ITEM"
  13905. (let ((title (match-string-no-properties 4)))
  13906. (if (org-string-nw-p title)
  13907. (org-remove-tabs title)
  13908. "")))
  13909. props)))
  13910. (when specific (throw 'exit props)))
  13911. (when (or (not specific) (string= specific "TODO"))
  13912. (let ((case-fold-search nil))
  13913. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  13914. (push (cons "TODO" (match-string-no-properties 2)) props)))
  13915. (when specific (throw 'exit props)))
  13916. (when (or (not specific) (string= specific "PRIORITY"))
  13917. (push (cons "PRIORITY"
  13918. (if (looking-at org-priority-regexp)
  13919. (match-string-no-properties 2)
  13920. (char-to-string org-default-priority)))
  13921. props)
  13922. (when specific (throw 'exit props)))
  13923. (when (or (not specific) (string= specific "FILE"))
  13924. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  13925. props)
  13926. (when specific (throw 'exit props)))
  13927. (when (or (not specific) (string= specific "TAGS"))
  13928. (let ((value (org-string-nw-p (org-get-tags-string))))
  13929. (when value (push (cons "TAGS" value) props)))
  13930. (when specific (throw 'exit props)))
  13931. (when (or (not specific) (string= specific "ALLTAGS"))
  13932. (let ((value (org-get-tags-at)))
  13933. (when value
  13934. (push (cons "ALLTAGS"
  13935. (format ":%s:" (mapconcat #'identity value ":")))
  13936. props)))
  13937. (when specific (throw 'exit props)))
  13938. (when (or (not specific) (string= specific "BLOCKED"))
  13939. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  13940. (when specific (throw 'exit props)))
  13941. (when (or (not specific)
  13942. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  13943. (forward-line)
  13944. (when (looking-at-p org-planning-line-re)
  13945. (end-of-line)
  13946. (let ((bol (line-beginning-position))
  13947. ;; Backward compatibility: time keywords used to
  13948. ;; be configurable (before 8.3). Make sure we
  13949. ;; get the correct keyword.
  13950. (key-assoc `(("CLOSED" . ,org-closed-string)
  13951. ("DEADLINE" . ,org-deadline-string)
  13952. ("SCHEDULED" . ,org-scheduled-string))))
  13953. (dolist (pair (if specific (list (assoc specific key-assoc))
  13954. key-assoc))
  13955. (save-excursion
  13956. (when (search-backward (cdr pair) bol t)
  13957. (goto-char (match-end 0))
  13958. (skip-chars-forward " \t")
  13959. (and (looking-at org-ts-regexp-both)
  13960. (push (cons (car pair)
  13961. (match-string-no-properties 0))
  13962. props)))))))
  13963. (when specific (throw 'exit props)))
  13964. (when (or (not specific)
  13965. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  13966. (let ((find-ts
  13967. (lambda (end ts)
  13968. ;; Fix next time-stamp before END. TS is the
  13969. ;; list of time-stamps found so far.
  13970. (let ((ts ts)
  13971. (regexp (cond
  13972. ((string= specific "TIMESTAMP")
  13973. org-ts-regexp)
  13974. ((string= specific "TIMESTAMP_IA")
  13975. org-ts-regexp-inactive)
  13976. ((assoc "TIMESTAMP_IA" ts)
  13977. org-ts-regexp)
  13978. ((assoc "TIMESTAMP" ts)
  13979. org-ts-regexp-inactive)
  13980. (t org-ts-regexp-both))))
  13981. (catch 'next
  13982. (while (re-search-forward regexp end t)
  13983. (backward-char)
  13984. (let ((object (org-element-context)))
  13985. ;; Accept to match timestamps in node
  13986. ;; properties, too.
  13987. (when (memq (org-element-type object)
  13988. '(node-property timestamp))
  13989. (let ((type
  13990. (org-element-property :type object)))
  13991. (cond
  13992. ((and (memq type '(active active-range))
  13993. (not (equal specific "TIMESTAMP_IA")))
  13994. (unless (assoc "TIMESTAMP" ts)
  13995. (push (cons "TIMESTAMP"
  13996. (org-element-property
  13997. :raw-value object))
  13998. ts)
  13999. (when specific (throw 'exit ts))))
  14000. ((and (memq type '(inactive inactive-range))
  14001. (not (string= specific "TIMESTAMP")))
  14002. (unless (assoc "TIMESTAMP_IA" ts)
  14003. (push (cons "TIMESTAMP_IA"
  14004. (org-element-property
  14005. :raw-value object))
  14006. ts)
  14007. (when specific (throw 'exit ts))))))
  14008. ;; Both timestamp types are found,
  14009. ;; move to next part.
  14010. (when (= (length ts) 2) (throw 'next ts)))))
  14011. ts)))))
  14012. (goto-char beg)
  14013. ;; First look for timestamps within headline.
  14014. (let ((ts (funcall find-ts (line-end-position) nil)))
  14015. (if (= (length ts) 2) (setq props (nconc ts props))
  14016. ;; Then find timestamps in the section, skipping
  14017. ;; planning line.
  14018. (let ((end (save-excursion (outline-next-heading))))
  14019. (forward-line)
  14020. (when (looking-at-p org-planning-line-re) (forward-line))
  14021. (setq props (nconc (funcall find-ts end ts) props))))))))
  14022. ;; Get the standard properties, like :PROP:.
  14023. (when (memq which '(nil all standard))
  14024. ;; If we are looking after a specific property, delegate
  14025. ;; to `org-entry-get', which is faster. However, make an
  14026. ;; exception for "CATEGORY", since it can be also set
  14027. ;; through keywords (i.e. #+CATEGORY).
  14028. (if (and specific (not (equal specific "CATEGORY")))
  14029. (let ((value (org-entry-get beg specific nil t)))
  14030. (throw 'exit (and value (list (cons specific value)))))
  14031. (let ((range (org-get-property-block beg)))
  14032. (when range
  14033. (let ((end (cdr range)) seen-base)
  14034. (goto-char (car range))
  14035. ;; Unlike to `org--update-property-plist', we
  14036. ;; handle the case where base values is found
  14037. ;; after its extension. We also forbid standard
  14038. ;; properties to be named as special properties.
  14039. (while (re-search-forward org-property-re end t)
  14040. (let* ((key (upcase (match-string-no-properties 2)))
  14041. (extendp (string-match-p "\\+\\'" key))
  14042. (key-base (if extendp (substring key 0 -1) key))
  14043. (value (match-string-no-properties 3)))
  14044. (cond
  14045. ((member-ignore-case key-base org-special-properties))
  14046. (extendp
  14047. (setq props
  14048. (org--update-property-plist key value props)))
  14049. ((member key seen-base))
  14050. (t (push key seen-base)
  14051. (let ((p (assoc-string key props t)))
  14052. (if p (setcdr p (concat value " " (cdr p)))
  14053. (push (cons key value) props))))))))))))
  14054. (unless (assoc "CATEGORY" props)
  14055. (push (cons "CATEGORY" (org-get-category beg)) props)
  14056. (when (string= specific "CATEGORY") (throw 'exit props)))
  14057. ;; Return value.
  14058. props)))))
  14059. (defun org--property-local-values (property literal-nil)
  14060. "Return value for PROPERTY in current entry.
  14061. Value is a list whose car is the base value for PROPERTY and cdr
  14062. a list of accumulated values. Return nil if neither is found in
  14063. the entry. Also return nil when PROPERTY is set to \"nil\",
  14064. unless LITERAL-NIL is non-nil."
  14065. (let ((range (org-get-property-block)))
  14066. (when range
  14067. (goto-char (car range))
  14068. (let* ((case-fold-search t)
  14069. (end (cdr range))
  14070. (value
  14071. ;; Base value.
  14072. (save-excursion
  14073. (let ((v (and (re-search-forward
  14074. (org-re-property property nil t) end t)
  14075. (match-string-no-properties 3))))
  14076. (list (if literal-nil v (org-not-nil v)))))))
  14077. ;; Find additional values.
  14078. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14079. (while (re-search-forward property+ end t)
  14080. (push (match-string-no-properties 3) value)))
  14081. ;; Return final values.
  14082. (and (not (equal value '(nil))) (nreverse value))))))
  14083. (defun org--property-global-value (property literal-nil)
  14084. "Return value for PROPERTY in current buffer.
  14085. Return value is a string. Return nil if property is not set
  14086. globally. Also return nil when PROPERTY is set to \"nil\",
  14087. unless LITERAL-NIL is non-nil."
  14088. (let ((global
  14089. (cdr (or (assoc-string property org-file-properties t)
  14090. (assoc-string property org-global-properties t)
  14091. (assoc-string property org-global-properties-fixed t)))))
  14092. (if literal-nil global (org-not-nil global))))
  14093. (defun org-entry-get (pom property &optional inherit literal-nil)
  14094. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14095. If INHERIT is non-nil and the entry does not have the property,
  14096. then also check higher levels of the hierarchy. If INHERIT is
  14097. the symbol `selective', use inheritance only if the setting in
  14098. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14099. If the property is present but empty, the return value is the
  14100. empty string. If the property is not present at all, nil is
  14101. returned. In any other case, return the value as a string.
  14102. Search is case-insensitive.
  14103. If LITERAL-NIL is set, return the string value \"nil\" as
  14104. a string, do not interpret it as the list atom nil. This is used
  14105. for inheritance when a \"nil\" value can supersede a non-nil
  14106. value higher up the hierarchy."
  14107. (org-with-point-at pom
  14108. (cond
  14109. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14110. ;; We need a special property. Use `org-entry-properties' to
  14111. ;; retrieve it, but specify the wanted property.
  14112. (cdr (assoc-string property (org-entry-properties nil property))))
  14113. ((and inherit
  14114. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14115. (org-entry-get-with-inheritance property literal-nil))
  14116. (t
  14117. (let* ((local (org--property-local-values property literal-nil))
  14118. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14119. (if literal-nil value (org-not-nil value)))))))
  14120. (defun org-property-or-variable-value (var &optional inherit)
  14121. "Check if there is a property fixing the value of VAR.
  14122. If yes, return this value. If not, return the current value of the variable."
  14123. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14124. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14125. (read prop)
  14126. (symbol-value var))))
  14127. (defun org-entry-delete (pom property)
  14128. "Delete PROPERTY from entry at point-or-marker POM.
  14129. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14130. non-nil when a property was removed."
  14131. (org-with-point-at pom
  14132. (pcase (org-get-property-block)
  14133. (`(,begin . ,origin)
  14134. (let* ((end (copy-marker origin))
  14135. (re (org-re-property
  14136. (concat (regexp-quote property) "\\+?") t t)))
  14137. (goto-char begin)
  14138. (while (re-search-forward re end t)
  14139. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14140. ;; If drawer is empty, remove it altogether.
  14141. (when (= begin end)
  14142. (delete-region (line-beginning-position 0)
  14143. (line-beginning-position 2)))
  14144. ;; Return non-nil if some property was removed.
  14145. (prog1 (/= end origin) (set-marker end nil))))
  14146. (_ nil))))
  14147. ;; Multi-values properties are properties that contain multiple values
  14148. ;; These values are assumed to be single words, separated by whitespace.
  14149. (defun org-entry-add-to-multivalued-property (pom property value)
  14150. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14151. (let* ((old (org-entry-get pom property))
  14152. (values (and old (split-string old))))
  14153. (setq value (org-entry-protect-space value))
  14154. (unless (member value values)
  14155. (setq values (append values (list value)))
  14156. (org-entry-put pom property (mapconcat #'identity values " ")))))
  14157. (defun org-entry-remove-from-multivalued-property (pom property value)
  14158. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14159. (let* ((old (org-entry-get pom property))
  14160. (values (and old (split-string old))))
  14161. (setq value (org-entry-protect-space value))
  14162. (when (member value values)
  14163. (setq values (delete value values))
  14164. (org-entry-put pom property (mapconcat #'identity values " ")))))
  14165. (defun org-entry-member-in-multivalued-property (pom property value)
  14166. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14167. (let* ((old (org-entry-get pom property))
  14168. (values (and old (split-string old))))
  14169. (setq value (org-entry-protect-space value))
  14170. (member value values)))
  14171. (defun org-entry-get-multivalued-property (pom property)
  14172. "Return a list of values in a multivalued property."
  14173. (let* ((value (org-entry-get pom property))
  14174. (values (and value (split-string value))))
  14175. (mapcar #'org-entry-restore-space values)))
  14176. (defun org-entry-put-multivalued-property (pom property &rest values)
  14177. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14178. VALUES should be a list of strings. Spaces will be protected."
  14179. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  14180. (let* ((value (org-entry-get pom property))
  14181. (values (and value (split-string value))))
  14182. (mapcar #'org-entry-restore-space values)))
  14183. (defun org-entry-protect-space (s)
  14184. "Protect spaces and newline in string S."
  14185. (while (string-match " " s)
  14186. (setq s (replace-match "%20" t t s)))
  14187. (while (string-match "\n" s)
  14188. (setq s (replace-match "%0A" t t s)))
  14189. s)
  14190. (defun org-entry-restore-space (s)
  14191. "Restore spaces and newline in string S."
  14192. (while (string-match "%20" s)
  14193. (setq s (replace-match " " t t s)))
  14194. (while (string-match "%0A" s)
  14195. (setq s (replace-match "\n" t t s)))
  14196. s)
  14197. (defvar org-entry-property-inherited-from (make-marker)
  14198. "Marker pointing to the entry from where a property was inherited.
  14199. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14200. location of the entry where the inheritance search matched. If there was
  14201. no match, the marker will point nowhere.
  14202. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14203. is set.")
  14204. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14205. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14206. The search will stop at the first ancestor which has the property defined.
  14207. If the value found is \"nil\", return nil to show that the property
  14208. should be considered as undefined (this is the meaning of nil here).
  14209. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14210. (move-marker org-entry-property-inherited-from nil)
  14211. (org-with-wide-buffer
  14212. (let (value)
  14213. (catch 'exit
  14214. (while t
  14215. (let ((v (org--property-local-values property literal-nil)))
  14216. (when v
  14217. (setq value
  14218. (concat (mapconcat #'identity (delq nil v) " ")
  14219. (and value " ")
  14220. value)))
  14221. (cond
  14222. ((car v)
  14223. (org-back-to-heading t)
  14224. (move-marker org-entry-property-inherited-from (point))
  14225. (throw 'exit nil))
  14226. ((org-up-heading-safe))
  14227. (t
  14228. (let ((global (org--property-global-value property literal-nil)))
  14229. (cond ((not global))
  14230. (value (setq value (concat global " " value)))
  14231. (t (setq value global))))
  14232. (throw 'exit nil))))))
  14233. (if literal-nil value (org-not-nil value)))))
  14234. (defvar org-property-changed-functions nil
  14235. "Hook called when the value of a property has changed.
  14236. Each hook function should accept two arguments, the name of the property
  14237. and the new value.")
  14238. (defun org-entry-put (pom property value)
  14239. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14240. If the value is nil, it is converted to the empty string. If it
  14241. is not a string, an error is raised. Also raise an error on
  14242. invalid property names.
  14243. PROPERTY can be any regular property (see
  14244. `org-special-properties'). It can also be \"TODO\",
  14245. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14246. For the last two properties, VALUE may have any of the special
  14247. values \"earlier\" and \"later\". The function then increases or
  14248. decreases scheduled or deadline date by one day."
  14249. (cond ((null value) (setq value ""))
  14250. ((not (stringp value)) (error "Properties values should be strings"))
  14251. ((not (org--valid-property-p property))
  14252. (user-error "Invalid property name: \"%s\"" property)))
  14253. (org-with-point-at pom
  14254. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14255. (org-back-to-heading t)
  14256. (org-with-limited-levels (org-back-to-heading t)))
  14257. (let ((beg (point)))
  14258. (cond
  14259. ((equal property "TODO")
  14260. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14261. ((not (member value org-todo-keywords-1))
  14262. (user-error "\"%s\" is not a valid TODO state" value)))
  14263. (org-todo value)
  14264. (org-set-tags nil 'align))
  14265. ((equal property "PRIORITY")
  14266. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14267. (org-set-tags nil 'align))
  14268. ((equal property "SCHEDULED")
  14269. (forward-line)
  14270. (if (and (looking-at-p org-planning-line-re)
  14271. (re-search-forward
  14272. org-scheduled-time-regexp (line-end-position) t))
  14273. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14274. ((string= value "later") (org-timestamp-change 1 'day))
  14275. ((string= value "") (org-schedule '(4)))
  14276. (t (org-schedule nil value)))
  14277. (if (member value '("earlier" "later" ""))
  14278. (call-interactively #'org-schedule)
  14279. (org-schedule nil value))))
  14280. ((equal property "DEADLINE")
  14281. (forward-line)
  14282. (if (and (looking-at-p org-planning-line-re)
  14283. (re-search-forward
  14284. org-deadline-time-regexp (line-end-position) t))
  14285. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14286. ((string= value "later") (org-timestamp-change 1 'day))
  14287. ((string= value "") (org-deadline '(4)))
  14288. (t (org-deadline nil value)))
  14289. (if (member value '("earlier" "later" ""))
  14290. (call-interactively #'org-deadline)
  14291. (org-deadline nil value))))
  14292. ((member property org-special-properties)
  14293. (error "The %s property cannot be set with `org-entry-put'" property))
  14294. (t
  14295. (let* ((range (org-get-property-block beg 'force))
  14296. (end (cdr range))
  14297. (case-fold-search t))
  14298. (goto-char (car range))
  14299. (if (re-search-forward (org-re-property property nil t) end t)
  14300. (progn (delete-region (match-beginning 0) (match-end 0))
  14301. (goto-char (match-beginning 0)))
  14302. (goto-char end)
  14303. (insert "\n")
  14304. (backward-char))
  14305. (insert ":" property ":")
  14306. (when value (insert " " value))
  14307. (org-indent-line)))))
  14308. (run-hook-with-args 'org-property-changed-functions property value)))
  14309. (defun org-buffer-property-keys (&optional specials defaults columns)
  14310. "Get all property keys in the current buffer.
  14311. When SPECIALS is non-nil, also list the special properties that
  14312. reflect things like tags and TODO state.
  14313. When DEFAULTS is non-nil, also include properties that has
  14314. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14315. DESCRIPTION, LOCATION, and LOGGING and others.
  14316. When COLUMNS in non-nil, also include property names given in
  14317. COLUMN formats in the current buffer."
  14318. (let ((case-fold-search t)
  14319. (props (append
  14320. (and specials org-special-properties)
  14321. (and defaults (cons org-effort-property org-default-properties))
  14322. nil)))
  14323. (org-with-wide-buffer
  14324. (goto-char (point-min))
  14325. (while (re-search-forward org-property-start-re nil t)
  14326. (catch :skip
  14327. (let ((range (org-get-property-block)))
  14328. (unless range (throw :skip nil))
  14329. (goto-char (car range))
  14330. (let ((begin (car range))
  14331. (end (cdr range)))
  14332. ;; Make sure that found property block is not located
  14333. ;; before current point, as it would generate an infloop.
  14334. ;; It can happen, for example, in the following
  14335. ;; situation:
  14336. ;;
  14337. ;; * Headline
  14338. ;; :PROPERTIES:
  14339. ;; ...
  14340. ;; :END:
  14341. ;; *************** Inlinetask
  14342. ;; #+BEGIN_EXAMPLE
  14343. ;; :PROPERTIES:
  14344. ;; #+END_EXAMPLE
  14345. ;;
  14346. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  14347. (while (< (point) end)
  14348. (let ((p (progn (looking-at org-property-re)
  14349. (match-string-no-properties 2))))
  14350. ;; Only add true property name, not extension symbol.
  14351. (push (if (not (string-match-p "\\+\\'" p)) p
  14352. (substring p 0 -1))
  14353. props))
  14354. (forward-line))))
  14355. (outline-next-heading)))
  14356. (when columns
  14357. (goto-char (point-min))
  14358. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14359. (let ((element (org-element-at-point)))
  14360. (when (memq (org-element-type element) '(keyword node-property))
  14361. (let ((value (org-element-property :value element))
  14362. (start 0))
  14363. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  14364. \\(?:{[^}]+}\\)?"
  14365. value start)
  14366. (setq start (match-end 0))
  14367. (let ((p (match-string-no-properties 1 value)))
  14368. (unless (member-ignore-case p org-special-properties)
  14369. (push p props))))))))))
  14370. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14371. (defun org-property-values (key)
  14372. "List all non-nil values of property KEY in current buffer."
  14373. (org-with-wide-buffer
  14374. (goto-char (point-min))
  14375. (let ((case-fold-search t)
  14376. (re (org-re-property key))
  14377. values)
  14378. (while (re-search-forward re nil t)
  14379. (push (org-entry-get (point) key) values))
  14380. (delete-dups values))))
  14381. (defun org-insert-property-drawer ()
  14382. "Insert a property drawer into the current entry."
  14383. (org-with-wide-buffer
  14384. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14385. (org-back-to-heading t)
  14386. (org-with-limited-levels (org-back-to-heading t)))
  14387. (forward-line)
  14388. (when (looking-at-p org-planning-line-re) (forward-line))
  14389. (unless (looking-at-p org-property-drawer-re)
  14390. ;; Make sure we start editing a line from current entry, not from
  14391. ;; next one. It prevents extending text properties or overlays
  14392. ;; belonging to the latter.
  14393. (when (bolp) (backward-char))
  14394. (let ((begin (1+ (point)))
  14395. (inhibit-read-only t))
  14396. (insert "\n:PROPERTIES:\n:END:")
  14397. (when (eobp) (insert "\n"))
  14398. (org-indent-region begin (point))))))
  14399. (defun org-insert-drawer (&optional arg drawer)
  14400. "Insert a drawer at point.
  14401. When optional argument ARG is non-nil, insert a property drawer.
  14402. Optional argument DRAWER, when non-nil, is a string representing
  14403. drawer's name. Otherwise, the user is prompted for a name.
  14404. If a region is active, insert the drawer around that region
  14405. instead.
  14406. Point is left between drawer's boundaries."
  14407. (interactive "P")
  14408. (let* ((drawer (if arg "PROPERTIES"
  14409. (or drawer (read-from-minibuffer "Drawer: ")))))
  14410. (cond
  14411. ;; With C-u, fall back on `org-insert-property-drawer'
  14412. (arg (org-insert-property-drawer))
  14413. ;; Check validity of suggested drawer's name.
  14414. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14415. (user-error "Invalid drawer name"))
  14416. ;; With an active region, insert a drawer at point.
  14417. ((not (org-region-active-p))
  14418. (progn
  14419. (unless (bolp) (insert "\n"))
  14420. (insert (format ":%s:\n\n:END:\n" drawer))
  14421. (forward-line -2)))
  14422. ;; Otherwise, insert the drawer at point
  14423. (t
  14424. (let ((rbeg (region-beginning))
  14425. (rend (copy-marker (region-end))))
  14426. (unwind-protect
  14427. (progn
  14428. (goto-char rbeg)
  14429. (beginning-of-line)
  14430. (when (save-excursion
  14431. (re-search-forward org-outline-regexp-bol rend t))
  14432. (user-error "Drawers cannot contain headlines"))
  14433. ;; Position point at the beginning of the first
  14434. ;; non-blank line in region. Insert drawer's opening
  14435. ;; there, then indent it.
  14436. (org-skip-whitespace)
  14437. (beginning-of-line)
  14438. (insert ":" drawer ":\n")
  14439. (forward-line -1)
  14440. (indent-for-tab-command)
  14441. ;; Move point to the beginning of the first blank line
  14442. ;; after the last non-blank line in region. Insert
  14443. ;; drawer's closing, then indent it.
  14444. (goto-char rend)
  14445. (skip-chars-backward " \r\t\n")
  14446. (insert "\n:END:")
  14447. (deactivate-mark t)
  14448. (indent-for-tab-command)
  14449. (unless (eolp) (insert "\n")))
  14450. ;; Clear marker, whatever the outcome of insertion is.
  14451. (set-marker rend nil)))))))
  14452. (defvar org-property-set-functions-alist nil
  14453. "Property set function alist.
  14454. Each entry should have the following format:
  14455. (PROPERTY . READ-FUNCTION)
  14456. The read function will be called with the same argument as
  14457. `org-completing-read'.")
  14458. (defun org-set-property-function (property)
  14459. "Get the function that should be used to set PROPERTY.
  14460. This is computed according to `org-property-set-functions-alist'."
  14461. (or (cdr (assoc property org-property-set-functions-alist))
  14462. 'org-completing-read))
  14463. (defun org-read-property-value (property)
  14464. "Read PROPERTY value from user."
  14465. (let* ((completion-ignore-case t)
  14466. (allowed (org-property-get-allowed-values nil property 'table))
  14467. (cur (org-entry-get nil property))
  14468. (prompt (concat property " value"
  14469. (if (and cur (string-match "\\S-" cur))
  14470. (concat " [" cur "]") "") ": "))
  14471. (set-function (org-set-property-function property))
  14472. (val (if allowed
  14473. (funcall set-function prompt allowed nil
  14474. (not (get-text-property 0 'org-unrestricted
  14475. (caar allowed))))
  14476. (funcall set-function prompt
  14477. (mapcar 'list (org-property-values property))
  14478. nil nil "" nil cur))))
  14479. (org-trim val)))
  14480. (defvar org-last-set-property nil)
  14481. (defvar org-last-set-property-value nil)
  14482. (defun org-read-property-name ()
  14483. "Read a property name."
  14484. (let ((completion-ignore-case t)
  14485. (default-prop (or (and (org-at-property-p)
  14486. (match-string-no-properties 2))
  14487. org-last-set-property)))
  14488. (org-completing-read
  14489. (concat "Property"
  14490. (if default-prop (concat " [" default-prop "]") "")
  14491. ": ")
  14492. (mapcar #'list (org-buffer-property-keys nil t t))
  14493. nil nil nil nil default-prop)))
  14494. (defun org-set-property-and-value (use-last)
  14495. "Allow to set [PROPERTY]: [value] direction from prompt.
  14496. When use-default, don't even ask, just use the last
  14497. \"[PROPERTY]: [value]\" string from the history."
  14498. (interactive "P")
  14499. (let* ((completion-ignore-case t)
  14500. (pv (or (and use-last org-last-set-property-value)
  14501. (org-completing-read
  14502. "Enter a \"[Property]: [value]\" pair: "
  14503. nil nil nil nil nil
  14504. org-last-set-property-value)))
  14505. prop val)
  14506. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14507. (setq prop (match-string 1 pv)
  14508. val (match-string 2 pv))
  14509. (org-set-property prop val))))
  14510. (defun org-set-property (property value)
  14511. "In the current entry, set PROPERTY to VALUE.
  14512. When called interactively, this will prompt for a property name, offering
  14513. completion on existing and default properties. And then it will prompt
  14514. for a value, offering completion either on allowed values (via an inherited
  14515. xxx_ALL property) or on existing values in other instances of this property
  14516. in the current file.
  14517. Throw an error when trying to set a property with an invalid name."
  14518. (interactive (list nil nil))
  14519. (let ((property (or property (org-read-property-name))))
  14520. ;; `org-entry-put' also makes the following check, but this one
  14521. ;; avoids polluting `org-last-set-property' and
  14522. ;; `org-last-set-property-value' needlessly.
  14523. (unless (org--valid-property-p property)
  14524. (user-error "Invalid property name: \"%s\"" property))
  14525. (let ((value (or value (org-read-property-value property)))
  14526. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14527. (setq org-last-set-property property)
  14528. (setq org-last-set-property-value (concat property ": " value))
  14529. ;; Possibly postprocess the inserted value:
  14530. (when fn (setq value (funcall fn value)))
  14531. (unless (equal (org-entry-get nil property) value)
  14532. (org-entry-put nil property value)))))
  14533. (defun org-find-property (property &optional value)
  14534. "Find first entry in buffer that sets PROPERTY.
  14535. When optional argument VALUE is non-nil, only consider an entry
  14536. if it contains PROPERTY set to this value. If PROPERTY should be
  14537. explicitly set to nil, use string \"nil\" for VALUE.
  14538. Return position where the entry begins, or nil if there is no
  14539. such entry. If narrowing is in effect, only search the visible
  14540. part of the buffer."
  14541. (save-excursion
  14542. (goto-char (point-min))
  14543. (let ((case-fold-search t)
  14544. (re (org-re-property property nil (not value) value)))
  14545. (catch 'exit
  14546. (while (re-search-forward re nil t)
  14547. (when (if value (org-at-property-p)
  14548. (org-entry-get (point) property nil t))
  14549. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14550. (defun org-delete-property (property)
  14551. "In the current entry, delete PROPERTY."
  14552. (interactive
  14553. (let* ((completion-ignore-case t)
  14554. (cat (org-entry-get (point) "CATEGORY"))
  14555. (props0 (org-entry-properties nil 'standard))
  14556. (props (if cat props0
  14557. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14558. (prop (if (< 1 (length props))
  14559. (completing-read "Property: " props nil t)
  14560. (caar props))))
  14561. (list prop)))
  14562. (if (not property)
  14563. (message "No property to delete in this entry")
  14564. (org-entry-delete nil property)
  14565. (message "Property \"%s\" deleted" property)))
  14566. (defun org-delete-property-globally (property)
  14567. "Remove PROPERTY globally, from all entries.
  14568. This function ignores narrowing, if any."
  14569. (interactive
  14570. (let* ((completion-ignore-case t)
  14571. (prop (completing-read
  14572. "Globally remove property: "
  14573. (mapcar #'list (org-buffer-property-keys)))))
  14574. (list prop)))
  14575. (org-with-wide-buffer
  14576. (goto-char (point-min))
  14577. (let ((count 0)
  14578. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14579. (while (re-search-forward re nil t)
  14580. (when (org-entry-delete (point) property) (cl-incf count)))
  14581. (message "Property \"%s\" removed from %d entries" property count))))
  14582. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14583. (defun org-compute-property-at-point ()
  14584. "Compute the property at point.
  14585. This looks for an enclosing column format, extracts the operator and
  14586. then applies it to the property in the column format's scope."
  14587. (interactive)
  14588. (unless (org-at-property-p)
  14589. (user-error "Not at a property"))
  14590. (let ((prop (match-string-no-properties 2)))
  14591. (org-columns-get-format-and-top-level)
  14592. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14593. (user-error "No operator defined for property %s" prop))
  14594. (org-columns-compute prop)))
  14595. (defvar org-property-allowed-value-functions nil
  14596. "Hook for functions supplying allowed values for a specific property.
  14597. The functions must take a single argument, the name of the property, and
  14598. return a flat list of allowed values. If \":ETC\" is one of
  14599. the values, this means that these values are intended as defaults for
  14600. completion, but that other values should be allowed too.
  14601. The functions must return nil if they are not responsible for this
  14602. property.")
  14603. (defun org-property-get-allowed-values (pom property &optional table)
  14604. "Get allowed values for the property PROPERTY.
  14605. When TABLE is non-nil, return an alist that can directly be used for
  14606. completion."
  14607. (let (vals)
  14608. (cond
  14609. ((equal property "TODO")
  14610. (setq vals (org-with-point-at pom
  14611. (append org-todo-keywords-1 '("")))))
  14612. ((equal property "PRIORITY")
  14613. (let ((n org-lowest-priority))
  14614. (while (>= n org-highest-priority)
  14615. (push (char-to-string n) vals)
  14616. (setq n (1- n)))))
  14617. ((equal property "CATEGORY"))
  14618. ((member property org-special-properties))
  14619. ((setq vals (run-hook-with-args-until-success
  14620. 'org-property-allowed-value-functions property)))
  14621. (t
  14622. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14623. (when (and vals (string-match "\\S-" vals))
  14624. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14625. (setq vals (mapcar (lambda (x)
  14626. (cond ((stringp x) x)
  14627. ((numberp x) (number-to-string x))
  14628. ((symbolp x) (symbol-name x))
  14629. (t "???")))
  14630. vals)))))
  14631. (when (member ":ETC" vals)
  14632. (setq vals (remove ":ETC" vals))
  14633. (org-add-props (car vals) '(org-unrestricted t)))
  14634. (if table (mapcar 'list vals) vals)))
  14635. (defun org-property-previous-allowed-value (&optional _previous)
  14636. "Switch to the next allowed value for this property."
  14637. (interactive)
  14638. (org-property-next-allowed-value t))
  14639. (defun org-property-next-allowed-value (&optional previous)
  14640. "Switch to the next allowed value for this property."
  14641. (interactive)
  14642. (unless (org-at-property-p)
  14643. (user-error "Not at a property"))
  14644. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14645. (key (match-string 2))
  14646. (value (match-string 3))
  14647. (allowed (or (org-property-get-allowed-values (point) key)
  14648. (and (member value '("[ ]" "[-]" "[X]"))
  14649. '("[ ]" "[X]"))))
  14650. (heading (save-match-data (nth 4 (org-heading-components))))
  14651. nval)
  14652. (unless allowed
  14653. (user-error "Allowed values for this property have not been defined"))
  14654. (when previous (setq allowed (reverse allowed)))
  14655. (when (member value allowed)
  14656. (setq nval (car (cdr (member value allowed)))))
  14657. (setq nval (or nval (car allowed)))
  14658. (when (equal nval value)
  14659. (user-error "Only one allowed value for this property"))
  14660. (org-at-property-p)
  14661. (replace-match (concat " :" key ": " nval) t t)
  14662. (org-indent-line)
  14663. (beginning-of-line 1)
  14664. (skip-chars-forward " \t")
  14665. (when (equal prop org-effort-property)
  14666. (org-refresh-property
  14667. '((effort . identity)
  14668. (effort-minutes . org-duration-to-minutes))
  14669. nval)
  14670. (when (string= org-clock-current-task heading)
  14671. (setq org-clock-effort nval)
  14672. (org-clock-update-mode-line)))
  14673. (run-hook-with-args 'org-property-changed-functions key nval)))
  14674. (defun org-find-olp (path &optional this-buffer)
  14675. "Return a marker pointing to the entry at outline path OLP.
  14676. If anything goes wrong, throw an error.
  14677. You can wrap this call to catch the error like this:
  14678. (condition-case msg
  14679. (org-mobile-locate-entry (match-string 4))
  14680. (error (nth 1 msg)))
  14681. The return value will then be either a string with the error message,
  14682. or a marker if everything is OK.
  14683. If THIS-BUFFER is set, the outline path does not contain a file,
  14684. only headings."
  14685. (let* ((file (if this-buffer buffer-file-name (pop path)))
  14686. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  14687. (level 1)
  14688. (lmin 1)
  14689. (lmax 1)
  14690. end found flevel)
  14691. (unless buffer (error "File not found :%s" file))
  14692. (with-current-buffer buffer
  14693. (unless (derived-mode-p 'org-mode)
  14694. (error "Buffer %s needs to be in Org mode" buffer))
  14695. (org-with-wide-buffer
  14696. (goto-char (point-min))
  14697. (dolist (heading path)
  14698. (let ((re (format org-complex-heading-regexp-format
  14699. (regexp-quote heading)))
  14700. (cnt 0))
  14701. (while (re-search-forward re end t)
  14702. (setq level (- (match-end 1) (match-beginning 1)))
  14703. (when (and (>= level lmin) (<= level lmax))
  14704. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  14705. (when (= cnt 0)
  14706. (error "Heading not found on level %d: %s" lmax heading))
  14707. (when (> cnt 1)
  14708. (error "Heading not unique on level %d: %s" lmax heading))
  14709. (goto-char found)
  14710. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  14711. (setq end (save-excursion (org-end-of-subtree t t)))))
  14712. (when (org-at-heading-p)
  14713. (point-marker))))))
  14714. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  14715. "Find node HEADING in BUFFER.
  14716. Return a marker to the heading if it was found, or nil if not.
  14717. If POS-ONLY is set, return just the position instead of a marker.
  14718. The heading text must match exact, but it may have a TODO keyword,
  14719. a priority cookie and tags in the standard locations."
  14720. (with-current-buffer (or buffer (current-buffer))
  14721. (org-with-wide-buffer
  14722. (goto-char (point-min))
  14723. (let (case-fold-search)
  14724. (when (re-search-forward
  14725. (format org-complex-heading-regexp-format
  14726. (regexp-quote heading)) nil t)
  14727. (if pos-only
  14728. (match-beginning 0)
  14729. (move-marker (make-marker) (match-beginning 0))))))))
  14730. (defun org-find-exact-heading-in-directory (heading &optional dir)
  14731. "Find Org node headline HEADING in all .org files in directory DIR.
  14732. When the target headline is found, return a marker to this location."
  14733. (let ((files (directory-files (or dir default-directory)
  14734. t "\\`[^.#].*\\.org\\'"))
  14735. visiting m buffer)
  14736. (catch 'found
  14737. (dolist (file files)
  14738. (message "trying %s" file)
  14739. (setq visiting (org-find-base-buffer-visiting file))
  14740. (setq buffer (or visiting (find-file-noselect file)))
  14741. (setq m (org-find-exact-headline-in-buffer
  14742. heading buffer))
  14743. (when (and (not m) (not visiting)) (kill-buffer buffer))
  14744. (and m (throw 'found m))))))
  14745. (defun org-find-entry-with-id (ident)
  14746. "Locate the entry that contains the ID property with exact value IDENT.
  14747. IDENT can be a string, a symbol or a number, this function will search for
  14748. the string representation of it.
  14749. Return the position where this entry starts, or nil if there is no such entry."
  14750. (interactive "sID: ")
  14751. (let ((id (cond
  14752. ((stringp ident) ident)
  14753. ((symbolp ident) (symbol-name ident))
  14754. ((numberp ident) (number-to-string ident))
  14755. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  14756. (org-with-wide-buffer (org-find-property "ID" id))))
  14757. ;;;; Timestamps
  14758. (defvar org-last-changed-timestamp nil)
  14759. (defvar org-last-inserted-timestamp nil
  14760. "The last time stamp inserted with `org-insert-time-stamp'.")
  14761. (defun org-time-stamp (arg &optional inactive)
  14762. "Prompt for a date/time and insert a time stamp.
  14763. If the user specifies a time like HH:MM or if this command is
  14764. called with at least one prefix argument, the time stamp contains
  14765. the date and the time. Otherwise, only the date is included.
  14766. All parts of a date not specified by the user are filled in from
  14767. the timestamp at point, if any, or the current date/time
  14768. otherwise.
  14769. If there is already a timestamp at the cursor, it is replaced.
  14770. With two universal prefix arguments, insert an active timestamp
  14771. with the current time without prompting the user.
  14772. When called from lisp, the timestamp is inactive if INACTIVE is
  14773. non-nil."
  14774. (interactive "P")
  14775. (let* ((ts (cond
  14776. ((org-at-date-range-p t)
  14777. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  14778. ((org-at-timestamp-p 'lax) (match-string 0))))
  14779. ;; Default time is either the timestamp at point or today.
  14780. ;; When entering a range, only the range start is considered.
  14781. (default-time (if (not ts) (current-time)
  14782. (apply #'encode-time (org-parse-time-string ts))))
  14783. (default-input (and ts (org-get-compact-tod ts)))
  14784. (repeater (and ts
  14785. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  14786. (match-string 0 ts)))
  14787. org-time-was-given
  14788. org-end-time-was-given
  14789. (time
  14790. (and (if (equal arg '(16)) (current-time)
  14791. ;; Preserve `this-command' and `last-command'.
  14792. (let ((this-command this-command)
  14793. (last-command last-command))
  14794. (org-read-date
  14795. arg 'totime nil nil default-time default-input
  14796. inactive))))))
  14797. (cond
  14798. ((and ts
  14799. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  14800. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  14801. (insert "--")
  14802. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  14803. (ts
  14804. ;; Make sure we're on a timestamp. When in the middle of a date
  14805. ;; range, move arbitrarily to range end.
  14806. (unless (org-at-timestamp-p 'lax)
  14807. (skip-chars-forward "-")
  14808. (org-at-timestamp-p 'lax))
  14809. (replace-match "")
  14810. (setq org-last-changed-timestamp
  14811. (org-insert-time-stamp
  14812. time (or org-time-was-given arg)
  14813. inactive nil nil (list org-end-time-was-given)))
  14814. (when repeater
  14815. (backward-char)
  14816. (insert " " repeater)
  14817. (setq org-last-changed-timestamp
  14818. (concat (substring org-last-inserted-timestamp 0 -1)
  14819. " " repeater ">")))
  14820. (message "Timestamp updated"))
  14821. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  14822. (t (org-insert-time-stamp
  14823. time (or org-time-was-given arg) inactive nil nil
  14824. (list org-end-time-was-given))))))
  14825. ;; FIXME: can we use this for something else, like computing time differences?
  14826. (defun org-get-compact-tod (s)
  14827. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  14828. (let* ((t1 (match-string 1 s))
  14829. (h1 (string-to-number (match-string 2 s)))
  14830. (m1 (string-to-number (match-string 3 s)))
  14831. (t2 (and (match-end 4) (match-string 5 s)))
  14832. (h2 (and t2 (string-to-number (match-string 6 s))))
  14833. (m2 (and t2 (string-to-number (match-string 7 s))))
  14834. dh dm)
  14835. (if (not t2)
  14836. t1
  14837. (setq dh (- h2 h1) dm (- m2 m1))
  14838. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  14839. (concat t1 "+" (number-to-string dh)
  14840. (and (/= 0 dm) (format ":%02d" dm)))))))
  14841. (defun org-time-stamp-inactive (&optional arg)
  14842. "Insert an inactive time stamp.
  14843. An inactive time stamp is enclosed in square brackets instead of angle
  14844. brackets. It is inactive in the sense that it does not trigger agenda entries,
  14845. does not link to the calendar and cannot be changed with the S-cursor keys.
  14846. So these are more for recording a certain time/date."
  14847. (interactive "P")
  14848. (org-time-stamp arg 'inactive))
  14849. (defvar org-date-ovl (make-overlay 1 1))
  14850. (overlay-put org-date-ovl 'face 'org-date-selected)
  14851. (delete-overlay org-date-ovl)
  14852. (defvar org-ans1) ; dynamically scoped parameter
  14853. (defvar org-ans2) ; dynamically scoped parameter
  14854. (defvar org-plain-time-of-day-regexp) ; defined below
  14855. (defvar org-overriding-default-time nil) ; dynamically scoped
  14856. (defvar org-read-date-overlay nil)
  14857. (defvar org-dcst nil) ; dynamically scoped
  14858. (defvar org-read-date-history nil)
  14859. (defvar org-read-date-final-answer nil)
  14860. (defvar org-read-date-analyze-futurep nil)
  14861. (defvar org-read-date-analyze-forced-year nil)
  14862. (defvar org-read-date-inactive)
  14863. (defvar org-read-date-minibuffer-local-map
  14864. (let* ((map (make-sparse-keymap)))
  14865. (set-keymap-parent map minibuffer-local-map)
  14866. (org-defkey map (kbd ".")
  14867. (lambda () (interactive)
  14868. ;; Are we at the beginning of the prompt?
  14869. (if (looking-back "^[^:]+: "
  14870. (let ((inhibit-field-text-motion t))
  14871. (line-beginning-position)))
  14872. (org-eval-in-calendar '(calendar-goto-today))
  14873. (insert "."))))
  14874. (org-defkey map (kbd "C-.")
  14875. (lambda () (interactive)
  14876. (org-eval-in-calendar '(calendar-goto-today))))
  14877. (org-defkey map [(meta shift left)]
  14878. (lambda () (interactive)
  14879. (org-eval-in-calendar '(calendar-backward-month 1))))
  14880. (org-defkey map [(meta shift right)]
  14881. (lambda () (interactive)
  14882. (org-eval-in-calendar '(calendar-forward-month 1))))
  14883. (org-defkey map [(meta shift up)]
  14884. (lambda () (interactive)
  14885. (org-eval-in-calendar '(calendar-backward-year 1))))
  14886. (org-defkey map [(meta shift down)]
  14887. (lambda () (interactive)
  14888. (org-eval-in-calendar '(calendar-forward-year 1))))
  14889. (org-defkey map [?\e (shift left)]
  14890. (lambda () (interactive)
  14891. (org-eval-in-calendar '(calendar-backward-month 1))))
  14892. (org-defkey map [?\e (shift right)]
  14893. (lambda () (interactive)
  14894. (org-eval-in-calendar '(calendar-forward-month 1))))
  14895. (org-defkey map [?\e (shift up)]
  14896. (lambda () (interactive)
  14897. (org-eval-in-calendar '(calendar-backward-year 1))))
  14898. (org-defkey map [?\e (shift down)]
  14899. (lambda () (interactive)
  14900. (org-eval-in-calendar '(calendar-forward-year 1))))
  14901. (org-defkey map [(shift up)]
  14902. (lambda () (interactive)
  14903. (org-eval-in-calendar '(calendar-backward-week 1))))
  14904. (org-defkey map [(shift down)]
  14905. (lambda () (interactive)
  14906. (org-eval-in-calendar '(calendar-forward-week 1))))
  14907. (org-defkey map [(shift left)]
  14908. (lambda () (interactive)
  14909. (org-eval-in-calendar '(calendar-backward-day 1))))
  14910. (org-defkey map [(shift right)]
  14911. (lambda () (interactive)
  14912. (org-eval-in-calendar '(calendar-forward-day 1))))
  14913. (org-defkey map "!"
  14914. (lambda () (interactive)
  14915. (org-eval-in-calendar '(diary-view-entries))
  14916. (message "")))
  14917. (org-defkey map ">"
  14918. (lambda () (interactive)
  14919. (org-eval-in-calendar '(calendar-scroll-left 1))))
  14920. (org-defkey map "<"
  14921. (lambda () (interactive)
  14922. (org-eval-in-calendar '(calendar-scroll-right 1))))
  14923. (org-defkey map "\C-v"
  14924. (lambda () (interactive)
  14925. (org-eval-in-calendar
  14926. '(calendar-scroll-left-three-months 1))))
  14927. (org-defkey map "\M-v"
  14928. (lambda () (interactive)
  14929. (org-eval-in-calendar
  14930. '(calendar-scroll-right-three-months 1))))
  14931. map)
  14932. "Keymap for minibuffer commands when using `org-read-date'.")
  14933. (defvar org-def)
  14934. (defvar org-defdecode)
  14935. (defvar org-with-time)
  14936. (defvar calendar-setup) ; Dynamically scoped.
  14937. (defun org-read-date (&optional with-time to-time from-string prompt
  14938. default-time default-input inactive)
  14939. "Read a date, possibly a time, and make things smooth for the user.
  14940. The prompt will suggest to enter an ISO date, but you can also enter anything
  14941. which will at least partially be understood by `parse-time-string'.
  14942. Unrecognized parts of the date will default to the current day, month, year,
  14943. hour and minute. If this command is called to replace a timestamp at point,
  14944. or to enter the second timestamp of a range, the default time is taken
  14945. from the existing stamp. Furthermore, the command prefers the future,
  14946. so if you are giving a date where the year is not given, and the day-month
  14947. combination is already past in the current year, it will assume you
  14948. mean next year. For details, see the manual. A few examples:
  14949. 3-2-5 --> 2003-02-05
  14950. feb 15 --> currentyear-02-15
  14951. 2/15 --> currentyear-02-15
  14952. sep 12 9 --> 2009-09-12
  14953. 12:45 --> today 12:45
  14954. 22 sept 0:34 --> currentyear-09-22 0:34
  14955. 12 --> currentyear-currentmonth-12
  14956. Fri --> nearest Friday after today
  14957. -Tue --> last Tuesday
  14958. etc.
  14959. Furthermore you can specify a relative date by giving, as the *first* thing
  14960. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  14961. change in days weeks, months, years.
  14962. With a single plus or minus, the date is relative to today. With a double
  14963. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  14964. +4d --> four days from today
  14965. +4 --> same as above
  14966. +2w --> two weeks from today
  14967. ++5 --> five days from default date
  14968. The function understands only English month and weekday abbreviations.
  14969. While prompting, a calendar is popped up - you can also select the
  14970. date with the mouse (button 1). The calendar shows a period of three
  14971. months. To scroll it to other months, use the keys `>' and `<'.
  14972. If you don't like the calendar, turn it off with
  14973. (setq org-read-date-popup-calendar nil)
  14974. With optional argument TO-TIME, the date will immediately be converted
  14975. to an internal time.
  14976. With an optional argument WITH-TIME, the prompt will suggest to
  14977. also insert a time. Note that when WITH-TIME is not set, you can
  14978. still enter a time, and this function will inform the calling routine
  14979. about this change. The calling routine may then choose to change the
  14980. format used to insert the time stamp into the buffer to include the time.
  14981. With optional argument FROM-STRING, read from this string instead from
  14982. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  14983. the time/date that is used for everything that is not specified by the
  14984. user."
  14985. (require 'parse-time)
  14986. (let* ((org-with-time with-time)
  14987. (org-time-stamp-rounding-minutes
  14988. (if (equal org-with-time '(16))
  14989. '(0 0)
  14990. org-time-stamp-rounding-minutes))
  14991. (org-dcst org-display-custom-times)
  14992. (ct (org-current-time))
  14993. (org-def (or org-overriding-default-time default-time ct))
  14994. (org-defdecode (decode-time org-def))
  14995. (cur-frame (selected-frame))
  14996. (mouse-autoselect-window nil) ; Don't let the mouse jump
  14997. (calendar-setup
  14998. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  14999. (calendar-move-hook nil)
  15000. (calendar-view-diary-initially-flag nil)
  15001. (calendar-view-holidays-initially-flag nil)
  15002. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15003. ;; Rationalize `org-def' and `org-defdecode', if required.
  15004. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15005. (setf (nth 2 org-defdecode) -1)
  15006. (setf (nth 1 org-defdecode) 59)
  15007. (setq org-def (apply #'encode-time org-defdecode))
  15008. (setq org-defdecode (decode-time org-def)))
  15009. (let* ((timestr (format-time-string
  15010. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15011. org-def))
  15012. (prompt (concat (if prompt (concat prompt " ") "")
  15013. (format "Date+time [%s]: " timestr))))
  15014. (cond
  15015. (from-string (setq ans from-string))
  15016. (org-read-date-popup-calendar
  15017. (save-excursion
  15018. (save-window-excursion
  15019. (calendar)
  15020. (when (eq calendar-setup 'calendar-only)
  15021. (setq cal-frame
  15022. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15023. (select-frame cal-frame))
  15024. (org-eval-in-calendar '(setq cursor-type nil) t)
  15025. (unwind-protect
  15026. (progn
  15027. (calendar-forward-day (- (time-to-days org-def)
  15028. (calendar-absolute-from-gregorian
  15029. (calendar-current-date))))
  15030. (org-eval-in-calendar nil t)
  15031. (let* ((old-map (current-local-map))
  15032. (map (copy-keymap calendar-mode-map))
  15033. (minibuffer-local-map
  15034. (copy-keymap org-read-date-minibuffer-local-map)))
  15035. (org-defkey map (kbd "RET") 'org-calendar-select)
  15036. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15037. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15038. (unwind-protect
  15039. (progn
  15040. (use-local-map map)
  15041. (setq org-read-date-inactive inactive)
  15042. (add-hook 'post-command-hook 'org-read-date-display)
  15043. (setq org-ans0
  15044. (read-string prompt
  15045. default-input
  15046. 'org-read-date-history
  15047. nil))
  15048. ;; org-ans0: from prompt
  15049. ;; org-ans1: from mouse click
  15050. ;; org-ans2: from calendar motion
  15051. (setq ans
  15052. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15053. (remove-hook 'post-command-hook 'org-read-date-display)
  15054. (use-local-map old-map)
  15055. (when org-read-date-overlay
  15056. (delete-overlay org-read-date-overlay)
  15057. (setq org-read-date-overlay nil)))))
  15058. (bury-buffer "*Calendar*")
  15059. (when cal-frame
  15060. (delete-frame cal-frame)
  15061. (select-frame-set-input-focus cur-frame))))))
  15062. (t ; Naked prompt only
  15063. (unwind-protect
  15064. (setq ans (read-string prompt default-input
  15065. 'org-read-date-history timestr))
  15066. (when org-read-date-overlay
  15067. (delete-overlay org-read-date-overlay)
  15068. (setq org-read-date-overlay nil))))))
  15069. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15070. (when org-read-date-analyze-forced-year
  15071. (message "Year was forced into %s"
  15072. (if org-read-date-force-compatible-dates
  15073. "compatible range (1970-2037)"
  15074. "range representable on this machine"))
  15075. (ding))
  15076. ;; One round trip to get rid of 34th of August and stuff like that....
  15077. (setq final (decode-time (apply 'encode-time final)))
  15078. (setq org-read-date-final-answer ans)
  15079. (if to-time
  15080. (apply 'encode-time final)
  15081. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15082. (format "%04d-%02d-%02d %02d:%02d"
  15083. (nth 5 final) (nth 4 final) (nth 3 final)
  15084. (nth 2 final) (nth 1 final))
  15085. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15086. (defun org-read-date-display ()
  15087. "Display the current date prompt interpretation in the minibuffer."
  15088. (when org-read-date-display-live
  15089. (when org-read-date-overlay
  15090. (delete-overlay org-read-date-overlay))
  15091. (when (minibufferp (current-buffer))
  15092. (save-excursion
  15093. (end-of-line 1)
  15094. (while (not (equal (buffer-substring
  15095. (max (point-min) (- (point) 4)) (point))
  15096. " "))
  15097. (insert " ")))
  15098. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15099. " " (or org-ans1 org-ans2)))
  15100. (org-end-time-was-given nil)
  15101. (f (org-read-date-analyze ans org-def org-defdecode))
  15102. (fmts (if org-dcst
  15103. org-time-stamp-custom-formats
  15104. org-time-stamp-formats))
  15105. (fmt (if (or org-with-time
  15106. (and (boundp 'org-time-was-given) org-time-was-given))
  15107. (cdr fmts)
  15108. (car fmts)))
  15109. (txt (format-time-string fmt (apply 'encode-time f)))
  15110. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15111. (txt (concat "=> " txt)))
  15112. (when (and org-end-time-was-given
  15113. (string-match org-plain-time-of-day-regexp txt))
  15114. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15115. org-end-time-was-given
  15116. (substring txt (match-end 0)))))
  15117. (when org-read-date-analyze-futurep
  15118. (setq txt (concat txt " (=>F)")))
  15119. (setq org-read-date-overlay
  15120. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15121. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15122. (defun org-read-date-analyze (ans def defdecode)
  15123. "Analyze the combined answer of the date prompt."
  15124. ;; FIXME: cleanup and comment
  15125. ;; Pass `current-time' result to `decode-time' (instead of calling
  15126. ;; without arguments) so that only `current-time' has to be
  15127. ;; overridden in tests.
  15128. (let ((org-def def)
  15129. (org-defdecode defdecode)
  15130. (nowdecode (decode-time (current-time)))
  15131. delta deltan deltaw deltadef year month day
  15132. hour minute second wday pm h2 m2 tl wday1
  15133. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15134. (setq org-read-date-analyze-futurep nil
  15135. org-read-date-analyze-forced-year nil)
  15136. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15137. (setq ans "+0"))
  15138. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15139. (setq ans (replace-match "" t t ans)
  15140. deltan (car delta)
  15141. deltaw (nth 1 delta)
  15142. deltadef (nth 2 delta)))
  15143. ;; Check if there is an iso week date in there. If yes, store the
  15144. ;; info and postpone interpreting it until the rest of the parsing
  15145. ;; is done.
  15146. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15147. (setq iso-year (when (match-end 1)
  15148. (org-small-year-to-year
  15149. (string-to-number (match-string 1 ans))))
  15150. iso-weekday (when (match-end 3)
  15151. (string-to-number (match-string 3 ans)))
  15152. iso-week (string-to-number (match-string 2 ans)))
  15153. (setq ans (replace-match "" t t ans)))
  15154. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15155. (when (string-match
  15156. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15157. (setq year (if (match-end 2)
  15158. (string-to-number (match-string 2 ans))
  15159. (progn (setq kill-year t)
  15160. (string-to-number (format-time-string "%Y"))))
  15161. month (string-to-number (match-string 3 ans))
  15162. day (string-to-number (match-string 4 ans)))
  15163. (setq year (org-small-year-to-year year))
  15164. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15165. t nil ans)))
  15166. ;; Help matching dotted european dates
  15167. (when (string-match
  15168. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15169. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15170. (setq kill-year t)
  15171. (string-to-number (format-time-string "%Y")))
  15172. day (string-to-number (match-string 1 ans))
  15173. month (string-to-number (match-string 2 ans))
  15174. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15175. t nil ans)))
  15176. ;; Help matching american dates, like 5/30 or 5/30/7
  15177. (when (string-match
  15178. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15179. (setq year (if (match-end 4)
  15180. (string-to-number (match-string 4 ans))
  15181. (progn (setq kill-year t)
  15182. (string-to-number (format-time-string "%Y"))))
  15183. month (string-to-number (match-string 1 ans))
  15184. day (string-to-number (match-string 2 ans)))
  15185. (setq year (org-small-year-to-year year))
  15186. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15187. t nil ans)))
  15188. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15189. ;; If there is a time with am/pm, and *no* time without it, we convert
  15190. ;; so that matching will be successful.
  15191. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  15192. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15193. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15194. (setq hour (string-to-number (match-string 1 ans))
  15195. minute (if (match-end 3)
  15196. (string-to-number (match-string 3 ans))
  15197. 0)
  15198. pm (equal ?p
  15199. (string-to-char (downcase (match-string 4 ans)))))
  15200. (if (and (= hour 12) (not pm))
  15201. (setq hour 0)
  15202. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15203. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15204. t t ans))))
  15205. ;; Check if a time range is given as a duration
  15206. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15207. (setq hour (string-to-number (match-string 1 ans))
  15208. h2 (+ hour (string-to-number (match-string 3 ans)))
  15209. minute (string-to-number (match-string 2 ans))
  15210. m2 (+ minute (if (match-end 5) (string-to-number
  15211. (match-string 5 ans))0)))
  15212. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15213. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15214. t t ans)))
  15215. ;; Check if there is a time range
  15216. (when (boundp 'org-end-time-was-given)
  15217. (setq org-time-was-given nil)
  15218. (when (and (string-match org-plain-time-of-day-regexp ans)
  15219. (match-end 8))
  15220. (setq org-end-time-was-given (match-string 8 ans))
  15221. (setq ans (concat (substring ans 0 (match-beginning 7))
  15222. (substring ans (match-end 7))))))
  15223. (setq tl (parse-time-string ans)
  15224. day (or (nth 3 tl) (nth 3 org-defdecode))
  15225. month
  15226. (cond ((nth 4 tl))
  15227. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15228. ;; Day was specified. Make sure DAY+MONTH
  15229. ;; combination happens in the future.
  15230. ((nth 3 tl)
  15231. (setq futurep t)
  15232. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15233. (nth 4 nowdecode)))
  15234. (t (nth 4 org-defdecode)))
  15235. year
  15236. (cond ((and (not kill-year) (nth 5 tl)))
  15237. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15238. ;; Month was guessed in the future and is at least
  15239. ;; equal to NOWDECODE's. Fix year accordingly.
  15240. (futurep
  15241. (if (or (> month (nth 4 nowdecode))
  15242. (>= day (nth 3 nowdecode)))
  15243. (nth 5 nowdecode)
  15244. (1+ (nth 5 nowdecode))))
  15245. ;; Month was specified. Make sure MONTH+YEAR
  15246. ;; combination happens in the future.
  15247. ((nth 4 tl)
  15248. (setq futurep t)
  15249. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15250. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15251. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15252. (t (nth 5 nowdecode))))
  15253. (t (nth 5 org-defdecode)))
  15254. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15255. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15256. second (or (nth 0 tl) 0)
  15257. wday (nth 6 tl))
  15258. (when (and (eq org-read-date-prefer-future 'time)
  15259. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15260. (equal day (nth 3 nowdecode))
  15261. (equal month (nth 4 nowdecode))
  15262. (equal year (nth 5 nowdecode))
  15263. (nth 2 tl)
  15264. (or (< (nth 2 tl) (nth 2 nowdecode))
  15265. (and (= (nth 2 tl) (nth 2 nowdecode))
  15266. (nth 1 tl)
  15267. (< (nth 1 tl) (nth 1 nowdecode)))))
  15268. (setq day (1+ day)
  15269. futurep t))
  15270. ;; Special date definitions below
  15271. (cond
  15272. (iso-week
  15273. ;; There was an iso week
  15274. (require 'cal-iso)
  15275. (setq futurep nil)
  15276. (setq year (or iso-year year)
  15277. day (or iso-weekday wday 1)
  15278. wday nil ; to make sure that the trigger below does not match
  15279. iso-date (calendar-gregorian-from-absolute
  15280. (calendar-iso-to-absolute
  15281. (list iso-week day year))))
  15282. ; FIXME: Should we also push ISO weeks into the future?
  15283. ; (when (and org-read-date-prefer-future
  15284. ; (not iso-year)
  15285. ; (< (calendar-absolute-from-gregorian iso-date)
  15286. ; (time-to-days (current-time))))
  15287. ; (setq year (1+ year)
  15288. ; iso-date (calendar-gregorian-from-absolute
  15289. ; (calendar-iso-to-absolute
  15290. ; (list iso-week day year)))))
  15291. (setq month (car iso-date)
  15292. year (nth 2 iso-date)
  15293. day (nth 1 iso-date)))
  15294. (deltan
  15295. (setq futurep nil)
  15296. (unless deltadef
  15297. ;; Pass `current-time' result to `decode-time' (instead of
  15298. ;; calling without arguments) so that only `current-time' has
  15299. ;; to be overridden in tests.
  15300. (let ((now (decode-time (current-time))))
  15301. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15302. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15303. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15304. ((equal deltaw "m") (setq month (+ month deltan)))
  15305. ((equal deltaw "y") (setq year (+ year deltan)))))
  15306. ((and wday (not (nth 3 tl)))
  15307. ;; Weekday was given, but no day, so pick that day in the week
  15308. ;; on or after the derived date.
  15309. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15310. (unless (equal wday wday1)
  15311. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15312. (when (and (boundp 'org-time-was-given)
  15313. (nth 2 tl))
  15314. (setq org-time-was-given t))
  15315. (when (< year 100) (setq year (+ 2000 year)))
  15316. ;; Check of the date is representable
  15317. (if org-read-date-force-compatible-dates
  15318. (progn
  15319. (when (< year 1970)
  15320. (setq year 1970 org-read-date-analyze-forced-year t))
  15321. (when (> year 2037)
  15322. (setq year 2037 org-read-date-analyze-forced-year t)))
  15323. (condition-case nil
  15324. (ignore (encode-time second minute hour day month year))
  15325. (error
  15326. (setq year (nth 5 org-defdecode))
  15327. (setq org-read-date-analyze-forced-year t))))
  15328. (setq org-read-date-analyze-futurep futurep)
  15329. (list second minute hour day month year)))
  15330. (defvar parse-time-weekdays)
  15331. (defun org-read-date-get-relative (s today default)
  15332. "Check string S for special relative date string.
  15333. TODAY and DEFAULT are internal times, for today and for a default.
  15334. Return shift list (N what def-flag)
  15335. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15336. N is the number of WHATs to shift.
  15337. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15338. the DEFAULT date rather than TODAY."
  15339. (require 'parse-time)
  15340. (when (and
  15341. (string-match
  15342. (concat
  15343. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15344. "\\([0-9]+\\)?"
  15345. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15346. "\\([ \t]\\|$\\)") s)
  15347. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15348. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15349. (string-to-char (substring (match-string 1 s) -1))
  15350. ?+))
  15351. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15352. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15353. (what (if (match-end 3) (match-string 3 s) "d"))
  15354. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15355. (date (if rel default today))
  15356. (wday (nth 6 (decode-time date)))
  15357. delta)
  15358. (if wday1
  15359. (progn
  15360. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15361. (when (= delta 0) (setq delta 7))
  15362. (when (= dir ?-)
  15363. (setq delta (- delta 7))
  15364. (when (= delta 0) (setq delta -7)))
  15365. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15366. (list delta "d" rel))
  15367. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15368. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15369. "Turn a user-specified date into the internal representation.
  15370. The internal representation needed by the calendar is (month day year).
  15371. This is a wrapper to handle the brain-dead convention in calendar that
  15372. user function argument order change dependent on argument order."
  15373. (pcase calendar-date-style
  15374. (`american (list arg1 arg2 arg3))
  15375. (`european (list arg2 arg1 arg3))
  15376. (`iso (list arg2 arg3 arg1))))
  15377. (defun org-eval-in-calendar (form &optional keepdate)
  15378. "Eval FORM in the calendar window and return to current window.
  15379. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15380. (let ((sf (selected-frame))
  15381. (sw (selected-window)))
  15382. (select-window (get-buffer-window "*Calendar*" t))
  15383. (eval form)
  15384. (when (and (not keepdate) (calendar-cursor-to-date))
  15385. (let* ((date (calendar-cursor-to-date))
  15386. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15387. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15388. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15389. (select-window sw)
  15390. (select-frame-set-input-focus sf)))
  15391. (defun org-calendar-select ()
  15392. "Return to `org-read-date' with the date currently selected.
  15393. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15394. (interactive)
  15395. (when (calendar-cursor-to-date)
  15396. (let* ((date (calendar-cursor-to-date))
  15397. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15398. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15399. (when (active-minibuffer-window) (exit-minibuffer))))
  15400. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15401. "Insert a date stamp for the date given by the internal TIME.
  15402. See `format-time-string' for the format of TIME.
  15403. WITH-HM means use the stamp format that includes the time of the day.
  15404. INACTIVE means use square brackets instead of angular ones, so that the
  15405. stamp will not contribute to the agenda.
  15406. PRE and POST are optional strings to be inserted before and after the
  15407. stamp.
  15408. The command returns the inserted time stamp."
  15409. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15410. stamp)
  15411. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15412. (insert-before-markers (or pre ""))
  15413. (when (listp extra)
  15414. (setq extra (car extra))
  15415. (if (and (stringp extra)
  15416. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15417. (setq extra (format "-%02d:%02d"
  15418. (string-to-number (match-string 1 extra))
  15419. (string-to-number (match-string 2 extra))))
  15420. (setq extra nil)))
  15421. (when extra
  15422. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15423. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15424. (insert-before-markers (or post ""))
  15425. (setq org-last-inserted-timestamp stamp)))
  15426. (defun org-toggle-time-stamp-overlays ()
  15427. "Toggle the use of custom time stamp formats."
  15428. (interactive)
  15429. (setq org-display-custom-times (not org-display-custom-times))
  15430. (unless org-display-custom-times
  15431. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15432. (while (setq p (next-single-property-change p 'display))
  15433. (when (and (get-text-property p 'display)
  15434. (eq (get-text-property p 'face) 'org-date))
  15435. (remove-text-properties
  15436. p (setq p (next-single-property-change p 'display))
  15437. '(display t))))
  15438. (set-buffer-modified-p bmp)))
  15439. (org-restart-font-lock)
  15440. (setq org-table-may-need-update t)
  15441. (if org-display-custom-times
  15442. (message "Time stamps are overlaid with custom format")
  15443. (message "Time stamp overlays removed")))
  15444. (defun org-display-custom-time (beg end)
  15445. "Overlay modified time stamp format over timestamp between BEG and END."
  15446. (let* ((ts (buffer-substring beg end))
  15447. t1 with-hm tf time str (off 0))
  15448. (save-match-data
  15449. (setq t1 (org-parse-time-string ts t))
  15450. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15451. (setq off (- (match-end 0) (match-beginning 0)))))
  15452. (setq end (- end off))
  15453. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  15454. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15455. time (org-fix-decoded-time t1)
  15456. str (org-add-props
  15457. (format-time-string
  15458. (substring tf 1 -1) (apply 'encode-time time))
  15459. nil 'mouse-face 'highlight))
  15460. (put-text-property beg end 'display str)))
  15461. (defun org-fix-decoded-time (time)
  15462. "Set 0 instead of nil for the first 6 elements of time.
  15463. Don't touch the rest."
  15464. (let ((n 0))
  15465. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15466. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15467. "Difference between TIMESTAMP-STRING and now in days.
  15468. If SECONDS is non-nil, return the difference in seconds."
  15469. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15470. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15471. (funcall fdiff (current-time)))))
  15472. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15473. "Is the time in TIMESTAMP-STRING close to the current date?"
  15474. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15475. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15476. (not (org-entry-is-done-p))))
  15477. (defun org-get-wdays (ts &optional delay zero-delay)
  15478. "Get the deadline lead time appropriate for timestring TS.
  15479. When DELAY is non-nil, get the delay time for scheduled items
  15480. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15481. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15482. don't try to find the delay cookie in the scheduled timestamp."
  15483. (let ((tv (if delay org-scheduled-delay-days
  15484. org-deadline-warning-days)))
  15485. (cond
  15486. ((or (and delay (< tv 0))
  15487. (and delay zero-delay (<= tv 0))
  15488. (and (not delay) (<= tv 0)))
  15489. ;; Enforce this value no matter what
  15490. (- tv))
  15491. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15492. ;; lead time is specified.
  15493. (floor (* (string-to-number (match-string 1 ts))
  15494. (cdr (assoc (match-string 2 ts)
  15495. '(("d" . 1) ("w" . 7)
  15496. ("m" . 30.4) ("y" . 365.25)
  15497. ("h" . 0.041667)))))))
  15498. ;; go for the default.
  15499. (t tv))))
  15500. (defun org-calendar-select-mouse (ev)
  15501. "Return to `org-read-date' with the date currently selected.
  15502. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15503. (interactive "e")
  15504. (mouse-set-point ev)
  15505. (when (calendar-cursor-to-date)
  15506. (let* ((date (calendar-cursor-to-date))
  15507. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15508. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15509. (when (active-minibuffer-window) (exit-minibuffer))))
  15510. (defun org-check-deadlines (ndays)
  15511. "Check if there are any deadlines due or past due.
  15512. A deadline is considered due if it happens within `org-deadline-warning-days'
  15513. days from today's date. If the deadline appears in an entry marked DONE,
  15514. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15515. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15516. are shown."
  15517. (interactive "P")
  15518. (let* ((org-warn-days
  15519. (cond
  15520. ((equal ndays '(4)) 100000)
  15521. (ndays (prefix-numeric-value ndays))
  15522. (t (abs org-deadline-warning-days))))
  15523. (case-fold-search nil)
  15524. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15525. (callback
  15526. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15527. (message "%d deadlines past-due or due within %d days"
  15528. (org-occur regexp nil callback)
  15529. org-warn-days)))
  15530. (defsubst org-re-timestamp (type)
  15531. "Return a regexp for timestamp TYPE.
  15532. Allowed values for TYPE are:
  15533. all: all timestamps
  15534. active: only active timestamps (<...>)
  15535. inactive: only inactive timestamps ([...])
  15536. scheduled: only scheduled timestamps
  15537. deadline: only deadline timestamps
  15538. closed: only closed time-stamps
  15539. When TYPE is nil, fall back on returning a regexp that matches
  15540. both scheduled and deadline timestamps."
  15541. (cl-case type
  15542. (all org-ts-regexp-both)
  15543. (active org-ts-regexp)
  15544. (inactive org-ts-regexp-inactive)
  15545. (scheduled org-scheduled-time-regexp)
  15546. (deadline org-deadline-time-regexp)
  15547. (closed org-closed-time-regexp)
  15548. (otherwise
  15549. (concat "\\<"
  15550. (regexp-opt (list org-deadline-string org-scheduled-string))
  15551. " *<\\([^>]+\\)>"))))
  15552. (defun org-check-before-date (d)
  15553. "Check if there are deadlines or scheduled entries before date D."
  15554. (interactive (list (org-read-date)))
  15555. (let* ((case-fold-search nil)
  15556. (regexp (org-re-timestamp org-ts-type))
  15557. (ts-type org-ts-type)
  15558. (callback
  15559. (lambda ()
  15560. (let ((match (match-string 1)))
  15561. (and (if (memq ts-type '(active inactive all))
  15562. (eq (org-element-type (save-excursion
  15563. (backward-char)
  15564. (org-element-context)))
  15565. 'timestamp)
  15566. (org-at-planning-p))
  15567. (time-less-p
  15568. (org-time-string-to-time match t)
  15569. (org-time-string-to-time d t)))))))
  15570. (message "%d entries before %s"
  15571. (org-occur regexp nil callback)
  15572. d)))
  15573. (defun org-check-after-date (d)
  15574. "Check if there are deadlines or scheduled entries after date D."
  15575. (interactive (list (org-read-date)))
  15576. (let* ((case-fold-search nil)
  15577. (regexp (org-re-timestamp org-ts-type))
  15578. (ts-type org-ts-type)
  15579. (callback
  15580. (lambda ()
  15581. (let ((match (match-string 1)))
  15582. (and (if (memq ts-type '(active inactive all))
  15583. (eq (org-element-type (save-excursion
  15584. (backward-char)
  15585. (org-element-context)))
  15586. 'timestamp)
  15587. (org-at-planning-p))
  15588. (not (time-less-p
  15589. (org-time-string-to-time match t)
  15590. (org-time-string-to-time d t))))))))
  15591. (message "%d entries after %s"
  15592. (org-occur regexp nil callback)
  15593. d)))
  15594. (defun org-check-dates-range (start-date end-date)
  15595. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15596. (interactive (list (org-read-date nil nil nil "Range starts")
  15597. (org-read-date nil nil nil "Range end")))
  15598. (let ((case-fold-search nil)
  15599. (regexp (org-re-timestamp org-ts-type))
  15600. (callback
  15601. (let ((type org-ts-type))
  15602. (lambda ()
  15603. (let ((match (match-string 1)))
  15604. (and
  15605. (if (memq type '(active inactive all))
  15606. (eq (org-element-type (save-excursion
  15607. (backward-char)
  15608. (org-element-context)))
  15609. 'timestamp)
  15610. (org-at-planning-p))
  15611. (not (time-less-p
  15612. (org-time-string-to-time match t)
  15613. (org-time-string-to-time start-date t)))
  15614. (time-less-p
  15615. (org-time-string-to-time match t)
  15616. (org-time-string-to-time end-date t))))))))
  15617. (message "%d entries between %s and %s"
  15618. (org-occur regexp nil callback) start-date end-date)))
  15619. (defun org-evaluate-time-range (&optional to-buffer)
  15620. "Evaluate a time range by computing the difference between start and end.
  15621. Normally the result is just printed in the echo area, but with prefix arg
  15622. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15623. If the time range is actually in a table, the result is inserted into the
  15624. next column.
  15625. For time difference computation, a year is assumed to be exactly 365
  15626. days in order to avoid rounding problems."
  15627. (interactive "P")
  15628. (or
  15629. (org-clock-update-time-maybe)
  15630. (save-excursion
  15631. (unless (org-at-date-range-p t)
  15632. (goto-char (point-at-bol))
  15633. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15634. (unless (org-at-date-range-p t)
  15635. (user-error "Not at a time-stamp range, and none found in current line")))
  15636. (let* ((ts1 (match-string 1))
  15637. (ts2 (match-string 2))
  15638. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15639. (match-end (match-end 0))
  15640. (time1 (org-time-string-to-time ts1))
  15641. (time2 (org-time-string-to-time ts2))
  15642. (t1 (float-time time1))
  15643. (t2 (float-time time2))
  15644. (diff (abs (- t2 t1)))
  15645. (negative (< (- t2 t1) 0))
  15646. ;; (ys (floor (* 365 24 60 60)))
  15647. (ds (* 24 60 60))
  15648. (hs (* 60 60))
  15649. (fy "%dy %dd %02d:%02d")
  15650. (fy1 "%dy %dd")
  15651. (fd "%dd %02d:%02d")
  15652. (fd1 "%dd")
  15653. (fh "%02d:%02d")
  15654. y d h m align)
  15655. (if havetime
  15656. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15657. y 0
  15658. d (floor (/ diff ds)) diff (mod diff ds)
  15659. h (floor (/ diff hs)) diff (mod diff hs)
  15660. m (floor (/ diff 60)))
  15661. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15662. y 0
  15663. d (floor (+ (/ diff ds) 0.5))
  15664. h 0 m 0))
  15665. (if (not to-buffer)
  15666. (message "%s" (org-make-tdiff-string y d h m))
  15667. (if (org-at-table-p)
  15668. (progn
  15669. (goto-char match-end)
  15670. (setq align t)
  15671. (and (looking-at " *|") (goto-char (match-end 0))))
  15672. (goto-char match-end))
  15673. (when (looking-at
  15674. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  15675. (replace-match ""))
  15676. (when negative (insert " -"))
  15677. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  15678. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  15679. (insert " " (format fh h m))))
  15680. (when align (org-table-align))
  15681. (message "Time difference inserted")))))
  15682. (defun org-make-tdiff-string (y d h m)
  15683. (let ((fmt "")
  15684. (l nil))
  15685. (when (> y 0)
  15686. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  15687. (push y l))
  15688. (when (> d 0)
  15689. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  15690. (push d l))
  15691. (when (> h 0)
  15692. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  15693. (push h l))
  15694. (when (> m 0)
  15695. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  15696. (push m l))
  15697. (apply 'format fmt (nreverse l))))
  15698. (defun org-time-string-to-time (s &optional zone)
  15699. "Convert timestamp string S into internal time.
  15700. The optional ZONE is omitted or nil for Emacs local time, t for
  15701. Universal Time, ‘wall’ for system wall clock time, or a string as
  15702. in the TZ environment variable."
  15703. (apply #'encode-time (org-parse-time-string s nil zone)))
  15704. (defun org-time-string-to-seconds (s &optional zone)
  15705. "Convert a timestamp string S into a number of seconds.
  15706. The optional ZONE is omitted or nil for Emacs local time, t for
  15707. Universal Time, ‘wall’ for system wall clock time, or a string as
  15708. in the TZ environment variable."
  15709. (float-time (org-time-string-to-time s zone)))
  15710. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  15711. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  15712. "Convert time stamp S to an absolute day number.
  15713. If DAYNR in non-nil, and there is a specifier for a cyclic time
  15714. stamp, get the closest date to DAYNR. If PREFER is
  15715. `past' (respectively `future') return a date past (respectively
  15716. after) or equal to DAYNR.
  15717. POS is the location of time stamp S, as a buffer position in
  15718. BUFFER.
  15719. Diary sexp timestamps are matched against DAYNR, when non-nil.
  15720. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  15721. signaled."
  15722. (cond
  15723. ((string-match "\\`%%\\((.*)\\)" s)
  15724. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  15725. ;; only able to match individual dates. If it fails, raise an
  15726. ;; error.
  15727. (if (and daynr
  15728. (org-diary-sexp-entry
  15729. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  15730. daynr
  15731. (signal 'org-diary-sexp-no-match (list s))))
  15732. (daynr (org-closest-date s daynr prefer))
  15733. (t (time-to-days
  15734. (condition-case errdata
  15735. (apply #'encode-time (org-parse-time-string s))
  15736. (error (error "Bad timestamp `%s'%s\nError was: %s"
  15737. s
  15738. (if (not (and buffer pos)) ""
  15739. (format-message " at %d in buffer `%s'" pos buffer))
  15740. (cdr errdata))))))))
  15741. (defun org-days-to-iso-week (days)
  15742. "Return the iso week number."
  15743. (require 'cal-iso)
  15744. (car (calendar-iso-from-absolute days)))
  15745. (defun org-small-year-to-year (year)
  15746. "Convert 2-digit years into 4-digit years.
  15747. YEAR is expanded into one of the 30 next years, if possible, or
  15748. into a past one. Any year larger than 99 is returned unchanged."
  15749. (if (>= year 100) year
  15750. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  15751. (century (/ current 100))
  15752. (offset (- year (% current 100))))
  15753. (cond ((> offset 30) (+ (* (1- century) 100) year))
  15754. ((> offset -70) (+ (* century 100) year))
  15755. (t (+ (* (1+ century) 100) year))))))
  15756. (defun org-time-from-absolute (d)
  15757. "Return the time corresponding to date D.
  15758. D may be an absolute day number, or a calendar-type list (month day year)."
  15759. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  15760. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  15761. (defvar org-agenda-current-date)
  15762. (defun org-calendar-holiday ()
  15763. "List of holidays, for Diary display in Org mode."
  15764. (require 'holidays)
  15765. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  15766. (and hl (mapconcat #'identity hl "; "))))
  15767. (defun org-diary-sexp-entry (sexp entry d)
  15768. "Process a SEXP diary ENTRY for date D."
  15769. (require 'diary-lib)
  15770. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  15771. ;; dynamically.
  15772. (let* ((sexp `(let ((entry ,entry)
  15773. (date ',d))
  15774. ,(car (read-from-string sexp))))
  15775. (result (if calendar-debug-sexp (eval sexp)
  15776. (condition-case nil
  15777. (eval sexp)
  15778. (error
  15779. (beep)
  15780. (message "Bad sexp at line %d in %s: %s"
  15781. (org-current-line)
  15782. (buffer-file-name) sexp)
  15783. (sleep-for 2))))))
  15784. (cond ((stringp result) (split-string result "; "))
  15785. ((and (consp result)
  15786. (not (consp (cdr result)))
  15787. (stringp (cdr result))) (cdr result))
  15788. ((and (consp result)
  15789. (stringp (car result))) result)
  15790. (result entry))))
  15791. (defun org-diary-to-ical-string (frombuf)
  15792. "Get iCalendar entries from diary entries in buffer FROMBUF.
  15793. This uses the icalendar.el library."
  15794. (let* ((tmpdir temporary-file-directory)
  15795. (tmpfile (make-temp-name
  15796. (expand-file-name "orgics" tmpdir)))
  15797. buf rtn b e)
  15798. (with-current-buffer frombuf
  15799. (icalendar-export-region (point-min) (point-max) tmpfile)
  15800. (setq buf (find-buffer-visiting tmpfile))
  15801. (set-buffer buf)
  15802. (goto-char (point-min))
  15803. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  15804. (setq b (match-beginning 0)))
  15805. (goto-char (point-max))
  15806. (when (re-search-backward "^END:VEVENT" nil t)
  15807. (setq e (match-end 0)))
  15808. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  15809. (kill-buffer buf)
  15810. (delete-file tmpfile)
  15811. rtn))
  15812. (defun org-closest-date (start current prefer)
  15813. "Return closest date to CURRENT starting from START.
  15814. CURRENT and START are both time stamps.
  15815. When PREFER is `past', return a date that is either CURRENT or
  15816. past. When PREFER is `future', return a date that is either
  15817. CURRENT or future.
  15818. Only time stamps with a repeater are modified. Any other time
  15819. stamp stay unchanged. In any case, return value is an absolute
  15820. day number."
  15821. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  15822. ;; No repeater. Do not shift time stamp.
  15823. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15824. (let ((value (string-to-number (match-string 1 start)))
  15825. (type (match-string 2 start)))
  15826. (if (= 0 value)
  15827. ;; Repeater with a 0-value is considered as void.
  15828. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15829. (let* ((base (org-date-to-gregorian start))
  15830. (target (org-date-to-gregorian current))
  15831. (sday (calendar-absolute-from-gregorian base))
  15832. (cday (calendar-absolute-from-gregorian target))
  15833. n1 n2)
  15834. ;; If START is already past CURRENT, just return START.
  15835. (if (<= cday sday) sday
  15836. ;; Compute closest date before (N1) and closest date past
  15837. ;; (N2) CURRENT.
  15838. (pcase type
  15839. ("h"
  15840. (let ((missing-hours
  15841. (mod (+ (- (* 24 (- cday sday))
  15842. (nth 2 (org-parse-time-string start)))
  15843. org-extend-today-until)
  15844. value)))
  15845. (setf n1 (if (= missing-hours 0) cday
  15846. (- cday (1+ (/ missing-hours 24)))))
  15847. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  15848. ((or "d" "w")
  15849. (let ((value (if (equal type "w") (* 7 value) value)))
  15850. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  15851. (setf n2 (+ n1 value))))
  15852. ("m"
  15853. (let* ((add-months
  15854. (lambda (d n)
  15855. ;; Add N months to gregorian date D, i.e.,
  15856. ;; a list (MONTH DAY YEAR). Return a valid
  15857. ;; gregorian date.
  15858. (let ((m (+ (nth 0 d) n)))
  15859. (list (mod m 12)
  15860. (nth 1 d)
  15861. (+ (/ m 12) (nth 2 d))))))
  15862. (months ; Complete months to TARGET.
  15863. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  15864. (- (nth 0 target) (nth 0 base))
  15865. ;; If START's day is greater than
  15866. ;; TARGET's, remove incomplete month.
  15867. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  15868. value)
  15869. value))
  15870. (before (funcall add-months base months)))
  15871. (setf n1 (calendar-absolute-from-gregorian before))
  15872. (setf n2
  15873. (calendar-absolute-from-gregorian
  15874. (funcall add-months before value)))))
  15875. (_
  15876. (let* ((d (nth 1 base))
  15877. (m (nth 0 base))
  15878. (y (nth 2 base))
  15879. (years ; Complete years to TARGET.
  15880. (* (/ (- (nth 2 target)
  15881. y
  15882. ;; If START's month and day are
  15883. ;; greater than TARGET's, remove
  15884. ;; incomplete year.
  15885. (if (or (> (nth 0 target) m)
  15886. (and (= (nth 0 target) m)
  15887. (> (nth 1 target) d)))
  15888. 0
  15889. 1))
  15890. value)
  15891. value))
  15892. (before (list m d (+ y years))))
  15893. (setf n1 (calendar-absolute-from-gregorian before))
  15894. (setf n2 (calendar-absolute-from-gregorian
  15895. (list m d (+ (nth 2 before) value)))))))
  15896. ;; Handle PREFER parameter, if any.
  15897. (cond
  15898. ((eq prefer 'past) (if (= cday n2) n2 n1))
  15899. ((eq prefer 'future) (if (= cday n1) n1 n2))
  15900. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  15901. (defun org-date-to-gregorian (d)
  15902. "Turn any specification of date D into a Gregorian date for the calendar."
  15903. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  15904. ((and (listp d) (= (length d) 3)) d)
  15905. ((stringp d)
  15906. (let ((d (org-parse-time-string d)))
  15907. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  15908. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  15909. (defun org-parse-time-string (s &optional nodefault zone)
  15910. "Parse the standard Org time string.
  15911. This should be a lot faster than the normal `parse-time-string'.
  15912. If time is not given, defaults to 0:00. However, with optional
  15913. NODEFAULT, hour and minute fields will be nil if not given.
  15914. The optional ZONE is omitted or nil for Emacs local time, t for
  15915. Universal Time, ‘wall’ for system wall clock time, or a string as
  15916. in the TZ environment variable."
  15917. (cond ((string-match org-ts-regexp0 s)
  15918. (list 0
  15919. (when (or (match-beginning 8) (not nodefault))
  15920. (string-to-number (or (match-string 8 s) "0")))
  15921. (when (or (match-beginning 7) (not nodefault))
  15922. (string-to-number (or (match-string 7 s) "0")))
  15923. (string-to-number (match-string 4 s))
  15924. (string-to-number (match-string 3 s))
  15925. (string-to-number (match-string 2 s))
  15926. nil nil zone))
  15927. ((string-match "^<[^>]+>$" s)
  15928. ;; FIXME: `decode-time' needs to be called with ZONE as its
  15929. ;; second argument. However, this requires at least Emacs
  15930. ;; 25.1. We can do it when we switch to this version as our
  15931. ;; minimal requirement.
  15932. (decode-time (seconds-to-time (org-matcher-time s))))
  15933. (t (error "Not a standard Org time string: %s" s))))
  15934. (defun org-timestamp-up (&optional arg)
  15935. "Increase the date item at the cursor by one.
  15936. If the cursor is on the year, change the year. If it is on the month,
  15937. the day or the time, change that.
  15938. With prefix ARG, change by that many units."
  15939. (interactive "p")
  15940. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  15941. (defun org-timestamp-down (&optional arg)
  15942. "Decrease the date item at the cursor by one.
  15943. If the cursor is on the year, change the year. If it is on the month,
  15944. the day or the time, change that.
  15945. With prefix ARG, change by that many units."
  15946. (interactive "p")
  15947. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  15948. (defun org-timestamp-up-day (&optional arg)
  15949. "Increase the date in the time stamp by one day.
  15950. With prefix ARG, change that many days."
  15951. (interactive "p")
  15952. (if (and (not (org-at-timestamp-p 'lax))
  15953. (org-at-heading-p))
  15954. (org-todo 'up)
  15955. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  15956. (defun org-timestamp-down-day (&optional arg)
  15957. "Decrease the date in the time stamp by one day.
  15958. With prefix ARG, change that many days."
  15959. (interactive "p")
  15960. (if (and (not (org-at-timestamp-p 'lax))
  15961. (org-at-heading-p))
  15962. (org-todo 'down)
  15963. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  15964. (defun org-at-timestamp-p (&optional extended)
  15965. "Non-nil if point is inside a timestamp.
  15966. By default, the function only consider syntactically valid active
  15967. timestamps. However, the caller may have a broader definition
  15968. for timestamps. As a consequence, optional argument EXTENDED can
  15969. be set to the following values
  15970. `inactive'
  15971. Include also syntactically valid inactive timestamps.
  15972. `agenda'
  15973. Include timestamps allowed in Agenda, i.e., those in
  15974. properties drawers, planning lines and clock lines.
  15975. `lax'
  15976. Ignore context. The function matches any part of the
  15977. document looking like a timestamp. This includes comments,
  15978. example blocks...
  15979. For backward-compatibility with Org 9.0, every other non-nil
  15980. value is equivalent to `inactive'.
  15981. When at a timestamp, return the position of the point as a symbol
  15982. among `bracket', `after', `year', `month', `hour', `minute',
  15983. `day' or a number of character from the last know part of the
  15984. time stamp.
  15985. When matching, the match groups are the following:
  15986. group 1: year
  15987. group 2: month
  15988. group 3: day number
  15989. group 4: day name
  15990. group 5: hours, if any
  15991. group 6: minutes, if any"
  15992. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  15993. (pos (point))
  15994. (match?
  15995. (let ((boundaries (org-in-regexp regexp)))
  15996. (save-match-data
  15997. (cond ((null boundaries) nil)
  15998. ((eq extended 'lax) t)
  15999. (t
  16000. (or (and (eq extended 'agenda)
  16001. (or (org-at-planning-p)
  16002. (org-at-property-p)
  16003. (and (bound-and-true-p
  16004. org-agenda-include-inactive-timestamps)
  16005. (org-at-clock-log-p))))
  16006. (eq 'timestamp
  16007. (save-excursion
  16008. (when (= pos (cdr boundaries)) (forward-char -1))
  16009. (org-element-type (org-element-context)))))))))))
  16010. (cond
  16011. ((not match?) nil)
  16012. ((= pos (match-beginning 0)) 'bracket)
  16013. ;; Distinguish location right before the closing bracket from
  16014. ;; right after it.
  16015. ((= pos (1- (match-end 0))) 'bracket)
  16016. ((= pos (match-end 0)) 'after)
  16017. ((org-pos-in-match-range pos 2) 'year)
  16018. ((org-pos-in-match-range pos 3) 'month)
  16019. ((org-pos-in-match-range pos 7) 'hour)
  16020. ((org-pos-in-match-range pos 8) 'minute)
  16021. ((or (org-pos-in-match-range pos 4)
  16022. (org-pos-in-match-range pos 5)) 'day)
  16023. ((and (> pos (or (match-end 8) (match-end 5)))
  16024. (< pos (match-end 0)))
  16025. (- pos (or (match-end 8) (match-end 5))))
  16026. (t 'day))))
  16027. (defun org-toggle-timestamp-type ()
  16028. "Toggle the type (<active> or [inactive]) of a time stamp."
  16029. (interactive)
  16030. (when (org-at-timestamp-p 'lax)
  16031. (let ((beg (match-beginning 0)) (end (match-end 0))
  16032. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16033. (save-excursion
  16034. (goto-char beg)
  16035. (while (re-search-forward "[][<>]" end t)
  16036. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16037. t t)))
  16038. (message "Timestamp is now %sactive"
  16039. (if (equal (char-after beg) ?<) "" "in")))))
  16040. (defun org-at-clock-log-p ()
  16041. "Non-nil if point is on a clock log line."
  16042. (and (org-match-line org-clock-line-re)
  16043. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  16044. (defvar org-clock-history) ; defined in org-clock.el
  16045. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16046. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16047. "Change the date in the time stamp at point.
  16048. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16049. `year', `minute', `second'. If WHAT is not given, the cursor position
  16050. in the timestamp determines what will be changed.
  16051. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16052. (let ((origin (point))
  16053. (timestamp? (org-at-timestamp-p 'lax))
  16054. origin-cat
  16055. with-hm inactive
  16056. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16057. extra rem
  16058. ts time time0 fixnext clrgx)
  16059. (unless timestamp? (user-error "Not at a timestamp"))
  16060. (if (and (not what) (eq timestamp? 'bracket))
  16061. (org-toggle-timestamp-type)
  16062. ;; Point isn't on brackets. Remember the part of the time-stamp
  16063. ;; the point was in. Indeed, size of time-stamps may change,
  16064. ;; but point must be kept in the same category nonetheless.
  16065. (setq origin-cat timestamp?)
  16066. (when (and (not what) (not (eq timestamp? 'day))
  16067. org-display-custom-times
  16068. (get-text-property (point) 'display)
  16069. (not (get-text-property (1- (point)) 'display)))
  16070. (setq timestamp? 'day))
  16071. (setq timestamp? (or what timestamp?)
  16072. inactive (= (char-after (match-beginning 0)) ?\[)
  16073. ts (match-string 0))
  16074. (replace-match "")
  16075. (when (string-match
  16076. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16077. ts)
  16078. (setq extra (match-string 1 ts))
  16079. (when suppress-tmp-delay
  16080. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16081. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16082. (setq with-hm t))
  16083. (setq time0 (org-parse-time-string ts))
  16084. (when (and updown
  16085. (eq timestamp? 'minute)
  16086. (not current-prefix-arg))
  16087. ;; This looks like s-up and s-down. Change by one rounding step.
  16088. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16089. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16090. (setcar (cdr time0) (+ (nth 1 time0)
  16091. (if (> n 0) (- rem) (- dm rem))))))
  16092. (setq time
  16093. (apply #'encode-time
  16094. (or (car time0) 0)
  16095. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  16096. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  16097. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  16098. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  16099. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  16100. (nthcdr 6 time0)))
  16101. (when (and (memq timestamp? '(hour minute))
  16102. extra
  16103. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16104. (setq extra (org-modify-ts-extra
  16105. extra
  16106. (if (eq timestamp? 'hour) 2 5)
  16107. n dm)))
  16108. (when (integerp timestamp?)
  16109. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  16110. (when (eq what 'calendar)
  16111. (let ((cal-date (org-get-date-from-calendar)))
  16112. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16113. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16114. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16115. (setcar time0 (or (car time0) 0))
  16116. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16117. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16118. (setq time (apply 'encode-time time0))))
  16119. ;; Insert the new time-stamp, and ensure point stays in the same
  16120. ;; category as before (i.e. not after the last position in that
  16121. ;; category).
  16122. (let ((pos (point)))
  16123. ;; Stay before inserted string. `save-excursion' is of no use.
  16124. (setq org-last-changed-timestamp
  16125. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16126. (goto-char pos))
  16127. (save-match-data
  16128. (looking-at org-ts-regexp3)
  16129. (goto-char
  16130. (pcase origin-cat
  16131. ;; `day' category ends before `hour' if any, or at the end
  16132. ;; of the day name.
  16133. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16134. (`hour (min (match-end 7) origin))
  16135. (`minute (min (1- (match-end 8)) origin))
  16136. ((pred integerp) (min (1- (match-end 0)) origin))
  16137. ;; Point was right after the time-stamp. However, the
  16138. ;; time-stamp length might have changed, so refer to
  16139. ;; (match-end 0) instead.
  16140. (`after (match-end 0))
  16141. ;; `year' and `month' have both fixed size: point couldn't
  16142. ;; have moved into another part.
  16143. (_ origin))))
  16144. ;; Update clock if on a CLOCK line.
  16145. (org-clock-update-time-maybe)
  16146. ;; Maybe adjust the closest clock in `org-clock-history'
  16147. (when org-clock-adjust-closest
  16148. (if (not (and (org-at-clock-log-p)
  16149. (< 1 (length (delq nil (mapcar 'marker-position
  16150. org-clock-history))))))
  16151. (message "No clock to adjust")
  16152. (cond ((save-excursion ; fix previous clock?
  16153. (re-search-backward org-ts-regexp0 nil t)
  16154. (looking-back (concat org-clock-string " \\[")
  16155. (line-beginning-position)))
  16156. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16157. ((save-excursion ; fix next clock?
  16158. (re-search-backward org-ts-regexp0 nil t)
  16159. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16160. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16161. (save-window-excursion
  16162. ;; Find closest clock to point, adjust the previous/next one in history
  16163. (let* ((p (save-excursion (org-back-to-heading t)))
  16164. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16165. (clfixnth
  16166. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16167. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16168. (if (not clfixpos)
  16169. (message "No clock to adjust")
  16170. (save-excursion
  16171. (org-goto-marker-or-bmk clfixpos)
  16172. (org-show-subtree)
  16173. (when (re-search-forward clrgx nil t)
  16174. (goto-char (match-beginning 1))
  16175. (let (org-clock-adjust-closest)
  16176. (org-timestamp-change n timestamp? updown))
  16177. (message "Clock adjusted in %s for heading: %s"
  16178. (file-name-nondirectory (buffer-file-name))
  16179. (org-get-heading t t)))))))))
  16180. ;; Try to recenter the calendar window, if any.
  16181. (when (and org-calendar-follow-timestamp-change
  16182. (get-buffer-window "*Calendar*" t)
  16183. (memq timestamp? '(day month year)))
  16184. (org-recenter-calendar (time-to-days time))))))
  16185. (defun org-modify-ts-extra (s pos n dm)
  16186. "Change the different parts of the lead-time and repeat fields in timestamp."
  16187. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16188. ng h m new rem)
  16189. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16190. (cond
  16191. ((or (org-pos-in-match-range pos 2)
  16192. (org-pos-in-match-range pos 3))
  16193. (setq m (string-to-number (match-string 3 s))
  16194. h (string-to-number (match-string 2 s)))
  16195. (if (org-pos-in-match-range pos 2)
  16196. (setq h (+ h n))
  16197. (setq n (* dm (with-no-warnings (signum n))))
  16198. (unless (= 0 (setq rem (% m dm)))
  16199. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16200. (setq m (+ m n)))
  16201. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16202. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16203. (setq h (mod h 24))
  16204. (setq ng 1 new (format "-%02d:%02d" h m)))
  16205. ((org-pos-in-match-range pos 6)
  16206. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16207. ((org-pos-in-match-range pos 5)
  16208. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16209. ((org-pos-in-match-range pos 9)
  16210. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16211. ((org-pos-in-match-range pos 8)
  16212. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16213. (when ng
  16214. (setq s (concat
  16215. (substring s 0 (match-beginning ng))
  16216. new
  16217. (substring s (match-end ng))))))
  16218. s))
  16219. (defun org-recenter-calendar (d)
  16220. "If the calendar is visible, recenter it to date D."
  16221. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16222. (when cwin
  16223. (let ((calendar-move-hook nil))
  16224. (with-selected-window cwin
  16225. (calendar-goto-date
  16226. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16227. (defun org-goto-calendar (&optional arg)
  16228. "Go to the Emacs calendar at the current date.
  16229. If there is a time stamp in the current line, go to that date.
  16230. A prefix ARG can be used to force the current date."
  16231. (interactive "P")
  16232. (let ((calendar-move-hook nil)
  16233. (calendar-view-holidays-initially-flag nil)
  16234. (calendar-view-diary-initially-flag nil)
  16235. diff)
  16236. (when (or (org-at-timestamp-p 'lax)
  16237. (org-match-line (concat ".*" org-ts-regexp)))
  16238. (let ((d1 (time-to-days (current-time)))
  16239. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  16240. (setq diff (- d2 d1))))
  16241. (calendar)
  16242. (calendar-goto-today)
  16243. (when (and diff (not arg)) (calendar-forward-day diff))))
  16244. (defun org-get-date-from-calendar ()
  16245. "Return a list (month day year) of date at point in calendar."
  16246. (with-current-buffer "*Calendar*"
  16247. (save-match-data
  16248. (calendar-cursor-to-date))))
  16249. (defun org-date-from-calendar ()
  16250. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16251. If there is already a time stamp at the cursor position, update it."
  16252. (interactive)
  16253. (if (org-at-timestamp-p 'lax)
  16254. (org-timestamp-change 0 'calendar)
  16255. (let ((cal-date (org-get-date-from-calendar)))
  16256. (org-insert-time-stamp
  16257. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16258. (defcustom org-effort-durations
  16259. `(("min" . 1)
  16260. ("h" . 60)
  16261. ("d" . ,(* 60 8))
  16262. ("w" . ,(* 60 8 5))
  16263. ("m" . ,(* 60 8 5 4))
  16264. ("y" . ,(* 60 8 5 40)))
  16265. "Conversion factor to minutes for an effort modifier.
  16266. Each entry has the form (MODIFIER . MINUTES).
  16267. In an effort string, a number followed by MODIFIER is multiplied
  16268. by the specified number of MINUTES to obtain an effort in
  16269. minutes.
  16270. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16271. effort string \"2hours\" is equivalent to 120 minutes."
  16272. :group 'org-agenda
  16273. :version "26.1"
  16274. :package-version '(Org . "8.3")
  16275. :type '(alist :key-type (string :tag "Modifier")
  16276. :value-type (number :tag "Minutes")))
  16277. (defcustom org-image-actual-width t
  16278. "Should we use the actual width of images when inlining them?
  16279. When set to t, always use the image width.
  16280. When set to a number, use imagemagick (when available) to set
  16281. the image's width to this value.
  16282. When set to a number in a list, try to get the width from any
  16283. #+ATTR.* keyword if it matches a width specification like
  16284. #+ATTR_HTML: :width 300px
  16285. and fall back on that number if none is found.
  16286. When set to nil, try to get the width from an #+ATTR.* keyword
  16287. and fall back on the original width if none is found.
  16288. This requires Emacs >= 24.1, build with imagemagick support."
  16289. :group 'org-appearance
  16290. :version "24.4"
  16291. :package-version '(Org . "8.0")
  16292. :type '(choice
  16293. (const :tag "Use the image width" t)
  16294. (integer :tag "Use a number of pixels")
  16295. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16296. (const :tag "Use #+ATTR* or don't resize" nil)))
  16297. (defcustom org-agenda-inhibit-startup nil
  16298. "Inhibit startup when preparing agenda buffers.
  16299. When this variable is t, the initialization of the Org agenda
  16300. buffers is inhibited: e.g. the visibility state is not set, the
  16301. tables are not re-aligned, etc."
  16302. :type 'boolean
  16303. :version "24.3"
  16304. :group 'org-agenda)
  16305. (defcustom org-agenda-ignore-properties nil
  16306. "Avoid updating text properties when building the agenda.
  16307. Properties are used to prepare buffers for effort estimates,
  16308. appointments, statistics and subtree-local categories.
  16309. If you don't use these in the agenda, you can add them to this
  16310. list and agenda building will be a bit faster.
  16311. The value is a list, with zero or more of the symbols `effort', `appt',
  16312. `stats' or `category'."
  16313. :type '(set :greedy t
  16314. (const effort)
  16315. (const appt)
  16316. (const stats)
  16317. (const category))
  16318. :version "26.1"
  16319. :package-version '(Org . "8.3")
  16320. :group 'org-agenda)
  16321. ;;;; Files
  16322. (defun org-save-all-org-buffers ()
  16323. "Save all Org buffers without user confirmation."
  16324. (interactive)
  16325. (message "Saving all Org buffers...")
  16326. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16327. (when (featurep 'org-id) (org-id-locations-save))
  16328. (message "Saving all Org buffers... done"))
  16329. (defun org-revert-all-org-buffers ()
  16330. "Revert all Org buffers.
  16331. Prompt for confirmation when there are unsaved changes.
  16332. Be sure you know what you are doing before letting this function
  16333. overwrite your changes.
  16334. This function is useful in a setup where one tracks org files
  16335. with a version control system, to revert on one machine after pulling
  16336. changes from another. I believe the procedure must be like this:
  16337. 1. M-x org-save-all-org-buffers
  16338. 2. Pull changes from the other machine, resolve conflicts
  16339. 3. M-x org-revert-all-org-buffers"
  16340. (interactive)
  16341. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16342. (user-error "Abort"))
  16343. (save-excursion
  16344. (save-window-excursion
  16345. (dolist (b (buffer-list))
  16346. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16347. (with-current-buffer b buffer-file-name))
  16348. (pop-to-buffer-same-window b)
  16349. (revert-buffer t 'no-confirm)))
  16350. (when (and (featurep 'org-id) org-id-track-globally)
  16351. (org-id-locations-load)))))
  16352. ;;;; Agenda files
  16353. ;;;###autoload
  16354. (defun org-switchb (&optional arg)
  16355. "Switch between Org buffers.
  16356. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16357. With `\\[universal-argument] \\[universal-argument]' \
  16358. prefix, restrict available buffers to agenda files."
  16359. (interactive "P")
  16360. (let ((blist (org-buffer-list
  16361. (cond ((equal arg '(4)) 'files)
  16362. ((equal arg '(16)) 'agenda)))))
  16363. (pop-to-buffer-same-window
  16364. (completing-read "Org buffer: "
  16365. (mapcar #'list (mapcar #'buffer-name blist))
  16366. nil t))))
  16367. (defun org-buffer-list (&optional predicate exclude-tmp)
  16368. "Return a list of Org buffers.
  16369. PREDICATE can be `export', `files' or `agenda'.
  16370. export restrict the list to Export buffers.
  16371. files restrict the list to buffers visiting Org files.
  16372. agenda restrict the list to buffers visiting agenda files.
  16373. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16374. (let* ((bfn nil)
  16375. (agenda-files (and (eq predicate 'agenda)
  16376. (mapcar 'file-truename (org-agenda-files t))))
  16377. (filter
  16378. (cond
  16379. ((eq predicate 'files)
  16380. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16381. ((eq predicate 'export)
  16382. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16383. ((eq predicate 'agenda)
  16384. (lambda (b)
  16385. (with-current-buffer b
  16386. (and (derived-mode-p 'org-mode)
  16387. (setq bfn (buffer-file-name b))
  16388. (member (file-truename bfn) agenda-files)))))
  16389. (t (lambda (b) (with-current-buffer b
  16390. (or (derived-mode-p 'org-mode)
  16391. (string-match "\\*Org .*Export"
  16392. (buffer-name b)))))))))
  16393. (delq nil
  16394. (mapcar
  16395. (lambda(b)
  16396. (if (and (funcall filter b)
  16397. (or (not exclude-tmp)
  16398. (not (string-match "tmp" (buffer-name b)))))
  16399. b
  16400. nil))
  16401. (buffer-list)))))
  16402. (defun org-agenda-files (&optional unrestricted archives)
  16403. "Get the list of agenda files.
  16404. Optional UNRESTRICTED means return the full list even if a restriction
  16405. is currently in place.
  16406. When ARCHIVES is t, include all archive files that are really being
  16407. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16408. `org-agenda-archives-mode' is t."
  16409. (let ((files
  16410. (cond
  16411. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16412. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16413. ((listp org-agenda-files) org-agenda-files)
  16414. (t (error "Invalid value of `org-agenda-files'")))))
  16415. (setq files (apply 'append
  16416. (mapcar (lambda (f)
  16417. (if (file-directory-p f)
  16418. (directory-files
  16419. f t org-agenda-file-regexp)
  16420. (list f)))
  16421. files)))
  16422. (when org-agenda-skip-unavailable-files
  16423. (setq files (delq nil
  16424. (mapcar (function
  16425. (lambda (file)
  16426. (and (file-readable-p file) file)))
  16427. files))))
  16428. (when (or (eq archives t)
  16429. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16430. (setq files (org-add-archive-files files)))
  16431. files))
  16432. (defun org-agenda-file-p (&optional file)
  16433. "Return non-nil, if FILE is an agenda file.
  16434. If FILE is omitted, use the file associated with the current
  16435. buffer."
  16436. (let ((fname (or file (buffer-file-name))))
  16437. (and fname
  16438. (member (file-truename fname)
  16439. (mapcar #'file-truename (org-agenda-files t))))))
  16440. (defun org-edit-agenda-file-list ()
  16441. "Edit the list of agenda files.
  16442. Depending on setup, this either uses customize to edit the variable
  16443. `org-agenda-files', or it visits the file that is holding the list. In the
  16444. latter case, the buffer is set up in a way that saving it automatically kills
  16445. the buffer and restores the previous window configuration."
  16446. (interactive)
  16447. (if (stringp org-agenda-files)
  16448. (let ((cw (current-window-configuration)))
  16449. (find-file org-agenda-files)
  16450. (setq-local org-window-configuration cw)
  16451. (add-hook 'after-save-hook
  16452. (lambda ()
  16453. (set-window-configuration
  16454. (prog1 org-window-configuration
  16455. (kill-buffer (current-buffer))))
  16456. (org-install-agenda-files-menu)
  16457. (message "New agenda file list installed"))
  16458. nil 'local)
  16459. (message "%s" (substitute-command-keys
  16460. "Edit list and finish with \\[save-buffer]")))
  16461. (customize-variable 'org-agenda-files)))
  16462. (defun org-store-new-agenda-file-list (list)
  16463. "Set new value for the agenda file list and save it correctly."
  16464. (if (stringp org-agenda-files)
  16465. (let ((fe (org-read-agenda-file-list t)) b u)
  16466. (while (setq b (find-buffer-visiting org-agenda-files))
  16467. (kill-buffer b))
  16468. (with-temp-file org-agenda-files
  16469. (insert
  16470. (mapconcat
  16471. (lambda (f) ;; Keep un-expanded entries.
  16472. (if (setq u (assoc f fe))
  16473. (cdr u)
  16474. f))
  16475. list "\n")
  16476. "\n")))
  16477. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16478. (org-insert-mode-line-in-empty-file nil))
  16479. (setq org-agenda-files list)
  16480. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16481. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16482. "Read the list of agenda files from a file.
  16483. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16484. filenames, used by `org-store-new-agenda-file-list' to write back
  16485. un-expanded file names."
  16486. (when (file-directory-p org-agenda-files)
  16487. (error "`org-agenda-files' cannot be a single directory"))
  16488. (when (stringp org-agenda-files)
  16489. (with-temp-buffer
  16490. (insert-file-contents org-agenda-files)
  16491. (mapcar
  16492. (lambda (f)
  16493. (let ((e (expand-file-name (substitute-in-file-name f)
  16494. org-directory)))
  16495. (if pair-with-expansion
  16496. (cons e f)
  16497. e)))
  16498. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16499. ;;;###autoload
  16500. (defun org-cycle-agenda-files ()
  16501. "Cycle through the files in `org-agenda-files'.
  16502. If the current buffer visits an agenda file, find the next one in the list.
  16503. If the current buffer does not, find the first agenda file."
  16504. (interactive)
  16505. (let* ((fs (or (org-agenda-files t)
  16506. (user-error "No agenda files")))
  16507. (files (copy-sequence fs))
  16508. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16509. file)
  16510. (when tcf
  16511. (while (and (setq file (pop files))
  16512. (not (equal (file-truename file) tcf)))))
  16513. (find-file (car (or files fs)))
  16514. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16515. (defun org-agenda-file-to-front (&optional to-end)
  16516. "Move/add the current file to the top of the agenda file list.
  16517. If the file is not present in the list, it is added to the front. If it is
  16518. present, it is moved there. With optional argument TO-END, add/move to the
  16519. end of the list."
  16520. (interactive "P")
  16521. (let ((org-agenda-skip-unavailable-files nil)
  16522. (file-alist (mapcar (lambda (x)
  16523. (cons (file-truename x) x))
  16524. (org-agenda-files t)))
  16525. (ctf (file-truename
  16526. (or buffer-file-name
  16527. (user-error "Please save the current buffer to a file"))))
  16528. x had)
  16529. (setq x (assoc ctf file-alist) had x)
  16530. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16531. (if to-end
  16532. (setq file-alist (append (delq x file-alist) (list x)))
  16533. (setq file-alist (cons x (delq x file-alist))))
  16534. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16535. (org-install-agenda-files-menu)
  16536. (message "File %s to %s of agenda file list"
  16537. (if had "moved" "added") (if to-end "end" "front"))))
  16538. (defun org-remove-file (&optional file)
  16539. "Remove current file from the list of files in variable `org-agenda-files'.
  16540. These are the files which are being checked for agenda entries.
  16541. Optional argument FILE means use this file instead of the current."
  16542. (interactive)
  16543. (let* ((org-agenda-skip-unavailable-files nil)
  16544. (file (or file buffer-file-name
  16545. (user-error "Current buffer does not visit a file")))
  16546. (true-file (file-truename file))
  16547. (afile (abbreviate-file-name file))
  16548. (files (delq nil (mapcar
  16549. (lambda (x)
  16550. (unless (equal true-file
  16551. (file-truename x))
  16552. x))
  16553. (org-agenda-files t)))))
  16554. (if (not (= (length files) (length (org-agenda-files t))))
  16555. (progn
  16556. (org-store-new-agenda-file-list files)
  16557. (org-install-agenda-files-menu)
  16558. (message "Removed from Org Agenda list: %s" afile))
  16559. (message "File was not in list: %s (not removed)" afile))))
  16560. (defun org-file-menu-entry (file)
  16561. (vector file (list 'find-file file) t))
  16562. (defun org-check-agenda-file (file)
  16563. "Make sure FILE exists. If not, ask user what to do."
  16564. (unless (file-exists-p file)
  16565. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16566. (abbreviate-file-name file))
  16567. (let ((r (downcase (read-char-exclusive))))
  16568. (cond
  16569. ((equal r ?r)
  16570. (org-remove-file file)
  16571. (throw 'nextfile t))
  16572. (t (user-error "Abort"))))))
  16573. (defun org-get-agenda-file-buffer (file)
  16574. "Get an agenda buffer visiting FILE.
  16575. If the buffer needs to be created, add it to the list of buffers
  16576. which might be released later."
  16577. (let ((buf (org-find-base-buffer-visiting file)))
  16578. (if buf
  16579. buf ; just return it
  16580. ;; Make a new buffer and remember it
  16581. (setq buf (find-file-noselect file))
  16582. (when buf (push buf org-agenda-new-buffers))
  16583. buf)))
  16584. (defun org-release-buffers (blist)
  16585. "Release all buffers in list, asking the user for confirmation when needed.
  16586. When a buffer is unmodified, it is just killed. When modified, it is saved
  16587. \(if the user agrees) and then killed."
  16588. (let (file)
  16589. (dolist (buf blist)
  16590. (setq file (buffer-file-name buf))
  16591. (when (and (buffer-modified-p buf)
  16592. file
  16593. (y-or-n-p (format "Save file %s? " file)))
  16594. (with-current-buffer buf (save-buffer)))
  16595. (kill-buffer buf))))
  16596. (defun org-agenda-prepare-buffers (files)
  16597. "Create buffers for all agenda files, protect archived trees and comments."
  16598. (interactive)
  16599. (let ((pa '(:org-archived t))
  16600. (pc '(:org-comment t))
  16601. (pall '(:org-archived t :org-comment t))
  16602. (inhibit-read-only t)
  16603. (org-inhibit-startup org-agenda-inhibit-startup)
  16604. (rea (concat ":" org-archive-tag ":"))
  16605. re pos)
  16606. (setq org-tag-alist-for-agenda nil
  16607. org-tag-groups-alist-for-agenda nil)
  16608. (save-excursion
  16609. (save-restriction
  16610. (dolist (file files)
  16611. (catch 'nextfile
  16612. (if (bufferp file)
  16613. (set-buffer file)
  16614. (org-check-agenda-file file)
  16615. (set-buffer (org-get-agenda-file-buffer file)))
  16616. (widen)
  16617. (org-set-regexps-and-options 'tags-only)
  16618. (setq pos (point))
  16619. (or (memq 'category org-agenda-ignore-properties)
  16620. (org-refresh-category-properties))
  16621. (or (memq 'stats org-agenda-ignore-properties)
  16622. (org-refresh-stats-properties))
  16623. (or (memq 'effort org-agenda-ignore-properties)
  16624. (org-refresh-effort-properties))
  16625. (or (memq 'appt org-agenda-ignore-properties)
  16626. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16627. (setq org-todo-keywords-for-agenda
  16628. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16629. (setq org-done-keywords-for-agenda
  16630. (append org-done-keywords-for-agenda org-done-keywords))
  16631. (setq org-todo-keyword-alist-for-agenda
  16632. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16633. (setq org-tag-alist-for-agenda
  16634. (org-uniquify
  16635. (append org-tag-alist-for-agenda
  16636. org-current-tag-alist)))
  16637. ;; Merge current file's tag groups into global
  16638. ;; `org-tag-groups-alist-for-agenda'.
  16639. (when org-group-tags
  16640. (dolist (alist org-tag-groups-alist)
  16641. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16642. (if old
  16643. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16644. (push alist org-tag-groups-alist-for-agenda)))))
  16645. (org-with-silent-modifications
  16646. (save-excursion
  16647. (remove-text-properties (point-min) (point-max) pall)
  16648. (when org-agenda-skip-archived-trees
  16649. (goto-char (point-min))
  16650. (while (re-search-forward rea nil t)
  16651. (when (org-at-heading-p t)
  16652. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16653. (goto-char (point-min))
  16654. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16655. (while (re-search-forward re nil t)
  16656. (when (save-match-data (org-in-commented-heading-p t))
  16657. (add-text-properties
  16658. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16659. (goto-char pos)))))
  16660. (setq org-todo-keywords-for-agenda
  16661. (org-uniquify org-todo-keywords-for-agenda))
  16662. (setq org-todo-keyword-alist-for-agenda
  16663. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16664. ;;;; CDLaTeX minor mode
  16665. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16666. "Keymap for the minor `org-cdlatex-mode'.")
  16667. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  16668. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  16669. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  16670. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  16671. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  16672. (defvar org-cdlatex-texmathp-advice-is-done nil
  16673. "Flag remembering if we have applied the advice to texmathp already.")
  16674. (define-minor-mode org-cdlatex-mode
  16675. "Toggle the minor `org-cdlatex-mode'.
  16676. This mode supports entering LaTeX environment and math in LaTeX fragments
  16677. in Org mode.
  16678. \\{org-cdlatex-mode-map}"
  16679. nil " OCDL" nil
  16680. (when org-cdlatex-mode
  16681. (require 'cdlatex)
  16682. (run-hooks 'cdlatex-mode-hook)
  16683. (cdlatex-compute-tables))
  16684. (unless org-cdlatex-texmathp-advice-is-done
  16685. (setq org-cdlatex-texmathp-advice-is-done t)
  16686. (defadvice texmathp (around org-math-always-on activate)
  16687. "Always return t in Org buffers.
  16688. This is because we want to insert math symbols without dollars even outside
  16689. the LaTeX math segments. If Org mode thinks that point is actually inside
  16690. an embedded LaTeX fragment, let `texmathp' do its job.
  16691. `\\[org-cdlatex-mode-map]'"
  16692. (interactive)
  16693. (let (p)
  16694. (cond
  16695. ((not (derived-mode-p 'org-mode)) ad-do-it)
  16696. ((eq this-command 'cdlatex-math-symbol)
  16697. (setq ad-return-value t
  16698. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  16699. (t
  16700. (let ((p (org-inside-LaTeX-fragment-p)))
  16701. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  16702. (setq ad-return-value t
  16703. texmathp-why '("Org mode embedded math" . 0))
  16704. (when p ad-do-it)))))))))
  16705. (defun turn-on-org-cdlatex ()
  16706. "Unconditionally turn on `org-cdlatex-mode'."
  16707. (org-cdlatex-mode 1))
  16708. (defun org-try-cdlatex-tab ()
  16709. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  16710. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  16711. - inside a LaTeX fragment, or
  16712. - after the first word in a line, where an abbreviation expansion could
  16713. insert a LaTeX environment."
  16714. (when org-cdlatex-mode
  16715. (cond
  16716. ;; Before any word on the line: No expansion possible.
  16717. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  16718. ;; Just after first word on the line: Expand it. Make sure it
  16719. ;; cannot happen on headlines, though.
  16720. ((save-excursion
  16721. (skip-chars-backward "a-zA-Z0-9*")
  16722. (skip-chars-backward " \t")
  16723. (and (bolp) (not (org-at-heading-p))))
  16724. (cdlatex-tab) t)
  16725. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  16726. (defun org-cdlatex-underscore-caret (&optional _arg)
  16727. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  16728. Revert to the normal definition outside of these fragments."
  16729. (interactive "P")
  16730. (if (org-inside-LaTeX-fragment-p)
  16731. (call-interactively 'cdlatex-sub-superscript)
  16732. (let (org-cdlatex-mode)
  16733. (call-interactively (key-binding (vector last-input-event))))))
  16734. (defun org-cdlatex-math-modify (&optional _arg)
  16735. "Execute `cdlatex-math-modify' in LaTeX fragments.
  16736. Revert to the normal definition outside of these fragments."
  16737. (interactive "P")
  16738. (if (org-inside-LaTeX-fragment-p)
  16739. (call-interactively 'cdlatex-math-modify)
  16740. (let (org-cdlatex-mode)
  16741. (call-interactively (key-binding (vector last-input-event))))))
  16742. (defun org-cdlatex-environment-indent (&optional environment item)
  16743. "Execute `cdlatex-environment' and indent the inserted environment.
  16744. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  16745. The inserted environment is indented to current indentation
  16746. unless point is at the beginning of the line, in which the
  16747. environment remains unintended."
  16748. (interactive)
  16749. ;; cdlatex-environment always return nil. Therefore, capture output
  16750. ;; first and determine if an environment was selected.
  16751. (let* ((beg (point-marker))
  16752. (end (copy-marker (point) t))
  16753. (inserted (progn
  16754. (ignore-errors (cdlatex-environment environment item))
  16755. (< beg end)))
  16756. ;; Figure out how many lines to move forward after the
  16757. ;; environment has been inserted.
  16758. (lines (when inserted
  16759. (save-excursion
  16760. (- (cl-loop while (< beg (point))
  16761. with x = 0
  16762. do (forward-line -1)
  16763. (cl-incf x)
  16764. finally return x)
  16765. (if (progn (goto-char beg)
  16766. (and (progn (skip-chars-forward " \t") (eolp))
  16767. (progn (skip-chars-backward " \t") (bolp))))
  16768. 1 0)))))
  16769. (env (org-trim (delete-and-extract-region beg end))))
  16770. (when inserted
  16771. ;; Get indentation of next line unless at column 0.
  16772. (let ((ind (if (bolp) 0
  16773. (save-excursion
  16774. (org-return-indent)
  16775. (prog1 (org-get-indentation)
  16776. (when (progn (skip-chars-forward " \t") (eolp))
  16777. (delete-region beg (point)))))))
  16778. (bol (progn (skip-chars-backward " \t") (bolp))))
  16779. ;; Insert a newline before environment unless at column zero
  16780. ;; to "escape" the current line. Insert a newline if
  16781. ;; something is one the same line as \end{ENVIRONMENT}.
  16782. (insert
  16783. (concat (unless bol "\n") env
  16784. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  16785. (unless (zerop ind)
  16786. (save-excursion
  16787. (goto-char beg)
  16788. (while (< (point) end)
  16789. (unless (eolp) (indent-line-to ind))
  16790. (forward-line))))
  16791. (goto-char beg)
  16792. (forward-line lines)
  16793. (indent-line-to ind)))
  16794. (set-marker beg nil)
  16795. (set-marker end nil)))
  16796. ;;;; LaTeX fragments
  16797. (defun org-inside-LaTeX-fragment-p ()
  16798. "Test if point is inside a LaTeX fragment.
  16799. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  16800. sequence appearing also before point.
  16801. Even though the matchers for math are configurable, this function assumes
  16802. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  16803. delimiters are skipped when they have been removed by customization.
  16804. The return value is nil, or a cons cell with the delimiter and the
  16805. position of this delimiter.
  16806. This function does a reasonably good job, but can locally be fooled by
  16807. for example currency specifications. For example it will assume being in
  16808. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  16809. fragments that are properly closed, but during editing, we have to live
  16810. with the uncertainty caused by missing closing delimiters. This function
  16811. looks only before point, not after."
  16812. (catch 'exit
  16813. (let ((pos (point))
  16814. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  16815. (lim (save-excursion (org-backward-paragraph) (point)))
  16816. dd-on str (start 0) m re)
  16817. (goto-char pos)
  16818. (when dodollar
  16819. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  16820. re (nth 1 (assoc "$" org-latex-regexps)))
  16821. (while (string-match re str start)
  16822. (cond
  16823. ((= (match-end 0) (length str))
  16824. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  16825. ((= (match-end 0) (- (length str) 5))
  16826. (throw 'exit nil))
  16827. (t (setq start (match-end 0))))))
  16828. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  16829. (goto-char pos)
  16830. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  16831. (and (match-beginning 2) (throw 'exit nil))
  16832. ;; count $$
  16833. (while (re-search-backward "\\$\\$" lim t)
  16834. (setq dd-on (not dd-on)))
  16835. (goto-char pos)
  16836. (when dd-on (cons "$$" m))))))
  16837. (defun org-inside-latex-macro-p ()
  16838. "Is point inside a LaTeX macro or its arguments?"
  16839. (save-match-data
  16840. (org-in-regexp
  16841. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  16842. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  16843. "Build an overlay between BEG and END using IMAGE file.
  16844. Argument IMAGETYPE is the extension of the displayed image,
  16845. as a string. It defaults to \"png\"."
  16846. (let ((ov (make-overlay beg end))
  16847. (imagetype (or (intern imagetype) 'png)))
  16848. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  16849. (overlay-put ov 'evaporate t)
  16850. (overlay-put ov
  16851. 'modification-hooks
  16852. (list (lambda (o _flag _beg _end &optional _l)
  16853. (delete-overlay o))))
  16854. (overlay-put ov
  16855. 'display
  16856. (list 'image :type imagetype :file image :ascent 'center))))
  16857. (defun org--list-latex-overlays (&optional beg end)
  16858. "List all Org LaTeX overlays in current buffer.
  16859. Limit to overlays between BEG and END when those are provided."
  16860. (cl-remove-if-not
  16861. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  16862. (overlays-in (or beg (point-min)) (or end (point-max)))))
  16863. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  16864. "Remove all overlays with LaTeX fragment images in current buffer.
  16865. When optional arguments BEG and END are non-nil, remove all
  16866. overlays between them instead. Return a non-nil value when some
  16867. overlays were removed, nil otherwise."
  16868. (let ((overlays (org--list-latex-overlays beg end)))
  16869. (mapc #'delete-overlay overlays)
  16870. overlays))
  16871. (defun org-toggle-latex-fragment (&optional arg)
  16872. "Preview the LaTeX fragment at point, or all locally or globally.
  16873. If the cursor is on a LaTeX fragment, create the image and overlay
  16874. it over the source code, if there is none. Remove it otherwise.
  16875. If there is no fragment at point, display all fragments in the
  16876. current section.
  16877. With prefix ARG, preview or clear image for all fragments in the
  16878. current subtree or in the whole buffer when used before the first
  16879. headline. With a prefix ARG `\\[universal-argument] \
  16880. \\[universal-argument]' preview or clear images
  16881. for all fragments in the buffer."
  16882. (interactive "P")
  16883. (when (display-graphic-p)
  16884. (catch 'exit
  16885. (save-excursion
  16886. (let (beg end msg)
  16887. (cond
  16888. ((or (equal arg '(16))
  16889. (and (equal arg '(4))
  16890. (org-with-limited-levels (org-before-first-heading-p))))
  16891. (if (org-remove-latex-fragment-image-overlays)
  16892. (progn (message "LaTeX fragments images removed from buffer")
  16893. (throw 'exit nil))
  16894. (setq msg "Creating images for buffer...")))
  16895. ((equal arg '(4))
  16896. (org-with-limited-levels (org-back-to-heading t))
  16897. (setq beg (point))
  16898. (setq end (progn (org-end-of-subtree t) (point)))
  16899. (if (org-remove-latex-fragment-image-overlays beg end)
  16900. (progn
  16901. (message "LaTeX fragment images removed from subtree")
  16902. (throw 'exit nil))
  16903. (setq msg "Creating images for subtree...")))
  16904. ((let ((datum (org-element-context)))
  16905. (when (memq (org-element-type datum)
  16906. '(latex-environment latex-fragment))
  16907. (setq beg (org-element-property :begin datum))
  16908. (setq end (org-element-property :end datum))
  16909. (if (org-remove-latex-fragment-image-overlays beg end)
  16910. (progn (message "LaTeX fragment image removed")
  16911. (throw 'exit nil))
  16912. (setq msg "Creating image...")))))
  16913. (t
  16914. (org-with-limited-levels
  16915. (setq beg (if (org-at-heading-p) (line-beginning-position)
  16916. (outline-previous-heading)
  16917. (point)))
  16918. (setq end (progn (outline-next-heading) (point)))
  16919. (if (org-remove-latex-fragment-image-overlays beg end)
  16920. (progn
  16921. (message "LaTeX fragment images removed from section")
  16922. (throw 'exit nil))
  16923. (setq msg "Creating images for section...")))))
  16924. (let ((file (buffer-file-name (buffer-base-buffer))))
  16925. (org-format-latex
  16926. (concat org-preview-latex-image-directory "org-ltximg")
  16927. beg end
  16928. ;; Emacs cannot overlay images from remote hosts. Create
  16929. ;; it in `temporary-file-directory' instead.
  16930. (if (or (not file) (file-remote-p file))
  16931. temporary-file-directory
  16932. default-directory)
  16933. 'overlays msg 'forbuffer org-preview-latex-default-process))
  16934. (message (concat msg "done")))))))
  16935. (defun org-format-latex
  16936. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  16937. "Replace LaTeX fragments with links to an image.
  16938. The function takes care of creating the replacement image.
  16939. Only consider fragments between BEG and END when those are
  16940. provided.
  16941. When optional argument OVERLAYS is non-nil, display the image on
  16942. top of the fragment instead of replacing it.
  16943. PROCESSING-TYPE is the conversion method to use, as a symbol.
  16944. Some of the options can be changed using the variable
  16945. `org-format-latex-options', which see."
  16946. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  16947. (unless (eq processing-type 'verbatim)
  16948. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  16949. (cnt 0)
  16950. checkdir-flag)
  16951. (goto-char (or beg (point-min)))
  16952. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  16953. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  16954. (overlay-recenter (or end (point-max))))
  16955. (while (re-search-forward math-regexp end t)
  16956. (unless (and overlays
  16957. (eq (get-char-property (point) 'org-overlay-type)
  16958. 'org-latex-overlay))
  16959. (let* ((context (org-element-context))
  16960. (type (org-element-type context)))
  16961. (when (memq type '(latex-environment latex-fragment))
  16962. (let ((block-type (eq type 'latex-environment))
  16963. (value (org-element-property :value context))
  16964. (beg (org-element-property :begin context))
  16965. (end (save-excursion
  16966. (goto-char (org-element-property :end context))
  16967. (skip-chars-backward " \r\t\n")
  16968. (point))))
  16969. (cond
  16970. ((eq processing-type 'mathjax)
  16971. ;; Prepare for MathJax processing.
  16972. (if (not (string-match "\\`\\$\\$?" value))
  16973. (goto-char end)
  16974. (delete-region beg end)
  16975. (if (string= (match-string 0 value) "$$")
  16976. (insert "\\[" (substring value 2 -2) "\\]")
  16977. (insert "\\(" (substring value 1 -1) "\\)"))))
  16978. ((assq processing-type org-preview-latex-process-alist)
  16979. ;; Process to an image.
  16980. (cl-incf cnt)
  16981. (goto-char beg)
  16982. (let* ((processing-info
  16983. (cdr (assq processing-type org-preview-latex-process-alist)))
  16984. (face (face-at-point))
  16985. ;; Get the colors from the face at point.
  16986. (fg
  16987. (let ((color (plist-get org-format-latex-options
  16988. :foreground)))
  16989. (if (and forbuffer (eq color 'auto))
  16990. (face-attribute face :foreground nil 'default)
  16991. color)))
  16992. (bg
  16993. (let ((color (plist-get org-format-latex-options
  16994. :background)))
  16995. (if (and forbuffer (eq color 'auto))
  16996. (face-attribute face :background nil 'default)
  16997. color)))
  16998. (hash (sha1 (prin1-to-string
  16999. (list org-format-latex-header
  17000. org-latex-default-packages-alist
  17001. org-latex-packages-alist
  17002. org-format-latex-options
  17003. forbuffer value fg bg))))
  17004. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  17005. (absprefix (expand-file-name prefix dir))
  17006. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  17007. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  17008. (sep (and block-type "\n\n"))
  17009. (link (concat sep "[[file:" linkfile "]]" sep))
  17010. (options
  17011. (org-combine-plists
  17012. org-format-latex-options
  17013. `(:foreground ,fg :background ,bg))))
  17014. (when msg (message msg cnt))
  17015. (unless checkdir-flag ; Ensure the directory exists.
  17016. (setq checkdir-flag t)
  17017. (let ((todir (file-name-directory absprefix)))
  17018. (unless (file-directory-p todir)
  17019. (make-directory todir t))))
  17020. (unless (file-exists-p movefile)
  17021. (org-create-formula-image
  17022. value movefile options forbuffer processing-type))
  17023. (if overlays
  17024. (progn
  17025. (dolist (o (overlays-in beg end))
  17026. (when (eq (overlay-get o 'org-overlay-type)
  17027. 'org-latex-overlay)
  17028. (delete-overlay o)))
  17029. (org--format-latex-make-overlay beg end movefile imagetype)
  17030. (goto-char end))
  17031. (delete-region beg end)
  17032. (insert
  17033. (org-add-props link
  17034. (list 'org-latex-src
  17035. (replace-regexp-in-string "\"" "" value)
  17036. 'org-latex-src-embed-type
  17037. (if block-type 'paragraph 'character)))))))
  17038. ((eq processing-type 'mathml)
  17039. ;; Process to MathML.
  17040. (unless (org-format-latex-mathml-available-p)
  17041. (user-error "LaTeX to MathML converter not configured"))
  17042. (cl-incf cnt)
  17043. (when msg (message msg cnt))
  17044. (goto-char beg)
  17045. (delete-region beg end)
  17046. (insert (org-format-latex-as-mathml
  17047. value block-type prefix dir)))
  17048. (t
  17049. (error "Unknown conversion process %s for LaTeX fragments"
  17050. processing-type)))))))))))
  17051. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17052. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17053. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17054. sucessful, return the portion between \"<math...> </math>\"
  17055. elements otherwise return nil. When MATHML-FILE is specified,
  17056. write the results in to that file. When invoked as an
  17057. interactive command, prompt for LATEX-FRAG, with initial value
  17058. set to the current active region and echo the results for user
  17059. inspection."
  17060. (interactive (list (let ((frag (when (org-region-active-p)
  17061. (buffer-substring-no-properties
  17062. (region-beginning) (region-end)))))
  17063. (read-string "LaTeX Fragment: " frag nil frag))))
  17064. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17065. (let* ((tmp-in-file
  17066. (let ((file (file-relative-name
  17067. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17068. (write-region latex-frag nil file)
  17069. file))
  17070. (tmp-out-file (file-relative-name
  17071. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17072. (cmd (format-spec
  17073. org-latex-to-mathml-convert-command
  17074. `((?j . ,(and org-latex-to-mathml-jar-file
  17075. (shell-quote-argument
  17076. (expand-file-name
  17077. org-latex-to-mathml-jar-file))))
  17078. (?I . ,(shell-quote-argument tmp-in-file))
  17079. (?i . ,latex-frag)
  17080. (?o . ,(shell-quote-argument tmp-out-file)))))
  17081. mathml shell-command-output)
  17082. (when (called-interactively-p 'any)
  17083. (unless (org-format-latex-mathml-available-p)
  17084. (user-error "LaTeX to MathML converter not configured")))
  17085. (message "Running %s" cmd)
  17086. (setq shell-command-output (shell-command-to-string cmd))
  17087. (setq mathml
  17088. (when (file-readable-p tmp-out-file)
  17089. (with-current-buffer (find-file-noselect tmp-out-file t)
  17090. (goto-char (point-min))
  17091. (when (re-search-forward
  17092. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  17093. (regexp-quote
  17094. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  17095. nil t)
  17096. (prog1 (match-string 0) (kill-buffer))))))
  17097. (cond
  17098. (mathml
  17099. (setq mathml
  17100. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17101. (when mathml-file
  17102. (write-region mathml nil mathml-file))
  17103. (when (called-interactively-p 'any)
  17104. (message mathml)))
  17105. ((message "LaTeX to MathML conversion failed")
  17106. (message shell-command-output)))
  17107. (delete-file tmp-in-file)
  17108. (when (file-exists-p tmp-out-file)
  17109. (delete-file tmp-out-file))
  17110. mathml))
  17111. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17112. prefix &optional dir)
  17113. "Use `org-create-math-formula' but check local cache first."
  17114. (let* ((absprefix (expand-file-name prefix dir))
  17115. (print-length nil) (print-level nil)
  17116. (formula-id (concat
  17117. "formula-"
  17118. (sha1
  17119. (prin1-to-string
  17120. (list latex-frag
  17121. org-latex-to-mathml-convert-command)))))
  17122. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17123. (formula-cache-dir (file-name-directory formula-cache)))
  17124. (unless (file-directory-p formula-cache-dir)
  17125. (make-directory formula-cache-dir t))
  17126. (unless (file-exists-p formula-cache)
  17127. (org-create-math-formula latex-frag formula-cache))
  17128. (if (file-exists-p formula-cache)
  17129. ;; Successful conversion. Return the link to MathML file.
  17130. (org-add-props
  17131. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17132. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17133. 'org-latex-src-embed-type (if latex-frag-type
  17134. 'paragraph 'character)))
  17135. ;; Failed conversion. Return the LaTeX fragment verbatim
  17136. latex-frag)))
  17137. (defun org--get-display-dpi ()
  17138. "Get the DPI of the display.
  17139. The function assumes that the display has the same pixel width in
  17140. the horizontal and vertical directions."
  17141. (if (display-graphic-p)
  17142. (round (/ (display-pixel-height)
  17143. (/ (display-mm-height) 25.4)))
  17144. (error "Attempt to calculate the dpi of a non-graphic display")))
  17145. (defun org-create-formula-image
  17146. (string tofile options buffer &optional processing-type)
  17147. "Create an image from LaTeX source using external processes.
  17148. The LaTeX STRING is saved to a temporary LaTeX file, then
  17149. converted to an image file by process PROCESSING-TYPE defined in
  17150. `org-preview-latex-process-alist'. A nil value defaults to
  17151. `org-preview-latex-default-process'.
  17152. The generated image file is eventually moved to TOFILE.
  17153. The OPTIONS argument controls the size, foreground color and
  17154. background color of the generated image.
  17155. When BUFFER non-nil, this function is used for LaTeX previewing.
  17156. Otherwise, it is used to deal with LaTeX snippets showed in
  17157. a HTML file."
  17158. (let* ((processing-type (or processing-type
  17159. org-preview-latex-default-process))
  17160. (processing-info
  17161. (cdr (assq processing-type org-preview-latex-process-alist)))
  17162. (programs (plist-get processing-info :programs))
  17163. (error-message (or (plist-get processing-info :message) ""))
  17164. (use-xcolor (plist-get processing-info :use-xcolor))
  17165. (image-input-type (plist-get processing-info :image-input-type))
  17166. (image-output-type (plist-get processing-info :image-output-type))
  17167. (post-clean (or (plist-get processing-info :post-clean)
  17168. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  17169. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  17170. (latex-header
  17171. (or (plist-get processing-info :latex-header)
  17172. (org-latex-make-preamble
  17173. (org-export-get-environment (org-export-get-backend 'latex))
  17174. org-format-latex-header
  17175. 'snippet)))
  17176. (latex-compiler (plist-get processing-info :latex-compiler))
  17177. (image-converter (plist-get processing-info :image-converter))
  17178. (tmpdir temporary-file-directory)
  17179. (texfilebase (make-temp-name
  17180. (expand-file-name "orgtex" tmpdir)))
  17181. (texfile (concat texfilebase ".tex"))
  17182. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  17183. '(1.0 . 1.0)))
  17184. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  17185. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  17186. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  17187. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17188. "Black"))
  17189. (bg (or (plist-get options (if buffer :background :html-background))
  17190. "Transparent"))
  17191. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  17192. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  17193. (dolist (program programs)
  17194. (org-check-external-command program error-message))
  17195. (if use-xcolor
  17196. (progn (if (eq fg 'default)
  17197. (setq fg (org-latex-color :foreground))
  17198. (setq fg (org-latex-color-format fg)))
  17199. (if (eq bg 'default)
  17200. (setq bg (org-latex-color :background))
  17201. (setq bg (org-latex-color-format
  17202. (if (string= bg "Transparent") "white" bg))))
  17203. (with-temp-file texfile
  17204. (insert latex-header)
  17205. (insert "\n\\begin{document}\n"
  17206. "\\definecolor{fg}{rgb}{" fg "}\n"
  17207. "\\definecolor{bg}{rgb}{" bg "}\n"
  17208. "\n\\pagecolor{bg}\n"
  17209. "\n{\\color{fg}\n"
  17210. string
  17211. "\n}\n"
  17212. "\n\\end{document}\n")))
  17213. (if (eq fg 'default)
  17214. (setq fg (org-dvipng-color :foreground))
  17215. (unless (string= fg "Transparent")
  17216. (setq fg (org-dvipng-color-format fg))))
  17217. (if (eq bg 'default)
  17218. (setq bg (org-dvipng-color :background))
  17219. (unless (string= bg "Transparent")
  17220. (setq bg (org-dvipng-color-format bg))))
  17221. (with-temp-file texfile
  17222. (insert latex-header)
  17223. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17224. (let* ((err-msg (format "Please adjust `%s' part of \
  17225. `org-preview-latex-process-alist'."
  17226. processing-type))
  17227. (image-input-file
  17228. (org-compile-file
  17229. texfile latex-compiler image-input-type err-msg log-buf))
  17230. (image-output-file
  17231. (org-compile-file
  17232. image-input-file image-converter image-output-type err-msg log-buf
  17233. `((?F . ,(shell-quote-argument fg))
  17234. (?B . ,(shell-quote-argument bg))
  17235. (?D . ,(shell-quote-argument (format "%s" dpi)))
  17236. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  17237. (copy-file image-output-file tofile 'replace)
  17238. (dolist (e post-clean)
  17239. (when (file-exists-p (concat texfilebase e))
  17240. (delete-file (concat texfilebase e))))
  17241. image-output-file)))
  17242. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17243. "Fill a LaTeX header template TPL.
  17244. In the template, the following place holders will be recognized:
  17245. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17246. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17247. [PACKAGES] \\usepackage statements for PKG
  17248. [NO-PACKAGES] do not include PKG
  17249. [EXTRA] the string EXTRA
  17250. [NO-EXTRA] do not include EXTRA
  17251. For backward compatibility, if both the positive and the negative place
  17252. holder is missing, the positive one (without the \"NO-\") will be
  17253. assumed to be present at the end of the template.
  17254. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17255. EXTRA is a string.
  17256. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17257. (let (rpl (end ""))
  17258. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17259. (setq rpl (if (or (match-end 1) (not def-pkg))
  17260. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17261. tpl (replace-match rpl t t tpl))
  17262. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17263. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17264. (setq rpl (if (or (match-end 1) (not pkg))
  17265. "" (org-latex-packages-to-string pkg snippets-p t))
  17266. tpl (replace-match rpl t t tpl))
  17267. (when pkg (setq end
  17268. (concat end "\n"
  17269. (org-latex-packages-to-string pkg snippets-p)))))
  17270. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17271. (setq rpl (if (or (match-end 1) (not extra))
  17272. "" (concat extra "\n"))
  17273. tpl (replace-match rpl t t tpl))
  17274. (when (and extra (string-match "\\S-" extra))
  17275. (setq end (concat end "\n" extra))))
  17276. (if (string-match "\\S-" end)
  17277. (concat tpl "\n" end)
  17278. tpl)))
  17279. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17280. "Turn an alist of packages into a string with the \\usepackage macros."
  17281. (setq pkg (mapconcat (lambda(p)
  17282. (cond
  17283. ((stringp p) p)
  17284. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17285. (format "%% Package %s omitted" (cadr p)))
  17286. ((equal "" (car p))
  17287. (format "\\usepackage{%s}" (cadr p)))
  17288. (t
  17289. (format "\\usepackage[%s]{%s}"
  17290. (car p) (cadr p)))))
  17291. pkg
  17292. "\n"))
  17293. (if newline (concat pkg "\n") pkg))
  17294. (defun org-dvipng-color (attr)
  17295. "Return a RGB color specification for dvipng."
  17296. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17297. (defun org-dvipng-color-format (color-name)
  17298. "Convert COLOR-NAME to a RGB color value for dvipng."
  17299. (apply #'format "rgb %s %s %s"
  17300. (mapcar 'org-normalize-color
  17301. (color-values color-name))))
  17302. (defun org-latex-color (attr)
  17303. "Return a RGB color for the LaTeX color package."
  17304. (org-latex-color-format (face-attribute 'default attr nil)))
  17305. (defun org-latex-color-format (color-name)
  17306. "Convert COLOR-NAME to a RGB color value."
  17307. (apply #'format "%s,%s,%s"
  17308. (mapcar 'org-normalize-color
  17309. (color-values color-name))))
  17310. (defun org-normalize-color (value)
  17311. "Return string to be used as color value for an RGB component."
  17312. (format "%g" (/ value 65535.0)))
  17313. ;; Image display
  17314. (defvar-local org-inline-image-overlays nil)
  17315. (defun org-toggle-inline-images (&optional include-linked)
  17316. "Toggle the display of inline images.
  17317. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17318. (interactive "P")
  17319. (if org-inline-image-overlays
  17320. (progn
  17321. (org-remove-inline-images)
  17322. (when (called-interactively-p 'interactive)
  17323. (message "Inline image display turned off")))
  17324. (org-display-inline-images include-linked)
  17325. (when (called-interactively-p 'interactive)
  17326. (message (if org-inline-image-overlays
  17327. (format "%d images displayed inline"
  17328. (length org-inline-image-overlays))
  17329. "No images to display inline")))))
  17330. (defun org-redisplay-inline-images ()
  17331. "Refresh the display of inline images."
  17332. (interactive)
  17333. (if (not org-inline-image-overlays)
  17334. (org-toggle-inline-images)
  17335. (org-toggle-inline-images)
  17336. (org-toggle-inline-images)))
  17337. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17338. "Display inline images.
  17339. An inline image is a link which follows either of these
  17340. conventions:
  17341. 1. Its path is a file with an extension matching return value
  17342. from `image-file-name-regexp' and it has no contents.
  17343. 2. Its description consists in a single link of the previous
  17344. type.
  17345. When optional argument INCLUDE-LINKED is non-nil, also links with
  17346. a text description part will be inlined. This can be nice for
  17347. a quick look at those images, but it does not reflect what
  17348. exported files will look like.
  17349. When optional argument REFRESH is non-nil, refresh existing
  17350. images between BEG and END. This will create new image displays
  17351. only if necessary. BEG and END default to the buffer
  17352. boundaries."
  17353. (interactive "P")
  17354. (when (display-graphic-p)
  17355. (unless refresh
  17356. (org-remove-inline-images)
  17357. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17358. (org-with-wide-buffer
  17359. (goto-char (or beg (point-min)))
  17360. (let* ((case-fold-search t)
  17361. (file-extension-re (image-file-name-regexp))
  17362. (link-abbrevs (mapcar #'car
  17363. (append org-link-abbrev-alist-local
  17364. org-link-abbrev-alist)))
  17365. ;; Check absolute, relative file names and explicit
  17366. ;; "file:" links. Also check link abbreviations since
  17367. ;; some might expand to "file" links.
  17368. (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
  17369. (if (not link-abbrevs) ""
  17370. (format "\\|\\(?:%s:\\)"
  17371. (regexp-opt link-abbrevs))))))
  17372. (while (re-search-forward file-types-re end t)
  17373. (let ((link (save-match-data (org-element-context))))
  17374. ;; Check if we're at an inline image, i.e., an image file
  17375. ;; link without a description (unless INCLUDE-LINKED is
  17376. ;; non-nil).
  17377. (when (and (equal "file" (org-element-property :type link))
  17378. (or include-linked
  17379. (null (org-element-contents link)))
  17380. (string-match-p file-extension-re
  17381. (org-element-property :path link)))
  17382. (let ((file (expand-file-name
  17383. (org-link-unescape
  17384. (org-element-property :path link)))))
  17385. (when (file-exists-p file)
  17386. (let ((width
  17387. ;; Apply `org-image-actual-width' specifications.
  17388. (cond
  17389. ((not (image-type-available-p 'imagemagick)) nil)
  17390. ((eq org-image-actual-width t) nil)
  17391. ((listp org-image-actual-width)
  17392. (or
  17393. ;; First try to find a width among
  17394. ;; attributes associated to the paragraph
  17395. ;; containing link.
  17396. (let ((paragraph
  17397. (let ((e link))
  17398. (while (and (setq e (org-element-property
  17399. :parent e))
  17400. (not (eq (org-element-type e)
  17401. 'paragraph))))
  17402. e)))
  17403. (when paragraph
  17404. (save-excursion
  17405. (goto-char (org-element-property :begin paragraph))
  17406. (when
  17407. (re-search-forward
  17408. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17409. (org-element-property
  17410. :post-affiliated paragraph)
  17411. t)
  17412. (string-to-number (match-string 1))))))
  17413. ;; Otherwise, fall-back to provided number.
  17414. (car org-image-actual-width)))
  17415. ((numberp org-image-actual-width)
  17416. org-image-actual-width)))
  17417. (old (get-char-property-and-overlay
  17418. (org-element-property :begin link)
  17419. 'org-image-overlay)))
  17420. (if (and (car-safe old) refresh)
  17421. (image-refresh (overlay-get (cdr old) 'display))
  17422. (let ((image (create-image file
  17423. (and width 'imagemagick)
  17424. nil
  17425. :width width)))
  17426. (when image
  17427. (let ((ov (make-overlay
  17428. (org-element-property :begin link)
  17429. (progn
  17430. (goto-char
  17431. (org-element-property :end link))
  17432. (skip-chars-backward " \t")
  17433. (point)))))
  17434. (overlay-put ov 'display image)
  17435. (overlay-put ov 'face 'default)
  17436. (overlay-put ov 'org-image-overlay t)
  17437. (overlay-put
  17438. ov 'modification-hooks
  17439. (list 'org-display-inline-remove-overlay))
  17440. (push ov org-inline-image-overlays)))))))))))))))
  17441. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17442. "Remove inline-display overlay if a corresponding region is modified."
  17443. (let ((inhibit-modification-hooks t))
  17444. (when (and ov after)
  17445. (delete ov org-inline-image-overlays)
  17446. (delete-overlay ov))))
  17447. (defun org-remove-inline-images ()
  17448. "Remove inline display of images."
  17449. (interactive)
  17450. (mapc #'delete-overlay org-inline-image-overlays)
  17451. (setq org-inline-image-overlays nil))
  17452. ;;;; Key bindings
  17453. (defun org-remap (map &rest commands)
  17454. "In MAP, remap the functions given in COMMANDS.
  17455. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  17456. (let (new old)
  17457. (while commands
  17458. (setq old (pop commands) new (pop commands))
  17459. (org-defkey map (vector 'remap old) new))))
  17460. ;; Outline functions from `outline-mode-prefix-map'
  17461. ;; that can be remapped in Org:
  17462. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  17463. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  17464. (define-key org-mode-map [remap outline-forward-same-level]
  17465. 'org-forward-heading-same-level)
  17466. (define-key org-mode-map [remap outline-backward-same-level]
  17467. 'org-backward-heading-same-level)
  17468. (define-key org-mode-map [remap outline-show-branches]
  17469. 'org-kill-note-or-show-branches)
  17470. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  17471. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  17472. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  17473. (define-key org-mode-map [remap outline-next-visible-heading]
  17474. 'org-next-visible-heading)
  17475. (define-key org-mode-map [remap outline-previous-visible-heading]
  17476. 'org-previous-visible-heading)
  17477. (define-key org-mode-map [remap show-children] 'org-show-children)
  17478. ;; Outline functions from `outline-mode-prefix-map' that can not
  17479. ;; be remapped in Org:
  17480. ;; - the column "key binding" shows whether the Outline function is still
  17481. ;; available in Org mode on the same key that it has been bound to in
  17482. ;; Outline mode:
  17483. ;; - "overridden": key used for a different functionality in Org mode
  17484. ;; - else: key still bound to the same Outline function in Org mode
  17485. ;; | Outline function | key binding | Org replacement |
  17486. ;; |------------------------------------+-------------+--------------------------|
  17487. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  17488. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  17489. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  17490. ;; | `show-entry' | overridden | no replacement |
  17491. ;; | `show-branches' | `C-c C-k' | still same function |
  17492. ;; | `show-subtree' | overridden | visibility cycling |
  17493. ;; | `show-all' | overridden | no replacement |
  17494. ;; | `hide-subtree' | overridden | visibility cycling |
  17495. ;; | `hide-body' | overridden | no replacement |
  17496. ;; | `hide-entry' | overridden | visibility cycling |
  17497. ;; | `hide-leaves' | overridden | no replacement |
  17498. ;; | `hide-sublevels' | overridden | no replacement |
  17499. ;; | `hide-other' | overridden | no replacement |
  17500. ;; Make `C-c C-x' a prefix key
  17501. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  17502. ;; TAB key with modifiers
  17503. (org-defkey org-mode-map "\C-i" 'org-cycle)
  17504. (org-defkey org-mode-map [(tab)] 'org-cycle)
  17505. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  17506. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  17507. ;; The following line is necessary under Suse GNU/Linux
  17508. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  17509. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  17510. (define-key org-mode-map [backtab] 'org-shifttab)
  17511. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  17512. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  17513. (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
  17514. ;; Cursor keys with modifiers
  17515. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  17516. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  17517. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  17518. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  17519. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  17520. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  17521. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  17522. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  17523. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  17524. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  17525. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  17526. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  17527. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  17528. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  17529. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  17530. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  17531. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  17532. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  17533. ;; Babel keys
  17534. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  17535. (dolist (pair org-babel-key-bindings)
  17536. (define-key org-babel-map (car pair) (cdr pair)))
  17537. ;;; Extra keys for tty access.
  17538. ;; We only set them when really needed because otherwise the
  17539. ;; menus don't show the simple keys
  17540. (when (or org-use-extra-keys (not window-system))
  17541. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  17542. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  17543. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  17544. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  17545. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  17546. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  17547. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  17548. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  17549. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  17550. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  17551. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  17552. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  17553. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  17554. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  17555. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  17556. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  17557. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  17558. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  17559. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  17560. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  17561. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  17562. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  17563. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  17564. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  17565. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  17566. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  17567. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  17568. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  17569. ;; All the other keys
  17570. (org-remap org-mode-map
  17571. 'self-insert-command 'org-self-insert-command
  17572. 'delete-char 'org-delete-char
  17573. 'delete-backward-char 'org-delete-backward-char)
  17574. (org-defkey org-mode-map "|" 'org-force-self-insert)
  17575. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  17576. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  17577. (if (boundp 'narrow-map)
  17578. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  17579. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  17580. (if (boundp 'narrow-map)
  17581. (org-defkey narrow-map "b" 'org-narrow-to-block)
  17582. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  17583. (if (boundp 'narrow-map)
  17584. (org-defkey narrow-map "e" 'org-narrow-to-element)
  17585. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  17586. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  17587. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  17588. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  17589. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  17590. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  17591. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  17592. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  17593. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  17594. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  17595. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  17596. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  17597. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  17598. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  17599. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  17600. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  17601. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  17602. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  17603. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  17604. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  17605. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  17606. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  17607. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  17608. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  17609. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  17610. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  17611. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  17612. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  17613. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  17614. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  17615. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  17616. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  17617. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  17618. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  17619. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  17620. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  17621. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  17622. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  17623. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  17624. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  17625. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  17626. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  17627. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  17628. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  17629. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  17630. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  17631. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  17632. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  17633. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  17634. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  17635. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  17636. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  17637. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  17638. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  17639. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  17640. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  17641. (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
  17642. (org-defkey org-mode-map "\C-c^" 'org-sort)
  17643. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  17644. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  17645. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  17646. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  17647. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  17648. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  17649. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  17650. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  17651. (org-defkey org-mode-map "\C-m" 'org-return)
  17652. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  17653. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  17654. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  17655. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  17656. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  17657. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  17658. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  17659. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  17660. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  17661. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  17662. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  17663. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  17664. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  17665. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  17666. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  17667. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  17668. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  17669. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  17670. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  17671. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  17672. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  17673. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  17674. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  17675. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  17676. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  17677. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  17678. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  17679. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  17680. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  17681. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  17682. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  17683. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  17684. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  17685. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  17686. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  17687. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  17688. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  17689. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  17690. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  17691. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  17692. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  17693. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  17694. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  17695. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  17696. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  17697. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  17698. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  17699. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  17700. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  17701. (org-defkey org-mode-map "\C-c\C-xw" 'org-insert-structure-template)
  17702. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  17703. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  17704. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  17705. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  17706. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  17707. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  17708. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  17709. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  17710. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  17711. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  17712. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  17713. (defconst org-speed-commands-default
  17714. '(
  17715. ("Outline Navigation")
  17716. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  17717. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  17718. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  17719. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  17720. ("F" . org-next-block)
  17721. ("B" . org-previous-block)
  17722. ("u" . (org-speed-move-safe 'outline-up-heading))
  17723. ("j" . org-goto)
  17724. ("g" . (org-refile t))
  17725. ("Outline Visibility")
  17726. ("c" . org-cycle)
  17727. ("C" . org-shifttab)
  17728. (" " . org-display-outline-path)
  17729. ("s" . org-narrow-to-subtree)
  17730. ("=" . org-columns)
  17731. ("Outline Structure Editing")
  17732. ("U" . org-metaup)
  17733. ("D" . org-metadown)
  17734. ("r" . org-metaright)
  17735. ("l" . org-metaleft)
  17736. ("R" . org-shiftmetaright)
  17737. ("L" . org-shiftmetaleft)
  17738. ("i" . (progn (forward-char 1) (call-interactively
  17739. 'org-insert-heading-respect-content)))
  17740. ("^" . org-sort)
  17741. ("w" . org-refile)
  17742. ("a" . org-archive-subtree-default-with-confirmation)
  17743. ("@" . org-mark-subtree)
  17744. ("#" . org-toggle-comment)
  17745. ("Clock Commands")
  17746. ("I" . org-clock-in)
  17747. ("O" . org-clock-out)
  17748. ("Meta Data Editing")
  17749. ("t" . org-todo)
  17750. ("," . (org-priority))
  17751. ("0" . (org-priority ?\ ))
  17752. ("1" . (org-priority ?A))
  17753. ("2" . (org-priority ?B))
  17754. ("3" . (org-priority ?C))
  17755. (":" . org-set-tags-command)
  17756. ("e" . org-set-effort)
  17757. ("E" . org-inc-effort)
  17758. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  17759. (org-entry-put (point) "APPT_WARNTIME" m)))
  17760. ("Agenda Views etc")
  17761. ("v" . org-agenda)
  17762. ("/" . org-sparse-tree)
  17763. ("Misc")
  17764. ("o" . org-open-at-point)
  17765. ("?" . org-speed-command-help)
  17766. ("<" . (org-agenda-set-restriction-lock 'subtree))
  17767. (">" . (org-agenda-remove-restriction-lock))
  17768. )
  17769. "The default speed commands.")
  17770. (defun org-print-speed-command (e)
  17771. (if (> (length (car e)) 1)
  17772. (progn
  17773. (princ "\n")
  17774. (princ (car e))
  17775. (princ "\n")
  17776. (princ (make-string (length (car e)) ?-))
  17777. (princ "\n"))
  17778. (princ (car e))
  17779. (princ " ")
  17780. (if (symbolp (cdr e))
  17781. (princ (symbol-name (cdr e)))
  17782. (prin1 (cdr e)))
  17783. (princ "\n")))
  17784. (defun org-speed-command-help ()
  17785. "Show the available speed commands."
  17786. (interactive)
  17787. (if (not org-use-speed-commands)
  17788. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  17789. (with-output-to-temp-buffer "*Help*"
  17790. (princ "User-defined Speed commands\n===========================\n")
  17791. (mapc #'org-print-speed-command org-speed-commands-user)
  17792. (princ "\n")
  17793. (princ "Built-in Speed commands\n=======================\n")
  17794. (mapc #'org-print-speed-command org-speed-commands-default))
  17795. (with-current-buffer "*Help*"
  17796. (setq truncate-lines t))))
  17797. (defun org-speed-move-safe (cmd)
  17798. "Execute CMD, but make sure that the cursor always ends up in a headline.
  17799. If not, return to the original position and throw an error."
  17800. (interactive)
  17801. (let ((pos (point)))
  17802. (call-interactively cmd)
  17803. (unless (and (bolp) (org-at-heading-p))
  17804. (goto-char pos)
  17805. (error "Boundary reached while executing %s" cmd))))
  17806. (defvar org-self-insert-command-undo-counter 0)
  17807. (defvar org-table-auto-blank-field) ; defined in org-table.el
  17808. (defvar org-speed-command nil)
  17809. (defun org-speed-command-activate (keys)
  17810. "Hook for activating single-letter speed commands.
  17811. `org-speed-commands-default' specifies a minimal command set.
  17812. Use `org-speed-commands-user' for further customization."
  17813. (when (or (and (bolp) (looking-at org-outline-regexp))
  17814. (and (functionp org-use-speed-commands)
  17815. (funcall org-use-speed-commands)))
  17816. (cdr (assoc keys (append org-speed-commands-user
  17817. org-speed-commands-default)))))
  17818. (defun org-babel-speed-command-activate (keys)
  17819. "Hook for activating single-letter code block commands."
  17820. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  17821. (cdr (assoc keys org-babel-key-bindings))))
  17822. (defcustom org-speed-command-hook
  17823. '(org-speed-command-activate org-babel-speed-command-activate)
  17824. "Hook for activating speed commands at strategic locations.
  17825. Hook functions are called in sequence until a valid handler is
  17826. found.
  17827. Each hook takes a single argument, a user-pressed command key
  17828. which is also a `self-insert-command' from the global map.
  17829. Within the hook, examine the cursor position and the command key
  17830. and return nil or a valid handler as appropriate. Handler could
  17831. be one of an interactive command, a function, or a form.
  17832. Set `org-use-speed-commands' to non-nil value to enable this
  17833. hook. The default setting is `org-speed-command-activate'."
  17834. :group 'org-structure
  17835. :version "24.1"
  17836. :type 'hook)
  17837. (defun org-self-insert-command (N)
  17838. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  17839. If the cursor is in a table looking at whitespace, the whitespace is
  17840. overwritten, and the table is not marked as requiring realignment."
  17841. (interactive "p")
  17842. (org-check-before-invisible-edit 'insert)
  17843. (cond
  17844. ((and org-use-speed-commands
  17845. (let ((kv (this-command-keys-vector)))
  17846. (setq org-speed-command
  17847. (run-hook-with-args-until-success
  17848. 'org-speed-command-hook
  17849. (make-string 1 (aref kv (1- (length kv))))))))
  17850. (cond
  17851. ((commandp org-speed-command)
  17852. (setq this-command org-speed-command)
  17853. (call-interactively org-speed-command))
  17854. ((functionp org-speed-command)
  17855. (funcall org-speed-command))
  17856. ((and org-speed-command (listp org-speed-command))
  17857. (eval org-speed-command))
  17858. (t (let (org-use-speed-commands)
  17859. (call-interactively 'org-self-insert-command)))))
  17860. ((and
  17861. (org-at-table-p)
  17862. (eq N 1)
  17863. (not (org-region-active-p))
  17864. (progn
  17865. ;; Check if we blank the field, and if that triggers align.
  17866. (and (featurep 'org-table) org-table-auto-blank-field
  17867. (memq last-command
  17868. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  17869. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  17870. ;; Got extra space, this field does not determine
  17871. ;; column width.
  17872. (let (org-table-may-need-update) (org-table-blank-field))
  17873. ;; No extra space, this field may determine column
  17874. ;; width.
  17875. (org-table-blank-field)))
  17876. t)
  17877. (looking-at "[^|\n]* \\( \\)|"))
  17878. ;; There is room for insertion without re-aligning the table.
  17879. (delete-region (match-beginning 1) (match-end 1))
  17880. (self-insert-command N))
  17881. (t
  17882. (setq org-table-may-need-update t)
  17883. (self-insert-command N)
  17884. (org-fix-tags-on-the-fly)
  17885. (when org-self-insert-cluster-for-undo
  17886. (if (not (eq last-command 'org-self-insert-command))
  17887. (setq org-self-insert-command-undo-counter 1)
  17888. (if (>= org-self-insert-command-undo-counter 20)
  17889. (setq org-self-insert-command-undo-counter 1)
  17890. (and (> org-self-insert-command-undo-counter 0)
  17891. buffer-undo-list (listp buffer-undo-list)
  17892. (not (cadr buffer-undo-list)) ; remove nil entry
  17893. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  17894. (setq org-self-insert-command-undo-counter
  17895. (1+ org-self-insert-command-undo-counter))))))))
  17896. (defun org-check-before-invisible-edit (kind)
  17897. "Check is editing if kind KIND would be dangerous with invisible text around.
  17898. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  17899. ;; First, try to get out of here as quickly as possible, to reduce overhead
  17900. (when (and org-catch-invisible-edits
  17901. (or (not (boundp 'visible-mode)) (not visible-mode))
  17902. (or (get-char-property (point) 'invisible)
  17903. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  17904. ;; OK, we need to take a closer look. Do not consider
  17905. ;; invisibility obtained through text properties (e.g., link
  17906. ;; fontification), as it cannot be toggled.
  17907. (let* ((invisible-at-point
  17908. (pcase (get-char-property-and-overlay (point) 'invisible)
  17909. (`(,_ . ,(and (pred overlayp) o)) o)))
  17910. ;; Assume that point cannot land in the middle of an
  17911. ;; overlay, or between two overlays.
  17912. (invisible-before-point
  17913. (and (not invisible-at-point)
  17914. (not (bobp))
  17915. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  17916. (`(,_ . ,(and (pred overlayp) o)) o))))
  17917. (border-and-ok-direction
  17918. (or
  17919. ;; Check if we are acting predictably before invisible
  17920. ;; text.
  17921. (and invisible-at-point
  17922. (memq kind '(insert delete-backward)))
  17923. ;; Check if we are acting predictably after invisible text
  17924. ;; This works not well, and I have turned it off. It seems
  17925. ;; better to always show and stop after invisible text.
  17926. ;; (and (not invisible-at-point) invisible-before-point
  17927. ;; (memq kind '(insert delete)))
  17928. )))
  17929. (when (or invisible-at-point invisible-before-point)
  17930. (when (eq org-catch-invisible-edits 'error)
  17931. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  17932. (if (and org-custom-properties-overlays
  17933. (y-or-n-p "Display invisible properties in this buffer? "))
  17934. (org-toggle-custom-properties-visibility)
  17935. ;; Make the area visible
  17936. (save-excursion
  17937. (when invisible-before-point
  17938. (goto-char
  17939. (previous-single-char-property-change (point) 'invisible)))
  17940. ;; Remove whatever overlay is currently making yet-to-be
  17941. ;; edited text invisible. Also remove nested invisibility
  17942. ;; related overlays.
  17943. (delete-overlay (or invisible-at-point invisible-before-point))
  17944. (let ((origin (if invisible-at-point (point) (1- (point)))))
  17945. (while (pcase (get-char-property-and-overlay origin 'invisible)
  17946. (`(,_ . ,(and (pred overlayp) o))
  17947. (delete-overlay o)
  17948. t)))))
  17949. (cond
  17950. ((eq org-catch-invisible-edits 'show)
  17951. ;; That's it, we do the edit after showing
  17952. (message
  17953. "Unfolding invisible region around point before editing")
  17954. (sit-for 1))
  17955. ((and (eq org-catch-invisible-edits 'smart)
  17956. border-and-ok-direction)
  17957. (message "Unfolding invisible region around point before editing"))
  17958. (t
  17959. ;; Don't do the edit, make the user repeat it in full visibility
  17960. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  17961. (defun org-fix-tags-on-the-fly ()
  17962. "Align tags in headline at point.
  17963. Unlike to `org-set-tags', it ignores region and sorting."
  17964. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  17965. (org-at-heading-p))
  17966. (let ((org-ignore-region t)
  17967. (org-tags-sort-function nil))
  17968. (org-set-tags nil t))))
  17969. (defun org-delete-backward-char (N)
  17970. "Like `delete-backward-char', insert whitespace at field end in tables.
  17971. When deleting backwards, in tables this function will insert whitespace in
  17972. front of the next \"|\" separator, to keep the table aligned. The table will
  17973. still be marked for re-alignment if the field did fill the entire column,
  17974. because, in this case the deletion might narrow the column."
  17975. (interactive "p")
  17976. (save-match-data
  17977. (org-check-before-invisible-edit 'delete-backward)
  17978. (if (and (org-at-table-p)
  17979. (eq N 1)
  17980. (not (org-region-active-p))
  17981. (string-match "|" (buffer-substring (point-at-bol) (point)))
  17982. (looking-at ".*?|"))
  17983. (let ((pos (point))
  17984. (noalign (looking-at "[^|\n\r]* |"))
  17985. (c org-table-may-need-update))
  17986. (backward-delete-char N)
  17987. (unless overwrite-mode
  17988. (skip-chars-forward "^|")
  17989. (insert " ")
  17990. (goto-char (1- pos)))
  17991. ;; noalign: if there were two spaces at the end, this field
  17992. ;; does not determine the width of the column.
  17993. (when noalign (setq org-table-may-need-update c)))
  17994. (backward-delete-char N)
  17995. (org-fix-tags-on-the-fly))))
  17996. (defun org-delete-char (N)
  17997. "Like `delete-char', but insert whitespace at field end in tables.
  17998. When deleting characters, in tables this function will insert whitespace in
  17999. front of the next \"|\" separator, to keep the table aligned. The table will
  18000. still be marked for re-alignment if the field did fill the entire column,
  18001. because, in this case the deletion might narrow the column."
  18002. (interactive "p")
  18003. (save-match-data
  18004. (org-check-before-invisible-edit 'delete)
  18005. (if (and (org-at-table-p)
  18006. (not (bolp))
  18007. (not (= (char-after) ?|))
  18008. (eq N 1))
  18009. (if (looking-at ".*?|")
  18010. (let ((pos (point))
  18011. (noalign (looking-at "[^|\n\r]* |"))
  18012. (c org-table-may-need-update))
  18013. (replace-match
  18014. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18015. (goto-char pos)
  18016. ;; noalign: if there were two spaces at the end, this field
  18017. ;; does not determine the width of the column.
  18018. (when noalign (setq org-table-may-need-update c)))
  18019. (delete-char N))
  18020. (delete-char N)
  18021. (org-fix-tags-on-the-fly))))
  18022. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  18023. (put 'org-self-insert-command 'delete-selection
  18024. (lambda ()
  18025. (not (run-hook-with-args-until-success
  18026. 'self-insert-uses-region-functions))))
  18027. (put 'orgtbl-self-insert-command 'delete-selection
  18028. (lambda ()
  18029. (not (run-hook-with-args-until-success
  18030. 'self-insert-uses-region-functions))))
  18031. (put 'org-delete-char 'delete-selection 'supersede)
  18032. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18033. (put 'org-yank 'delete-selection 'yank)
  18034. ;; Make `flyspell-mode' delay after some commands
  18035. (put 'org-self-insert-command 'flyspell-delayed t)
  18036. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18037. (put 'org-delete-char 'flyspell-delayed t)
  18038. (put 'org-delete-backward-char 'flyspell-delayed t)
  18039. ;; Make pabbrev-mode expand after Org mode commands
  18040. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18041. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18042. (defun org-transpose-words ()
  18043. "Transpose words for Org.
  18044. This uses the `org-mode-transpose-word-syntax-table' syntax
  18045. table, which interprets characters in `org-emphasis-alist' as
  18046. word constituents."
  18047. (interactive)
  18048. (with-syntax-table org-mode-transpose-word-syntax-table
  18049. (call-interactively 'transpose-words)))
  18050. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18051. (defvar org-ctrl-c-ctrl-c-hook nil
  18052. "Hook for functions attaching themselves to `C-c C-c'.
  18053. This can be used to add additional functionality to the C-c C-c
  18054. key which executes context-dependent commands. This hook is run
  18055. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18056. run after the last test.
  18057. Each function will be called with no arguments. The function
  18058. must check if the context is appropriate for it to act. If yes,
  18059. it should do its thing and then return a non-nil value. If the
  18060. context is wrong, just do nothing and return nil.")
  18061. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18062. "Hook for functions attaching themselves to `C-c C-c'.
  18063. This can be used to add additional functionality to the C-c C-c
  18064. key which executes context-dependent commands. This hook is run
  18065. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18066. before the first test.
  18067. Each function will be called with no arguments. The function
  18068. must check if the context is appropriate for it to act. If yes,
  18069. it should do its thing and then return a non-nil value. If the
  18070. context is wrong, just do nothing and return nil.")
  18071. (defvar org-tab-first-hook nil
  18072. "Hook for functions to attach themselves to TAB.
  18073. See `org-ctrl-c-ctrl-c-hook' for more information.
  18074. This hook runs as the first action when TAB is pressed, even before
  18075. `org-cycle' messes around with the `outline-regexp' to cater for
  18076. inline tasks and plain list item folding.
  18077. If any function in this hook returns t, any other actions that
  18078. would have been caused by TAB (such as table field motion or visibility
  18079. cycling) will not occur.")
  18080. (defvar org-tab-after-check-for-table-hook nil
  18081. "Hook for functions to attach themselves to TAB.
  18082. See `org-ctrl-c-ctrl-c-hook' for more information.
  18083. This hook runs after it has been established that the cursor is not in a
  18084. table, but before checking if the cursor is in a headline or if global cycling
  18085. should be done.
  18086. If any function in this hook returns t, not other actions like visibility
  18087. cycling will be done.")
  18088. (defvar org-tab-after-check-for-cycling-hook nil
  18089. "Hook for functions to attach themselves to TAB.
  18090. See `org-ctrl-c-ctrl-c-hook' for more information.
  18091. This hook runs after it has been established that not table field motion and
  18092. not visibility should be done because of current context. This is probably
  18093. the place where a package like yasnippets can hook in.")
  18094. (defvar org-tab-before-tab-emulation-hook nil
  18095. "Hook for functions to attach themselves to TAB.
  18096. See `org-ctrl-c-ctrl-c-hook' for more information.
  18097. This hook runs after every other options for TAB have been exhausted, but
  18098. before indentation and \t insertion takes place.")
  18099. (defvar org-metaleft-hook nil
  18100. "Hook for functions attaching themselves to `M-left'.
  18101. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18102. (defvar org-metaright-hook nil
  18103. "Hook for functions attaching themselves to `M-right'.
  18104. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18105. (defvar org-metaup-hook nil
  18106. "Hook for functions attaching themselves to `M-up'.
  18107. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18108. (defvar org-metadown-hook nil
  18109. "Hook for functions attaching themselves to `M-down'.
  18110. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18111. (defvar org-shiftmetaleft-hook nil
  18112. "Hook for functions attaching themselves to `M-S-left'.
  18113. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18114. (defvar org-shiftmetaright-hook nil
  18115. "Hook for functions attaching themselves to `M-S-right'.
  18116. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18117. (defvar org-shiftmetaup-hook nil
  18118. "Hook for functions attaching themselves to `M-S-up'.
  18119. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18120. (defvar org-shiftmetadown-hook nil
  18121. "Hook for functions attaching themselves to `M-S-down'.
  18122. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18123. (defvar org-metareturn-hook nil
  18124. "Hook for functions attaching themselves to `M-RET'.
  18125. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18126. (defvar org-shiftup-hook nil
  18127. "Hook for functions attaching themselves to `S-up'.
  18128. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18129. (defvar org-shiftup-final-hook nil
  18130. "Hook for functions attaching themselves to `S-up'.
  18131. This one runs after all other options except shift-select have been excluded.
  18132. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18133. (defvar org-shiftdown-hook nil
  18134. "Hook for functions attaching themselves to `S-down'.
  18135. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18136. (defvar org-shiftdown-final-hook nil
  18137. "Hook for functions attaching themselves to `S-down'.
  18138. This one runs after all other options except shift-select have been excluded.
  18139. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18140. (defvar org-shiftleft-hook nil
  18141. "Hook for functions attaching themselves to `S-left'.
  18142. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18143. (defvar org-shiftleft-final-hook nil
  18144. "Hook for functions attaching themselves to `S-left'.
  18145. This one runs after all other options except shift-select have been excluded.
  18146. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18147. (defvar org-shiftright-hook nil
  18148. "Hook for functions attaching themselves to `S-right'.
  18149. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18150. (defvar org-shiftright-final-hook nil
  18151. "Hook for functions attaching themselves to `S-right'.
  18152. This one runs after all other options except shift-select have been excluded.
  18153. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18154. (defun org-modifier-cursor-error ()
  18155. "Throw an error, a modified cursor command was applied in wrong context."
  18156. (user-error "This command is active in special context like tables, headlines or items"))
  18157. (defun org-shiftselect-error ()
  18158. "Throw an error because Shift-Cursor command was applied in wrong context."
  18159. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18160. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  18161. (user-error "This command works only in special context like headlines or timestamps")))
  18162. (defun org-call-for-shift-select (cmd)
  18163. (let ((this-command-keys-shift-translated t))
  18164. (call-interactively cmd)))
  18165. (defun org-shifttab (&optional arg)
  18166. "Global visibility cycling or move to previous table field.
  18167. Call `org-table-previous-field' within a table.
  18168. When ARG is nil, cycle globally through visibility states.
  18169. When ARG is a numeric prefix, show contents of this level."
  18170. (interactive "P")
  18171. (cond
  18172. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18173. ((integerp arg)
  18174. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18175. (message "Content view to level: %d" arg)
  18176. (org-content (prefix-numeric-value arg2))
  18177. (org-cycle-show-empty-lines t)
  18178. (setq org-cycle-global-status 'overview)))
  18179. (t (call-interactively 'org-global-cycle))))
  18180. (defun org-shiftmetaleft ()
  18181. "Promote subtree or delete table column.
  18182. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18183. `org-table-delete-column', depending on context. See the
  18184. individual commands for more information."
  18185. (interactive)
  18186. (cond
  18187. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18188. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18189. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18190. ((if (not (org-region-active-p)) (org-at-item-p)
  18191. (save-excursion (goto-char (region-beginning))
  18192. (org-at-item-p)))
  18193. (call-interactively 'org-outdent-item-tree))
  18194. (t (org-modifier-cursor-error))))
  18195. (defun org-shiftmetaright ()
  18196. "Demote subtree or insert table column.
  18197. Calls `org-demote-subtree', `org-indent-item-tree', or
  18198. `org-table-insert-column', depending on context. See the
  18199. individual commands for more information."
  18200. (interactive)
  18201. (cond
  18202. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18203. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18204. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18205. ((if (not (org-region-active-p)) (org-at-item-p)
  18206. (save-excursion (goto-char (region-beginning))
  18207. (org-at-item-p)))
  18208. (call-interactively 'org-indent-item-tree))
  18209. (t (org-modifier-cursor-error))))
  18210. (defun org-shiftmetaup (&optional _arg)
  18211. "Drag the line at point up.
  18212. In a table, kill the current row.
  18213. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18214. but also adjust the previous clocked item in the clock history.
  18215. Everywhere else, drag the line at point up."
  18216. (interactive "P")
  18217. (cond
  18218. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18219. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18220. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18221. (call-interactively 'org-timestamp-up)))
  18222. (t (call-interactively 'org-drag-line-backward))))
  18223. (defun org-shiftmetadown (&optional _arg)
  18224. "Drag the line at point down.
  18225. In a table, insert an empty row at the current line.
  18226. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18227. but also adjust the previous clocked item in the clock history.
  18228. Everywhere else, drag the line at point down."
  18229. (interactive "P")
  18230. (cond
  18231. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18232. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18233. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18234. (call-interactively 'org-timestamp-down)))
  18235. (t (call-interactively 'org-drag-line-forward))))
  18236. (defsubst org-hidden-tree-error ()
  18237. (user-error
  18238. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18239. (defun org-metaleft (&optional _arg)
  18240. "Promote heading, list item at point or move table column left.
  18241. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18242. depending on context. With no specific context, calls the Emacs
  18243. default `backward-word'. See the individual commands for more
  18244. information.
  18245. This function runs the hook `org-metaleft-hook' as a first step,
  18246. and returns at first non-nil value."
  18247. (interactive "P")
  18248. (cond
  18249. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18250. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18251. ((org-with-limited-levels
  18252. (or (org-at-heading-p)
  18253. (and (org-region-active-p)
  18254. (save-excursion
  18255. (goto-char (region-beginning))
  18256. (org-at-heading-p)))))
  18257. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18258. (call-interactively 'org-do-promote))
  18259. ;; At an inline task.
  18260. ((org-at-heading-p)
  18261. (call-interactively 'org-inlinetask-promote))
  18262. ((or (org-at-item-p)
  18263. (and (org-region-active-p)
  18264. (save-excursion
  18265. (goto-char (region-beginning))
  18266. (org-at-item-p))))
  18267. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18268. (call-interactively 'org-outdent-item))
  18269. (t (call-interactively 'backward-word))))
  18270. (defun org-metaright (&optional _arg)
  18271. "Demote heading, list item at point or move table column right.
  18272. In front of a drawer or a block keyword, indent it correctly.
  18273. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18274. `org-indent-drawer' or `org-indent-block' depending on context.
  18275. With no specific context, calls the Emacs default `forward-word'.
  18276. See the individual commands for more information.
  18277. This function runs the hook `org-metaright-hook' as a first step,
  18278. and returns at first non-nil value."
  18279. (interactive "P")
  18280. (cond
  18281. ((run-hook-with-args-until-success 'org-metaright-hook))
  18282. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18283. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18284. ((org-at-block-p) (call-interactively 'org-indent-block))
  18285. ((org-with-limited-levels
  18286. (or (org-at-heading-p)
  18287. (and (org-region-active-p)
  18288. (save-excursion
  18289. (goto-char (region-beginning))
  18290. (org-at-heading-p)))))
  18291. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18292. (call-interactively 'org-do-demote))
  18293. ;; At an inline task.
  18294. ((org-at-heading-p)
  18295. (call-interactively 'org-inlinetask-demote))
  18296. ((or (org-at-item-p)
  18297. (and (org-region-active-p)
  18298. (save-excursion
  18299. (goto-char (region-beginning))
  18300. (org-at-item-p))))
  18301. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18302. (call-interactively 'org-indent-item))
  18303. (t (call-interactively 'forward-word))))
  18304. (defun org-check-for-hidden (what)
  18305. "Check if there are hidden headlines/items in the current visual line.
  18306. WHAT can be either `headlines' or `items'. If the current line is
  18307. an outline or item heading and it has a folded subtree below it,
  18308. this function returns t, nil otherwise."
  18309. (let ((re (cond
  18310. ((eq what 'headlines) org-outline-regexp-bol)
  18311. ((eq what 'items) (org-item-beginning-re))
  18312. (t (error "This should not happen"))))
  18313. beg end)
  18314. (save-excursion
  18315. (catch 'exit
  18316. (unless (org-region-active-p)
  18317. (setq beg (point-at-bol))
  18318. (beginning-of-line 2)
  18319. (while (and (not (eobp)) ;; this is like `next-line'
  18320. (get-char-property (1- (point)) 'invisible))
  18321. (beginning-of-line 2))
  18322. (setq end (point))
  18323. (goto-char beg)
  18324. (goto-char (point-at-eol))
  18325. (setq end (max end (point)))
  18326. (while (re-search-forward re end t)
  18327. (when (get-char-property (match-beginning 0) 'invisible)
  18328. (throw 'exit t))))
  18329. nil))))
  18330. (defun org-metaup (&optional _arg)
  18331. "Move subtree up or move table row up.
  18332. Calls `org-move-subtree-up' or `org-table-move-row' or
  18333. `org-move-item-up', depending on context. See the individual commands
  18334. for more information."
  18335. (interactive "P")
  18336. (cond
  18337. ((run-hook-with-args-until-success 'org-metaup-hook))
  18338. ((org-region-active-p)
  18339. (let* ((a (min (region-beginning) (region-end)))
  18340. (b (1- (max (region-beginning) (region-end))))
  18341. (c (save-excursion (goto-char a)
  18342. (move-beginning-of-line 0)))
  18343. (d (save-excursion (goto-char a)
  18344. (move-end-of-line 0) (point))))
  18345. (transpose-regions a b c d)
  18346. (goto-char c)))
  18347. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18348. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18349. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18350. (t (org-drag-element-backward))))
  18351. (defun org-metadown (&optional _arg)
  18352. "Move subtree down or move table row down.
  18353. Calls `org-move-subtree-down' or `org-table-move-row' or
  18354. `org-move-item-down', depending on context. See the individual
  18355. commands for more information."
  18356. (interactive "P")
  18357. (cond
  18358. ((run-hook-with-args-until-success 'org-metadown-hook))
  18359. ((org-region-active-p)
  18360. (let* ((a (min (region-beginning) (region-end)))
  18361. (b (max (region-beginning) (region-end)))
  18362. (c (save-excursion (goto-char b)
  18363. (move-beginning-of-line 1)))
  18364. (d (save-excursion (goto-char b)
  18365. (move-end-of-line 1) (1+ (point)))))
  18366. (transpose-regions a b c d)
  18367. (goto-char d)))
  18368. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18369. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18370. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18371. (t (org-drag-element-forward))))
  18372. (defun org-shiftup (&optional arg)
  18373. "Increase item in timestamp or increase priority of current headline.
  18374. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18375. depending on context. See the individual commands for more information."
  18376. (interactive "P")
  18377. (cond
  18378. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18379. ((and org-support-shift-select (org-region-active-p))
  18380. (org-call-for-shift-select 'previous-line))
  18381. ((org-at-timestamp-p 'lax)
  18382. (call-interactively (if org-edit-timestamp-down-means-later
  18383. 'org-timestamp-down 'org-timestamp-up)))
  18384. ((and (not (eq org-support-shift-select 'always))
  18385. org-enable-priority-commands
  18386. (org-at-heading-p))
  18387. (call-interactively 'org-priority-up))
  18388. ((and (not org-support-shift-select) (org-at-item-p))
  18389. (call-interactively 'org-previous-item))
  18390. ((org-clocktable-try-shift 'up arg))
  18391. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18392. (org-support-shift-select
  18393. (org-call-for-shift-select 'previous-line))
  18394. (t (org-shiftselect-error))))
  18395. (defun org-shiftdown (&optional arg)
  18396. "Decrease item in timestamp or decrease priority of current headline.
  18397. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18398. depending on context. See the individual commands for more information."
  18399. (interactive "P")
  18400. (cond
  18401. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18402. ((and org-support-shift-select (org-region-active-p))
  18403. (org-call-for-shift-select 'next-line))
  18404. ((org-at-timestamp-p 'lax)
  18405. (call-interactively (if org-edit-timestamp-down-means-later
  18406. 'org-timestamp-up 'org-timestamp-down)))
  18407. ((and (not (eq org-support-shift-select 'always))
  18408. org-enable-priority-commands
  18409. (org-at-heading-p))
  18410. (call-interactively 'org-priority-down))
  18411. ((and (not org-support-shift-select) (org-at-item-p))
  18412. (call-interactively 'org-next-item))
  18413. ((org-clocktable-try-shift 'down arg))
  18414. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18415. (org-support-shift-select
  18416. (org-call-for-shift-select 'next-line))
  18417. (t (org-shiftselect-error))))
  18418. (defun org-shiftright (&optional arg)
  18419. "Cycle the thing at point or in the current line, depending on context.
  18420. Depending on context, this does one of the following:
  18421. - switch a timestamp at point one day into the future
  18422. - on a headline, switch to the next TODO keyword.
  18423. - on an item, switch entire list to the next bullet type
  18424. - on a property line, switch to the next allowed value
  18425. - on a clocktable definition line, move time block into the future"
  18426. (interactive "P")
  18427. (cond
  18428. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18429. ((and org-support-shift-select (org-region-active-p))
  18430. (org-call-for-shift-select 'forward-char))
  18431. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  18432. ((and (not (eq org-support-shift-select 'always))
  18433. (org-at-heading-p))
  18434. (let ((org-inhibit-logging
  18435. (not org-treat-S-cursor-todo-selection-as-state-change))
  18436. (org-inhibit-blocking
  18437. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18438. (org-call-with-arg 'org-todo 'right)))
  18439. ((or (and org-support-shift-select
  18440. (not (eq org-support-shift-select 'always))
  18441. (org-at-item-bullet-p))
  18442. (and (not org-support-shift-select) (org-at-item-p)))
  18443. (org-call-with-arg 'org-cycle-list-bullet nil))
  18444. ((and (not (eq org-support-shift-select 'always))
  18445. (org-at-property-p))
  18446. (call-interactively 'org-property-next-allowed-value))
  18447. ((org-clocktable-try-shift 'right arg))
  18448. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18449. (org-support-shift-select
  18450. (org-call-for-shift-select 'forward-char))
  18451. (t (org-shiftselect-error))))
  18452. (defun org-shiftleft (&optional arg)
  18453. "Cycle the thing at point or in the current line, depending on context.
  18454. Depending on context, this does one of the following:
  18455. - switch a timestamp at point one day into the past
  18456. - on a headline, switch to the previous TODO keyword.
  18457. - on an item, switch entire list to the previous bullet type
  18458. - on a property line, switch to the previous allowed value
  18459. - on a clocktable definition line, move time block into the past"
  18460. (interactive "P")
  18461. (cond
  18462. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18463. ((and org-support-shift-select (org-region-active-p))
  18464. (org-call-for-shift-select 'backward-char))
  18465. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  18466. ((and (not (eq org-support-shift-select 'always))
  18467. (org-at-heading-p))
  18468. (let ((org-inhibit-logging
  18469. (not org-treat-S-cursor-todo-selection-as-state-change))
  18470. (org-inhibit-blocking
  18471. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18472. (org-call-with-arg 'org-todo 'left)))
  18473. ((or (and org-support-shift-select
  18474. (not (eq org-support-shift-select 'always))
  18475. (org-at-item-bullet-p))
  18476. (and (not org-support-shift-select) (org-at-item-p)))
  18477. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  18478. ((and (not (eq org-support-shift-select 'always))
  18479. (org-at-property-p))
  18480. (call-interactively 'org-property-previous-allowed-value))
  18481. ((org-clocktable-try-shift 'left arg))
  18482. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  18483. (org-support-shift-select
  18484. (org-call-for-shift-select 'backward-char))
  18485. (t (org-shiftselect-error))))
  18486. (defun org-shiftcontrolright ()
  18487. "Switch to next TODO set."
  18488. (interactive)
  18489. (cond
  18490. ((and org-support-shift-select (org-region-active-p))
  18491. (org-call-for-shift-select 'forward-word))
  18492. ((and (not (eq org-support-shift-select 'always))
  18493. (org-at-heading-p))
  18494. (org-call-with-arg 'org-todo 'nextset))
  18495. (org-support-shift-select
  18496. (org-call-for-shift-select 'forward-word))
  18497. (t (org-shiftselect-error))))
  18498. (defun org-shiftcontrolleft ()
  18499. "Switch to previous TODO set."
  18500. (interactive)
  18501. (cond
  18502. ((and org-support-shift-select (org-region-active-p))
  18503. (org-call-for-shift-select 'backward-word))
  18504. ((and (not (eq org-support-shift-select 'always))
  18505. (org-at-heading-p))
  18506. (org-call-with-arg 'org-todo 'previousset))
  18507. (org-support-shift-select
  18508. (org-call-for-shift-select 'backward-word))
  18509. (t (org-shiftselect-error))))
  18510. (defun org-shiftcontrolup (&optional n)
  18511. "Change timestamps synchronously up in CLOCK log lines.
  18512. Optional argument N tells to change by that many units."
  18513. (interactive "P")
  18514. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18515. (let (org-support-shift-select)
  18516. (org-clock-timestamps-up n))
  18517. (user-error "Not at a clock log")))
  18518. (defun org-shiftcontroldown (&optional n)
  18519. "Change timestamps synchronously down in CLOCK log lines.
  18520. Optional argument N tells to change by that many units."
  18521. (interactive "P")
  18522. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18523. (let (org-support-shift-select)
  18524. (org-clock-timestamps-down n))
  18525. (user-error "Not at a clock log")))
  18526. (defun org-increase-number-at-point (&optional inc)
  18527. "Increment the number at point.
  18528. With an optional prefix numeric argument INC, increment using
  18529. this numeric value."
  18530. (interactive "p")
  18531. (if (not (number-at-point))
  18532. (user-error "Not on a number")
  18533. (unless inc (setq inc 1))
  18534. (let ((pos (point))
  18535. (beg (skip-chars-backward "-+^/*0-9eE."))
  18536. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  18537. (setq nap (buffer-substring-no-properties
  18538. (+ pos beg) (+ pos beg end)))
  18539. (delete-region (+ pos beg) (+ pos beg end))
  18540. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18541. (when (org-at-table-p)
  18542. (org-table-align)
  18543. (org-table-end-of-field 1))))
  18544. (defun org-decrease-number-at-point (&optional inc)
  18545. "Decrement the number at point.
  18546. With an optional prefix numeric argument INC, decrement using
  18547. this numeric value."
  18548. (interactive "p")
  18549. (org-increase-number-at-point (- (or inc 1))))
  18550. (defun org-ctrl-c-ret ()
  18551. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  18552. (interactive)
  18553. (cond
  18554. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18555. (t (call-interactively 'org-insert-heading))))
  18556. (defun org-find-visible ()
  18557. (let ((s (point)))
  18558. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18559. (get-char-property s 'invisible)))
  18560. s))
  18561. (defun org-find-invisible ()
  18562. (let ((s (point)))
  18563. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18564. (not (get-char-property s 'invisible))))
  18565. s))
  18566. (defun org-copy-visible (beg end)
  18567. "Copy the visible parts of the region."
  18568. (interactive "r")
  18569. (let ((result ""))
  18570. (while (/= beg end)
  18571. (when (get-char-property beg 'invisible)
  18572. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  18573. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  18574. (setq result (concat result (buffer-substring beg next)))
  18575. (setq beg next)))
  18576. (kill-new result)))
  18577. (defun org-copy-special ()
  18578. "Copy region in table or copy current subtree.
  18579. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18580. context. See the individual commands for more information."
  18581. (interactive)
  18582. (call-interactively
  18583. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18584. (defun org-cut-special ()
  18585. "Cut region in table or cut current subtree.
  18586. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  18587. context. See the individual commands for more information."
  18588. (interactive)
  18589. (call-interactively
  18590. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  18591. (defun org-paste-special (arg)
  18592. "Paste rectangular region into table, or past subtree relative to level.
  18593. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18594. See the individual commands for more information."
  18595. (interactive "P")
  18596. (if (org-at-table-p)
  18597. (org-table-paste-rectangle)
  18598. (org-paste-subtree arg)))
  18599. (defun org-edit-special (&optional arg)
  18600. "Call a special editor for the element at point.
  18601. When at a table, call the formula editor with `org-table-edit-formulas'.
  18602. When in a source code block, call `org-edit-src-code'.
  18603. When in a fixed-width region, call `org-edit-fixed-width-region'.
  18604. When in an export block, call `org-edit-export-block'.
  18605. When in a LaTeX environment, call `org-edit-latex-environment'.
  18606. When at an #+INCLUDE keyword, visit the included file.
  18607. When at a footnote reference, call `org-edit-footnote-reference'
  18608. On a link, call `ffap' to visit the link at point.
  18609. Otherwise, return a user error."
  18610. (interactive "P")
  18611. (let ((element (org-element-at-point)))
  18612. (barf-if-buffer-read-only)
  18613. (pcase (org-element-type element)
  18614. (`src-block
  18615. (if (not arg) (org-edit-src-code)
  18616. (let* ((info (org-babel-get-src-block-info))
  18617. (lang (nth 0 info))
  18618. (params (nth 2 info))
  18619. (session (cdr (assq :session params))))
  18620. (if (not session) (org-edit-src-code)
  18621. ;; At a src-block with a session and function called with
  18622. ;; an ARG: switch to the buffer related to the inferior
  18623. ;; process.
  18624. (switch-to-buffer
  18625. (funcall (intern (concat "org-babel-prep-session:" lang))
  18626. session params))))))
  18627. (`keyword
  18628. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  18629. (org-open-link-from-string
  18630. (format "[[%s]]"
  18631. (expand-file-name
  18632. (let ((value (org-element-property :value element)))
  18633. (cond ((org-file-url-p value)
  18634. (user-error "The file is specified as a URL, cannot be edited"))
  18635. ((not (org-string-nw-p value))
  18636. (user-error "No file to edit"))
  18637. ((string-match "\\`\"\\(.*?\\)\"" value)
  18638. (match-string 1 value))
  18639. ((string-match "\\`[^ \t\"]\\S-*" value)
  18640. (match-string 0 value))
  18641. (t (user-error "No valid file specified")))))))
  18642. (user-error "No special environment to edit here")))
  18643. (`table
  18644. (if (eq (org-element-property :type element) 'table.el)
  18645. (org-edit-table.el)
  18646. (call-interactively 'org-table-edit-formulas)))
  18647. ;; Only Org tables contain `table-row' type elements.
  18648. (`table-row (call-interactively 'org-table-edit-formulas))
  18649. (`example-block (org-edit-src-code))
  18650. (`export-block (org-edit-export-block))
  18651. (`fixed-width (org-edit-fixed-width-region))
  18652. (`latex-environment (org-edit-latex-environment))
  18653. (_
  18654. ;; No notable element at point. Though, we may be at a link or
  18655. ;; a footnote reference, which are objects. Thus, scan deeper.
  18656. (let ((context (org-element-context element)))
  18657. (pcase (org-element-type context)
  18658. (`footnote-reference (org-edit-footnote-reference))
  18659. (`inline-src-block (org-edit-inline-src-code))
  18660. (`link (call-interactively #'ffap))
  18661. (_ (user-error "No special environment to edit here"))))))))
  18662. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  18663. (defun org-ctrl-c-ctrl-c (&optional arg)
  18664. "Set tags in headline, or update according to changed information at point.
  18665. This command does many different things, depending on context:
  18666. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  18667. this is what we do.
  18668. - If the cursor is on a statistics cookie, update it.
  18669. - If the cursor is in a headline, prompt for tags and insert them
  18670. into the current line, aligned to `org-tags-column'. When called
  18671. with prefix arg, realign all tags in the current buffer.
  18672. - If the cursor is in one of the special #+KEYWORD lines, this
  18673. triggers scanning the buffer for these lines and updating the
  18674. information.
  18675. - If the cursor is inside a table, realign the table. This command
  18676. works even if the automatic table editor has been turned off.
  18677. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  18678. the entire table.
  18679. - If the cursor is at a footnote reference or definition, jump to
  18680. the corresponding definition or references, respectively.
  18681. - If the cursor is a the beginning of a dynamic block, update it.
  18682. - If the current buffer is a capture buffer, close note and file it.
  18683. - If the cursor is on a <<<target>>>, update radio targets and
  18684. corresponding links in this buffer.
  18685. - If the cursor is on a numbered item in a plain list, renumber the
  18686. ordered list.
  18687. - If the cursor is on a checkbox, toggle it.
  18688. - If the cursor is on a code block, evaluate it. The variable
  18689. `org-confirm-babel-evaluate' can be used to control prompting
  18690. before code block evaluation, by default every code block
  18691. evaluation requires confirmation. Code block evaluation can be
  18692. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  18693. (interactive "P")
  18694. (cond
  18695. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  18696. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  18697. (org-remove-occur-highlights)
  18698. (message "Temporary highlights/overlays removed from current buffer"))
  18699. ((and (local-variable-p 'org-finish-function)
  18700. (fboundp org-finish-function))
  18701. (funcall org-finish-function))
  18702. ((org-babel-hash-at-point))
  18703. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  18704. (t
  18705. (let* ((context
  18706. (org-element-lineage
  18707. (org-element-context)
  18708. ;; Limit to supported contexts.
  18709. '(babel-call clock dynamic-block footnote-definition
  18710. footnote-reference inline-babel-call inline-src-block
  18711. inlinetask item keyword node-property paragraph
  18712. plain-list planning property-drawer radio-target
  18713. src-block statistics-cookie table table-cell table-row
  18714. timestamp)
  18715. t))
  18716. (type (org-element-type context)))
  18717. ;; For convenience: at the first line of a paragraph on the same
  18718. ;; line as an item, apply function on that item instead.
  18719. (when (eq type 'paragraph)
  18720. (let ((parent (org-element-property :parent context)))
  18721. (when (and (eq (org-element-type parent) 'item)
  18722. (= (line-beginning-position)
  18723. (org-element-property :begin parent)))
  18724. (setq context parent)
  18725. (setq type 'item))))
  18726. ;; Act according to type of element or object at point.
  18727. ;;
  18728. ;; Do nothing on a blank line, except if it is contained in
  18729. ;; a src block. Hence, we first check if point is in such
  18730. ;; a block and then if it is at a blank line.
  18731. (pcase type
  18732. ((or `inline-src-block `src-block)
  18733. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  18734. (org-babel-eval-wipe-error-buffer)
  18735. (org-babel-execute-src-block
  18736. current-prefix-arg (org-babel-get-src-block-info nil context))))
  18737. ((guard (org-match-line "[ \t]*$"))
  18738. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  18739. (user-error
  18740. (substitute-command-keys
  18741. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  18742. ((or `babel-call `inline-babel-call)
  18743. (let ((info (org-babel-lob-get-info context)))
  18744. (when info (org-babel-execute-src-block nil info))))
  18745. (`clock (org-clock-update-time-maybe))
  18746. (`dynamic-block
  18747. (save-excursion
  18748. (goto-char (org-element-property :post-affiliated context))
  18749. (org-update-dblock)))
  18750. (`footnote-definition
  18751. (goto-char (org-element-property :post-affiliated context))
  18752. (call-interactively 'org-footnote-action))
  18753. (`footnote-reference (call-interactively #'org-footnote-action))
  18754. ((or `headline `inlinetask)
  18755. (save-excursion (goto-char (org-element-property :begin context))
  18756. (call-interactively #'org-set-tags)))
  18757. (`item
  18758. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  18759. ;; unconditionally, whereas `C-u' will toggle its presence.
  18760. ;; Without a universal argument, if the item has a checkbox,
  18761. ;; toggle it. Otherwise repair the list.
  18762. (let* ((box (org-element-property :checkbox context))
  18763. (struct (org-element-property :structure context))
  18764. (old-struct (copy-tree struct))
  18765. (parents (org-list-parents-alist struct))
  18766. (prevs (org-list-prevs-alist struct))
  18767. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  18768. (org-list-set-checkbox
  18769. (org-element-property :begin context) struct
  18770. (cond ((equal arg '(16)) "[-]")
  18771. ((and (not box) (equal arg '(4))) "[ ]")
  18772. ((or (not box) (equal arg '(4))) nil)
  18773. ((eq box 'on) "[ ]")
  18774. (t "[X]")))
  18775. ;; Mimic `org-list-write-struct' but with grabbing a return
  18776. ;; value from `org-list-struct-fix-box'.
  18777. (org-list-struct-fix-ind struct parents 2)
  18778. (org-list-struct-fix-item-end struct)
  18779. (org-list-struct-fix-bul struct prevs)
  18780. (org-list-struct-fix-ind struct parents)
  18781. (let ((block-item
  18782. (org-list-struct-fix-box struct parents prevs orderedp)))
  18783. (if (and box (equal struct old-struct))
  18784. (if (equal arg '(16))
  18785. (message "Checkboxes already reset")
  18786. (user-error "Cannot toggle this checkbox: %s"
  18787. (if (eq box 'on)
  18788. "all subitems checked"
  18789. "unchecked subitems")))
  18790. (org-list-struct-apply-struct struct old-struct)
  18791. (org-update-checkbox-count-maybe))
  18792. (when block-item
  18793. (message "Checkboxes were removed due to empty box at line %d"
  18794. (org-current-line block-item))))))
  18795. (`keyword
  18796. (let ((org-inhibit-startup-visibility-stuff t)
  18797. (org-startup-align-all-tables nil))
  18798. (when (boundp 'org-table-coordinate-overlays)
  18799. (mapc #'delete-overlay org-table-coordinate-overlays)
  18800. (setq org-table-coordinate-overlays nil))
  18801. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  18802. (message "Local setup has been refreshed"))
  18803. (`plain-list
  18804. ;; At a plain list, with a double C-u argument, set
  18805. ;; checkboxes of each item to "[-]", whereas a single one
  18806. ;; will toggle their presence according to the state of the
  18807. ;; first item in the list. Without an argument, repair the
  18808. ;; list.
  18809. (let* ((begin (org-element-property :contents-begin context))
  18810. (beginm (move-marker (make-marker) begin))
  18811. (struct (org-element-property :structure context))
  18812. (old-struct (copy-tree struct))
  18813. (first-box (save-excursion
  18814. (goto-char begin)
  18815. (looking-at org-list-full-item-re)
  18816. (match-string-no-properties 3)))
  18817. (new-box (cond ((equal arg '(16)) "[-]")
  18818. ((equal arg '(4)) (unless first-box "[ ]"))
  18819. ((equal first-box "[X]") "[ ]")
  18820. (t "[X]"))))
  18821. (cond
  18822. (arg
  18823. (dolist (pos
  18824. (org-list-get-all-items
  18825. begin struct (org-list-prevs-alist struct)))
  18826. (org-list-set-checkbox pos struct new-box)))
  18827. ((and first-box (eq (point) begin))
  18828. ;; For convenience, when point is at bol on the first
  18829. ;; item of the list and no argument is provided, simply
  18830. ;; toggle checkbox of that item, if any.
  18831. (org-list-set-checkbox begin struct new-box)))
  18832. (org-list-write-struct
  18833. struct (org-list-parents-alist struct) old-struct)
  18834. (org-update-checkbox-count-maybe)
  18835. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  18836. ((or `property-drawer `node-property)
  18837. (call-interactively #'org-property-action))
  18838. (`radio-target
  18839. (call-interactively #'org-update-radio-target-regexp))
  18840. (`statistics-cookie
  18841. (call-interactively #'org-update-statistics-cookies))
  18842. ((or `table `table-cell `table-row)
  18843. ;; At a table, recalculate every field and align it. Also
  18844. ;; send the table if necessary. If the table has
  18845. ;; a `table.el' type, just give up. At a table row or cell,
  18846. ;; maybe recalculate line but always align table.
  18847. (if (eq (org-element-property :type context) 'table.el)
  18848. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  18849. Use `\\[org-edit-special]' to edit table.el tables"))
  18850. (if (or (eq type 'table)
  18851. ;; Check if point is at a TBLFM line.
  18852. (and (eq type 'table-row)
  18853. (= (point) (org-element-property :end context))))
  18854. (save-excursion
  18855. (if (org-at-TBLFM-p)
  18856. (progn (require 'org-table)
  18857. (org-table-calc-current-TBLFM))
  18858. (goto-char (org-element-property :contents-begin context))
  18859. (org-call-with-arg 'org-table-recalculate (or arg t))
  18860. (orgtbl-send-table 'maybe)))
  18861. (org-table-maybe-eval-formula)
  18862. (cond (arg (call-interactively #'org-table-recalculate))
  18863. ((org-table-maybe-recalculate-line))
  18864. (t (org-table-align))))))
  18865. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  18866. (org-timestamp-change 0 'day))
  18867. ((and `nil (guard (org-at-heading-p)))
  18868. ;; When point is on an unsupported object type, we can miss
  18869. ;; the fact that it also is at a heading. Handle it here.
  18870. (call-interactively #'org-set-tags))
  18871. ((guard
  18872. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  18873. (_
  18874. (user-error
  18875. (substitute-command-keys
  18876. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  18877. (defun org-mode-restart ()
  18878. (interactive)
  18879. (let ((indent-status (bound-and-true-p org-indent-mode)))
  18880. (funcall major-mode)
  18881. (hack-local-variables)
  18882. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  18883. (org-indent-mode -1))
  18884. (org-reset-file-cache))
  18885. (message "%s restarted" major-mode))
  18886. (defun org-kill-note-or-show-branches ()
  18887. "Abort storing current note, or call `outline-show-branches'."
  18888. (interactive)
  18889. (if (not org-finish-function)
  18890. (progn
  18891. (outline-hide-subtree)
  18892. (call-interactively 'outline-show-branches))
  18893. (let ((org-note-abort t))
  18894. (funcall org-finish-function))))
  18895. (defun org-delete-indentation (&optional arg)
  18896. "Join current line to previous and fix whitespace at join.
  18897. If previous line is a headline add to headline title. Otherwise
  18898. the function calls `delete-indentation'.
  18899. With a non-nil optional argument, join it to the following one."
  18900. (interactive "*P")
  18901. (if (save-excursion
  18902. (beginning-of-line (if arg 1 0))
  18903. (let ((case-fold-search nil))
  18904. (looking-at org-complex-heading-regexp)))
  18905. ;; At headline.
  18906. (let ((tags-column (when (match-beginning 5)
  18907. (save-excursion (goto-char (match-beginning 5))
  18908. (current-column))))
  18909. (string (concat " " (progn (when arg (forward-line 1))
  18910. (org-trim (delete-and-extract-region
  18911. (line-beginning-position)
  18912. (line-end-position)))))))
  18913. (unless (bobp) (delete-region (point) (1- (point))))
  18914. (goto-char (or (match-end 4)
  18915. (match-beginning 5)
  18916. (match-end 0)))
  18917. (skip-chars-backward " \t")
  18918. (save-excursion (insert string))
  18919. ;; Adjust alignment of tags.
  18920. (cond
  18921. ((not tags-column)) ;no tags
  18922. (org-auto-align-tags (org-set-tags nil t))
  18923. (t (org--align-tags-here tags-column)))) ;preserve tags column
  18924. (delete-indentation arg)))
  18925. (defun org-open-line (n)
  18926. "Insert a new row in tables, call `open-line' elsewhere.
  18927. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  18928. As a special case, when a document starts with a table, allow to
  18929. call `open-line' on the very first character."
  18930. (interactive "*p")
  18931. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  18932. (org-table-insert-row)
  18933. (open-line n)))
  18934. (defun org-return (&optional indent)
  18935. "Goto next table row or insert a newline.
  18936. Calls `org-table-next-row' or `newline', depending on context.
  18937. When optional INDENT argument is non-nil, call
  18938. `newline-and-indent' instead of `newline'.
  18939. When `org-return-follows-link' is non-nil and point is on
  18940. a timestamp or a link, call `org-open-at-point'. However, it
  18941. will not happen if point is in a table or on a \"dead\"
  18942. object (e.g., within a comment). In these case, you need to use
  18943. `org-open-at-point' directly."
  18944. (interactive)
  18945. (let ((context (if org-return-follows-link (org-element-context)
  18946. (org-element-at-point))))
  18947. (cond
  18948. ;; In a table, call `org-table-next-row'.
  18949. ((or (and (eq (org-element-type context) 'table)
  18950. (>= (point) (org-element-property :contents-begin context))
  18951. (< (point) (org-element-property :contents-end context)))
  18952. (org-element-lineage context '(table-row table-cell) t))
  18953. (org-table-justify-field-maybe)
  18954. (call-interactively #'org-table-next-row))
  18955. ;; On a link or a timestamp, call `org-open-at-point' if
  18956. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  18957. ;; locations, e.g., in a comment, as `org-open-at-point'.
  18958. ((and org-return-follows-link
  18959. (or (org-in-regexp org-ts-regexp-both nil t)
  18960. (org-in-regexp org-tsr-regexp-both nil t)
  18961. (org-in-regexp org-any-link-re nil t)))
  18962. (call-interactively #'org-open-at-point))
  18963. ;; Insert newline in heading, but preserve tags.
  18964. ((and (not (bolp))
  18965. (save-excursion (beginning-of-line)
  18966. (let ((case-fold-search nil))
  18967. (looking-at org-complex-heading-regexp))))
  18968. ;; At headline. Split line. However, if point is on keyword,
  18969. ;; priority cookie or tags, do not break any of them: add
  18970. ;; a newline after the headline instead.
  18971. (let ((tags-column (and (match-beginning 5)
  18972. (save-excursion (goto-char (match-beginning 5))
  18973. (current-column))))
  18974. (string
  18975. (when (and (match-end 4) (org-point-in-group (point) 4))
  18976. (delete-and-extract-region (point) (match-end 4)))))
  18977. ;; Adjust tag alignment.
  18978. (cond
  18979. ((not (and tags-column string)))
  18980. (org-auto-align-tags (org-set-tags nil t))
  18981. (t (org--align-tags-here tags-column))) ;preserve tags column
  18982. (end-of-line)
  18983. (org-show-entry)
  18984. (if indent (newline-and-indent) (newline))
  18985. (when string (save-excursion (insert (org-trim string))))))
  18986. ;; In a list, make sure indenting keeps trailing text within.
  18987. ((and indent
  18988. (not (eolp))
  18989. (org-element-lineage context '(item)))
  18990. (let ((trailing-data
  18991. (delete-and-extract-region (point) (line-end-position))))
  18992. (newline-and-indent)
  18993. (save-excursion (insert trailing-data))))
  18994. (t (if indent (newline-and-indent) (newline))))))
  18995. (defun org-return-indent ()
  18996. "Goto next table row or insert a newline and indent.
  18997. Calls `org-table-next-row' or `newline-and-indent', depending on
  18998. context. See the individual commands for more information."
  18999. (interactive)
  19000. (org-return t))
  19001. (defun org-ctrl-c-tab (&optional _arg)
  19002. "Toggle columns width in a table, or show children.
  19003. Call `org-table-toggle-column-width' if point is in a table.
  19004. Otherwise, call `org-show-children'."
  19005. (interactive "p")
  19006. (call-interactively
  19007. (if (org-at-table-p) #'org-table-toggle-column-width
  19008. #'org-show-children)))
  19009. (defun org-ctrl-c-star ()
  19010. "Compute table, or change heading status of lines.
  19011. Calls `org-table-recalculate' or `org-toggle-heading',
  19012. depending on context."
  19013. (interactive)
  19014. (cond
  19015. ((org-at-table-p)
  19016. (call-interactively 'org-table-recalculate))
  19017. (t
  19018. ;; Convert all lines in region to list items
  19019. (call-interactively 'org-toggle-heading))))
  19020. (defun org-ctrl-c-minus ()
  19021. "Insert separator line in table or modify bullet status of line.
  19022. Also turns a plain line or a region of lines into list items.
  19023. Calls `org-table-insert-hline', `org-toggle-item', or
  19024. `org-cycle-list-bullet', depending on context."
  19025. (interactive)
  19026. (cond
  19027. ((org-at-table-p)
  19028. (call-interactively 'org-table-insert-hline))
  19029. ((org-region-active-p)
  19030. (call-interactively 'org-toggle-item))
  19031. ((org-in-item-p)
  19032. (call-interactively 'org-cycle-list-bullet))
  19033. (t
  19034. (call-interactively 'org-toggle-item))))
  19035. (defun org-toggle-heading (&optional nstars)
  19036. "Convert headings to normal text, or items or text to headings.
  19037. If there is no active region, only convert the current line.
  19038. With a `\\[universal-argument]' prefix, convert the whole list at
  19039. point into heading.
  19040. In a region:
  19041. - If the first non blank line is a headline, remove the stars
  19042. from all headlines in the region.
  19043. - If it is a normal line, turn each and every normal line (i.e.,
  19044. not an heading or an item) in the region into headings. If you
  19045. want to convert only the first line of this region, use one
  19046. universal prefix argument.
  19047. - If it is a plain list item, turn all plain list items into headings.
  19048. When converting a line into a heading, the number of stars is chosen
  19049. such that the lines become children of the current entry. However,
  19050. when a numeric prefix argument is given, its value determines the
  19051. number of stars to add."
  19052. (interactive "P")
  19053. (let ((skip-blanks
  19054. (function
  19055. ;; Return beginning of first non-blank line, starting from
  19056. ;; line at POS.
  19057. (lambda (pos)
  19058. (save-excursion
  19059. (goto-char pos)
  19060. (while (org-at-comment-p) (forward-line))
  19061. (skip-chars-forward " \r\t\n")
  19062. (point-at-bol)))))
  19063. beg end toggled)
  19064. ;; Determine boundaries of changes. If a universal prefix has
  19065. ;; been given, put the list in a region. If region ends at a bol,
  19066. ;; do not consider the last line to be in the region.
  19067. (when (and current-prefix-arg (org-at-item-p))
  19068. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19069. (org-mark-element))
  19070. (if (org-region-active-p)
  19071. (setq beg (funcall skip-blanks (region-beginning))
  19072. end (copy-marker (save-excursion
  19073. (goto-char (region-end))
  19074. (if (bolp) (point) (point-at-eol)))))
  19075. (setq beg (funcall skip-blanks (point-at-bol))
  19076. end (copy-marker (point-at-eol))))
  19077. ;; Ensure inline tasks don't count as headings.
  19078. (org-with-limited-levels
  19079. (save-excursion
  19080. (goto-char beg)
  19081. (cond
  19082. ;; Case 1. Started at an heading: de-star headings.
  19083. ((org-at-heading-p)
  19084. (while (< (point) end)
  19085. (when (org-at-heading-p t)
  19086. (looking-at org-outline-regexp) (replace-match "")
  19087. (setq toggled t))
  19088. (forward-line)))
  19089. ;; Case 2. Started at an item: change items into headlines.
  19090. ;; One star will be added by `org-list-to-subtree'.
  19091. ((org-at-item-p)
  19092. (while (< (point) end)
  19093. (when (org-at-item-p)
  19094. ;; Pay attention to cases when region ends before list.
  19095. (let* ((struct (org-list-struct))
  19096. (list-end
  19097. (min (org-list-get-bottom-point struct) (1+ end))))
  19098. (save-restriction
  19099. (narrow-to-region (point) list-end)
  19100. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19101. (setq toggled t))
  19102. (forward-line)))
  19103. ;; Case 3. Started at normal text: make every line an heading,
  19104. ;; skipping headlines and items.
  19105. (t (let* ((stars
  19106. (make-string
  19107. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19108. (add-stars
  19109. (cond (nstars "") ; stars from prefix only
  19110. ((equal stars "") "*") ; before first heading
  19111. (org-odd-levels-only "**") ; inside heading, odd
  19112. (t "*"))) ; inside heading, oddeven
  19113. (rpl (concat stars add-stars " "))
  19114. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19115. (while (< (point) (if (equal nstars '(4)) lend end))
  19116. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19117. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19118. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19119. (forward-line)))))))
  19120. (unless toggled (message "Cannot toggle heading from here"))))
  19121. (defun org-meta-return (&optional arg)
  19122. "Insert a new heading or wrap a region in a table.
  19123. Calls `org-insert-heading', `org-insert-item' or
  19124. `org-table-wrap-region', depending on context. When called with
  19125. an argument, unconditionally call `org-insert-heading'."
  19126. (interactive "P")
  19127. (org-check-before-invisible-edit 'insert)
  19128. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19129. (call-interactively (cond (arg #'org-insert-heading)
  19130. ((org-at-table-p) #'org-table-wrap-region)
  19131. ((org-in-item-p) #'org-insert-item)
  19132. (t #'org-insert-heading)))))
  19133. ;;; Menu entries
  19134. (defsubst org-in-subtree-not-table-p ()
  19135. "Are we in a subtree and not in a table?"
  19136. (and (not (org-before-first-heading-p))
  19137. (not (org-at-table-p))))
  19138. ;; Define the Org mode menus
  19139. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19140. '("Tbl"
  19141. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19142. ["Next Field" org-cycle (org-at-table-p)]
  19143. ["Previous Field" org-shifttab (org-at-table-p)]
  19144. ["Next Row" org-return (org-at-table-p)]
  19145. "--"
  19146. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19147. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19148. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19149. "--"
  19150. ("Column"
  19151. ["Move Column Left" org-metaleft (org-at-table-p)]
  19152. ["Move Column Right" org-metaright (org-at-table-p)]
  19153. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19154. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  19155. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  19156. ("Row"
  19157. ["Move Row Up" org-metaup (org-at-table-p)]
  19158. ["Move Row Down" org-metadown (org-at-table-p)]
  19159. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19160. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19161. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19162. "--"
  19163. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19164. ("Rectangle"
  19165. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19166. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19167. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19168. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19169. "--"
  19170. ("Calculate"
  19171. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19172. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19173. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19174. "--"
  19175. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19176. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19177. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19178. "--"
  19179. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19180. "--"
  19181. ["Sum Column/Rectangle" org-table-sum
  19182. (or (org-at-table-p) (org-region-active-p))]
  19183. ["Which Column?" org-table-current-column (org-at-table-p)])
  19184. ["Debug Formulas"
  19185. org-table-toggle-formula-debugger
  19186. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19187. ["Show Col/Row Numbers"
  19188. org-table-toggle-coordinate-overlays
  19189. :style toggle
  19190. :selected (bound-and-true-p org-table-overlay-coordinates)]
  19191. "--"
  19192. ["Create" org-table-create (not (org-at-table-p))]
  19193. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19194. ["Import from File" org-table-import (not (org-at-table-p))]
  19195. ["Export to File" org-table-export (org-at-table-p)]
  19196. "--"
  19197. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19198. "--"
  19199. ("Plot"
  19200. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19201. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19202. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19203. '("Org"
  19204. ("Show/Hide"
  19205. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19206. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19207. ["Sparse Tree..." org-sparse-tree t]
  19208. ["Reveal Context" org-reveal t]
  19209. ["Show All" outline-show-all t]
  19210. "--"
  19211. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19212. "--"
  19213. ["New Heading" org-insert-heading t]
  19214. ("Navigate Headings"
  19215. ["Up" outline-up-heading t]
  19216. ["Next" outline-next-visible-heading t]
  19217. ["Previous" outline-previous-visible-heading t]
  19218. ["Next Same Level" outline-forward-same-level t]
  19219. ["Previous Same Level" outline-backward-same-level t]
  19220. "--"
  19221. ["Jump" org-goto t])
  19222. ("Edit Structure"
  19223. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19224. "--"
  19225. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19226. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19227. "--"
  19228. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19229. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19230. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19231. "--"
  19232. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19233. "--"
  19234. ["Copy visible text" org-copy-visible t]
  19235. "--"
  19236. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19237. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19238. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19239. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19240. "--"
  19241. ["Sort Region/Children" org-sort t]
  19242. "--"
  19243. ["Convert to odd levels" org-convert-to-odd-levels t]
  19244. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19245. ("Editing"
  19246. ["Emphasis..." org-emphasize t]
  19247. ["Edit Source Example" org-edit-special t]
  19248. "--"
  19249. ["Footnote new/jump" org-footnote-action t]
  19250. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19251. ("Archive"
  19252. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19253. "--"
  19254. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19255. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19256. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19257. )
  19258. "--"
  19259. ("Hyperlinks"
  19260. ["Store Link (Global)" org-store-link t]
  19261. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19262. ["Insert Link" org-insert-link t]
  19263. ["Follow Link" org-open-at-point t]
  19264. "--"
  19265. ["Next link" org-next-link t]
  19266. ["Previous link" org-previous-link t]
  19267. "--"
  19268. ["Descriptive Links"
  19269. org-toggle-link-display
  19270. :style radio
  19271. :selected org-descriptive-links
  19272. ]
  19273. ["Literal Links"
  19274. org-toggle-link-display
  19275. :style radio
  19276. :selected (not org-descriptive-links)])
  19277. "--"
  19278. ("TODO Lists"
  19279. ["TODO/DONE/-" org-todo t]
  19280. ("Select keyword"
  19281. ["Next keyword" org-shiftright (org-at-heading-p)]
  19282. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19283. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19284. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19285. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19286. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19287. ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
  19288. "--"
  19289. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19290. :selected org-enforce-todo-dependencies :style toggle :active t]
  19291. "Settings for tree at point"
  19292. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19293. :selected (org-entry-get nil "ORDERED")
  19294. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19295. ["Do Children parallel" org-toggle-ordered-property :style radio
  19296. :selected (not (org-entry-get nil "ORDERED"))
  19297. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19298. "--"
  19299. ["Set Priority" org-priority t]
  19300. ["Priority Up" org-shiftup t]
  19301. ["Priority Down" org-shiftdown t]
  19302. "--"
  19303. ["Get news from all feeds" org-feed-update-all t]
  19304. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19305. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19306. ("TAGS and Properties"
  19307. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19308. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19309. "--"
  19310. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19311. ["Column view of properties" org-columns t]
  19312. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19313. ("Dates and Scheduling"
  19314. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19315. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19316. ("Change Date"
  19317. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  19318. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  19319. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  19320. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  19321. ["Compute Time Range" org-evaluate-time-range t]
  19322. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19323. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19324. "--"
  19325. ["Custom time format" org-toggle-time-stamp-overlays
  19326. :style radio :selected org-display-custom-times]
  19327. "--"
  19328. ["Goto Calendar" org-goto-calendar t]
  19329. ["Date from Calendar" org-date-from-calendar t]
  19330. "--"
  19331. ["Start/Restart Timer" org-timer-start t]
  19332. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19333. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19334. ["Insert Timer String" org-timer t]
  19335. ["Insert Timer Item" org-timer-item t])
  19336. ("Logging work"
  19337. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19338. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19339. ["Clock out" org-clock-out t]
  19340. ["Clock cancel" org-clock-cancel t]
  19341. "--"
  19342. ["Mark as default task" org-clock-mark-default-task t]
  19343. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19344. ["Goto running clock" org-clock-goto t]
  19345. "--"
  19346. ["Display times" org-clock-display t]
  19347. ["Create clock table" org-clock-report t]
  19348. "--"
  19349. ["Record DONE time"
  19350. (progn (setq org-log-done (not org-log-done))
  19351. (message "Switching to %s will %s record a timestamp"
  19352. (car org-done-keywords)
  19353. (if org-log-done "automatically" "not")))
  19354. :style toggle :selected org-log-done])
  19355. "--"
  19356. ["Agenda Command..." org-agenda t]
  19357. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19358. ("File List for Agenda")
  19359. ("Special views current file"
  19360. ["TODO Tree" org-show-todo-tree t]
  19361. ["Check Deadlines" org-check-deadlines t]
  19362. ["Tags/Property tree" org-match-sparse-tree t])
  19363. "--"
  19364. ["Export/Publish..." org-export-dispatch t]
  19365. ("LaTeX"
  19366. ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
  19367. :selected org-cdlatex-mode]
  19368. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19369. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19370. ["Modify math symbol" org-cdlatex-math-modify
  19371. (org-inside-LaTeX-fragment-p)]
  19372. ["Insert citation" org-reftex-citation t])
  19373. "--"
  19374. ("MobileOrg"
  19375. ["Push Files and Views" org-mobile-push t]
  19376. ["Get Captured and Flagged" org-mobile-pull t]
  19377. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
  19378. "--"
  19379. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19380. "--"
  19381. ("Documentation"
  19382. ["Show Version" org-version t]
  19383. ["Info Documentation" org-info t])
  19384. ("Customize"
  19385. ["Browse Org Group" org-customize t]
  19386. "--"
  19387. ["Expand This Menu" org-create-customize-menu
  19388. (fboundp 'customize-menu-create)])
  19389. ["Send bug report" org-submit-bug-report t]
  19390. "--"
  19391. ("Refresh/Reload"
  19392. ["Refresh setup current buffer" org-mode-restart t]
  19393. ["Reload Org (after update)" org-reload t]
  19394. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  19395. ))
  19396. (defun org-info (&optional node)
  19397. "Read documentation for Org in the info system.
  19398. With optional NODE, go directly to that node."
  19399. (interactive)
  19400. (info (format "(org)%s" (or node ""))))
  19401. ;;;###autoload
  19402. (defun org-submit-bug-report ()
  19403. "Submit a bug report on Org via mail.
  19404. Don't hesitate to report any problems or inaccurate documentation.
  19405. If you don't have setup sending mail from (X)Emacs, please copy the
  19406. output buffer into your mail program, as it gives us important
  19407. information about your Org version and configuration."
  19408. (interactive)
  19409. (require 'reporter)
  19410. (defvar reporter-prompt-for-summary-p)
  19411. (org-load-modules-maybe)
  19412. (org-require-autoloaded-modules)
  19413. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19414. (reporter-submit-bug-report
  19415. "emacs-orgmode@gnu.org"
  19416. (org-version nil 'full)
  19417. (let (list)
  19418. (save-window-excursion
  19419. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19420. (delete-other-windows)
  19421. (erase-buffer)
  19422. (insert "You are about to submit a bug report to the Org mailing list.
  19423. We would like to add your full Org and Outline configuration to the
  19424. bug report. This greatly simplifies the work of the maintainer and
  19425. other experts on the mailing list.
  19426. HOWEVER, some variables you have customized may contain private
  19427. information. The names of customers, colleagues, or friends, might
  19428. appear in the form of file names, tags, todo states, or search strings.
  19429. If you answer yes to the prompt, you might want to check and remove
  19430. such private information before sending the email.")
  19431. (add-text-properties (point-min) (point-max) '(face org-warning))
  19432. (when (yes-or-no-p "Include your Org configuration ")
  19433. (mapatoms
  19434. (lambda (v)
  19435. (and (boundp v)
  19436. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19437. (or (and (symbol-value v)
  19438. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19439. (and
  19440. (get v 'custom-type) (get v 'standard-value)
  19441. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19442. (push v list)))))
  19443. (kill-buffer (get-buffer "*Warn about privacy*"))
  19444. list))
  19445. nil nil
  19446. "Remember to cover the basics, that is, what you expected to happen and
  19447. what in fact did happen. You don't know how to make a good report? See
  19448. http://orgmode.org/manual/Feedback.html#Feedback
  19449. Your bug report will be posted to the Org mailing list.
  19450. ------------------------------------------------------------------------")
  19451. (save-excursion
  19452. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19453. (replace-match "\\1Bug: \\3 [\\2]")))))
  19454. (defun org-install-agenda-files-menu ()
  19455. (let ((bl (buffer-list)))
  19456. (save-excursion
  19457. (while bl
  19458. (set-buffer (pop bl))
  19459. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19460. (when (derived-mode-p 'org-mode)
  19461. (easy-menu-change
  19462. '("Org") "File List for Agenda"
  19463. (append
  19464. (list
  19465. ["Edit File List" (org-edit-agenda-file-list) t]
  19466. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19467. ["Remove Current File from List" org-remove-file t]
  19468. ["Cycle through agenda files" org-cycle-agenda-files t]
  19469. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19470. "--")
  19471. (mapcar 'org-file-menu-entry
  19472. ;; Prevent initialization from failing.
  19473. (ignore-errors (org-agenda-files t)))))))))
  19474. ;;;; Documentation
  19475. (defun org-require-autoloaded-modules ()
  19476. (interactive)
  19477. (mapc #'require
  19478. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19479. org-table org-timer)))
  19480. ;;;###autoload
  19481. (defun org-reload (&optional uncompiled)
  19482. "Reload all org lisp files.
  19483. With prefix arg UNCOMPILED, load the uncompiled versions."
  19484. (interactive "P")
  19485. (require 'loadhist)
  19486. (let* ((org-dir (org-find-library-dir "org"))
  19487. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19488. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  19489. (remove-re (format "\\`%s\\'"
  19490. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19491. (feats (delete-dups
  19492. (mapcar 'file-name-sans-extension
  19493. (mapcar 'file-name-nondirectory
  19494. (delq nil
  19495. (mapcar 'feature-file
  19496. features))))))
  19497. (lfeat (append
  19498. (sort
  19499. (setq feats
  19500. (delq nil (mapcar
  19501. (lambda (f)
  19502. (if (and (string-match feature-re f)
  19503. (not (string-match remove-re f)))
  19504. f nil))
  19505. feats)))
  19506. 'string-lessp)
  19507. (list "org-version" "org")))
  19508. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  19509. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19510. load-uncore load-misses)
  19511. (setq load-misses
  19512. (delq 't
  19513. (mapcar (lambda (f)
  19514. (or (org-load-noerror-mustsuffix (concat org-dir f))
  19515. (and (string= org-dir contrib-dir)
  19516. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19517. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19518. (add-to-list 'load-uncore f 'append)
  19519. 't)
  19520. f))
  19521. lfeat)))
  19522. (when load-uncore
  19523. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19524. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  19525. (if load-misses
  19526. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19527. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19528. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19529. ;;;###autoload
  19530. (defun org-customize ()
  19531. "Call the customize function with org as argument."
  19532. (interactive)
  19533. (org-load-modules-maybe)
  19534. (org-require-autoloaded-modules)
  19535. (customize-browse 'org))
  19536. (defun org-create-customize-menu ()
  19537. "Create a full customization menu for Org mode, insert it into the menu."
  19538. (interactive)
  19539. (org-load-modules-maybe)
  19540. (org-require-autoloaded-modules)
  19541. (if (fboundp 'customize-menu-create)
  19542. (progn
  19543. (easy-menu-change
  19544. '("Org") "Customize"
  19545. `(["Browse Org group" org-customize t]
  19546. "--"
  19547. ,(customize-menu-create 'org)
  19548. ["Set" Custom-set t]
  19549. ["Save" Custom-save t]
  19550. ["Reset to Current" Custom-reset-current t]
  19551. ["Reset to Saved" Custom-reset-saved t]
  19552. ["Reset to Standard Settings" Custom-reset-standard t]))
  19553. (message "\"Org\"-menu now contains full customization menu"))
  19554. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  19555. ;;;; Miscellaneous stuff
  19556. ;;; Generally useful functions
  19557. (defun org-link-display-format (s)
  19558. "Replace links in string S with their description.
  19559. If there is no description, use the link target."
  19560. (save-match-data
  19561. (replace-regexp-in-string
  19562. org-bracket-link-analytic-regexp
  19563. (lambda (m)
  19564. (if (match-end 5) (match-string 5 m)
  19565. (concat (match-string 1 m) (match-string 3 m))))
  19566. s nil t)))
  19567. (defun org-toggle-link-display ()
  19568. "Toggle the literal or descriptive display of links."
  19569. (interactive)
  19570. (if org-descriptive-links
  19571. (progn (org-remove-from-invisibility-spec '(org-link))
  19572. (org-restart-font-lock)
  19573. (setq org-descriptive-links nil))
  19574. (progn (add-to-invisibility-spec '(org-link))
  19575. (org-restart-font-lock)
  19576. (setq org-descriptive-links t))))
  19577. (defun org-in-clocktable-p ()
  19578. "Check if the cursor is in a clocktable."
  19579. (let ((pos (point)) start)
  19580. (save-excursion
  19581. (end-of-line 1)
  19582. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19583. (setq start (match-beginning 0))
  19584. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19585. (>= (match-end 0) pos)
  19586. start))))
  19587. (defun org-in-verbatim-emphasis ()
  19588. (save-match-data
  19589. (and (org-in-regexp org-verbatim-re 2)
  19590. (>= (point) (match-beginning 3))
  19591. (<= (point) (match-end 4)))))
  19592. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19593. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  19594. (if (and marker (marker-buffer marker)
  19595. (buffer-live-p (marker-buffer marker)))
  19596. (progn
  19597. (pop-to-buffer-same-window (marker-buffer marker))
  19598. (when (or (> marker (point-max)) (< marker (point-min)))
  19599. (widen))
  19600. (goto-char marker)
  19601. (org-show-context 'org-goto))
  19602. (if bookmark
  19603. (bookmark-jump bookmark)
  19604. (error "Cannot find location"))))
  19605. (defun org-quote-csv-field (s)
  19606. "Quote field for inclusion in CSV material."
  19607. (if (string-match "[\",]" s)
  19608. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19609. s))
  19610. (defun org-force-self-insert (N)
  19611. "Needed to enforce self-insert under remapping."
  19612. (interactive "p")
  19613. (self-insert-command N))
  19614. (defun org-get-indentation (&optional line)
  19615. "Get the indentation of the current line, interpreting tabs.
  19616. When LINE is given, assume it represents a line and compute its indentation."
  19617. (if line
  19618. (when (string-match "^ *" (org-remove-tabs line))
  19619. (match-end 0))
  19620. (save-excursion
  19621. (beginning-of-line 1)
  19622. (skip-chars-forward " \t")
  19623. (current-column))))
  19624. (defun org-get-string-indentation (s)
  19625. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  19626. (let ((n -1) (i 0) (w tab-width) c)
  19627. (catch 'exit
  19628. (while (< (setq n (1+ n)) (length s))
  19629. (setq c (aref s n))
  19630. (cond ((= c ?\ ) (setq i (1+ i)))
  19631. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  19632. (t (throw 'exit t)))))
  19633. i))
  19634. (defun org-fix-indentation (line ind)
  19635. "Fix indentation in LINE.
  19636. IND is a cons cell with target and minimum indentation.
  19637. If the current indentation in LINE is smaller than the minimum,
  19638. leave it alone. If it is larger than ind, set it to the target."
  19639. (let* ((l (org-remove-tabs line))
  19640. (i (org-get-indentation l))
  19641. (i1 (car ind)) (i2 (cdr ind)))
  19642. (when (>= i i2) (setq l (substring line i2)))
  19643. (if (> i1 0)
  19644. (concat (make-string i1 ?\ ) l)
  19645. l)))
  19646. (defun org-fill-template (template alist)
  19647. "Find each %key of ALIST in TEMPLATE and replace it."
  19648. (let ((case-fold-search nil))
  19649. (dolist (entry (sort (copy-sequence alist)
  19650. (lambda (a b) (< (length (car a)) (length (car b))))))
  19651. (setq template
  19652. (replace-regexp-in-string
  19653. (concat "%" (regexp-quote (car entry)))
  19654. (or (cdr entry) "") template t t)))
  19655. template))
  19656. (defun org-quote-vert (s)
  19657. "Replace \"|\" with \"\\vert\"."
  19658. (while (string-match "|" s)
  19659. (setq s (replace-match "\\vert" t t s)))
  19660. s)
  19661. (defun org-uuidgen-p (s)
  19662. "Is S an ID created by UUIDGEN?"
  19663. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  19664. (defun org-in-src-block-p (&optional inside)
  19665. "Whether point is in a code source block.
  19666. When INSIDE is non-nil, don't consider we are within a src block
  19667. when point is at #+BEGIN_SRC or #+END_SRC."
  19668. (let ((case-fold-search t))
  19669. (or (and (eq (get-char-property (point) 'src-block) t))
  19670. (and (not inside)
  19671. (save-match-data
  19672. (save-excursion
  19673. (beginning-of-line)
  19674. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  19675. (defun org-context ()
  19676. "Return a list of contexts of the current cursor position.
  19677. If several contexts apply, all are returned.
  19678. Each context entry is a list with a symbol naming the context, and
  19679. two positions indicating start and end of the context. Possible
  19680. contexts are:
  19681. :headline anywhere in a headline
  19682. :headline-stars on the leading stars in a headline
  19683. :todo-keyword on a TODO keyword (including DONE) in a headline
  19684. :tags on the TAGS in a headline
  19685. :priority on the priority cookie in a headline
  19686. :item on the first line of a plain list item
  19687. :item-bullet on the bullet/number of a plain list item
  19688. :checkbox on the checkbox in a plain list item
  19689. :table in an Org table
  19690. :table-special on a special filed in a table
  19691. :table-table in a table.el table
  19692. :clocktable in a clocktable
  19693. :src-block in a source block
  19694. :link on a hyperlink
  19695. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  19696. :target on a <<target>>
  19697. :radio-target on a <<<radio-target>>>
  19698. :latex-fragment on a LaTeX fragment
  19699. :latex-preview on a LaTeX fragment with overlaid preview image
  19700. This function expects the position to be visible because it uses font-lock
  19701. faces as a help to recognize the following contexts: :table-special, :link,
  19702. and :keyword."
  19703. (let* ((f (get-text-property (point) 'face))
  19704. (faces (if (listp f) f (list f)))
  19705. (case-fold-search t)
  19706. (p (point)) clist o)
  19707. ;; First the large context
  19708. (cond
  19709. ((org-at-heading-p t)
  19710. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  19711. (when (progn
  19712. (beginning-of-line 1)
  19713. (looking-at org-todo-line-tags-regexp))
  19714. (push (org-point-in-group p 1 :headline-stars) clist)
  19715. (push (org-point-in-group p 2 :todo-keyword) clist)
  19716. (push (org-point-in-group p 4 :tags) clist))
  19717. (goto-char p)
  19718. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  19719. (when (looking-at "\\[#[A-Z0-9]\\]")
  19720. (push (org-point-in-group p 0 :priority) clist)))
  19721. ((org-at-item-p)
  19722. (push (org-point-in-group p 2 :item-bullet) clist)
  19723. (push (list :item (point-at-bol)
  19724. (save-excursion (org-end-of-item) (point)))
  19725. clist)
  19726. (and (org-at-item-checkbox-p)
  19727. (push (org-point-in-group p 0 :checkbox) clist)))
  19728. ((org-at-table-p)
  19729. (push (list :table (org-table-begin) (org-table-end)) clist)
  19730. (when (memq 'org-formula faces)
  19731. (push (list :table-special
  19732. (previous-single-property-change p 'face)
  19733. (next-single-property-change p 'face)) clist)))
  19734. ((org-at-table-p 'any)
  19735. (push (list :table-table) clist)))
  19736. (goto-char p)
  19737. (let ((case-fold-search t))
  19738. ;; New the "medium" contexts: clocktables, source blocks
  19739. (cond ((org-in-clocktable-p)
  19740. (push (list :clocktable
  19741. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  19742. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  19743. (match-beginning 1))
  19744. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  19745. (match-end 0))) clist))
  19746. ((org-in-src-block-p)
  19747. (push (list :src-block
  19748. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  19749. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  19750. (match-beginning 1))
  19751. (and (search-forward "#+END_SRC" nil t)
  19752. (match-beginning 0))) clist))))
  19753. (goto-char p)
  19754. ;; Now the small context
  19755. (cond
  19756. ((org-at-timestamp-p)
  19757. (push (org-point-in-group p 0 :timestamp) clist))
  19758. ((memq 'org-link faces)
  19759. (push (list :link
  19760. (previous-single-property-change p 'face)
  19761. (next-single-property-change p 'face)) clist))
  19762. ((memq 'org-special-keyword faces)
  19763. (push (list :keyword
  19764. (previous-single-property-change p 'face)
  19765. (next-single-property-change p 'face)) clist))
  19766. ((org-at-target-p)
  19767. (push (org-point-in-group p 0 :target) clist)
  19768. (goto-char (1- (match-beginning 0)))
  19769. (when (looking-at org-radio-target-regexp)
  19770. (push (org-point-in-group p 0 :radio-target) clist))
  19771. (goto-char p))
  19772. ((setq o (cl-some
  19773. (lambda (o)
  19774. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  19775. o))
  19776. (overlays-at (point))))
  19777. (push (list :latex-fragment
  19778. (overlay-start o) (overlay-end o)) clist)
  19779. (push (list :latex-preview
  19780. (overlay-start o) (overlay-end o)) clist))
  19781. ((org-inside-LaTeX-fragment-p)
  19782. ;; FIXME: positions wrong.
  19783. (push (list :latex-fragment (point) (point)) clist)))
  19784. (setq clist (nreverse (delq nil clist)))
  19785. clist))
  19786. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  19787. "Non-nil when point is between matches of START-RE and END-RE.
  19788. Also return a non-nil value when point is on one of the matches.
  19789. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  19790. buffer positions. Default values are the positions of headlines
  19791. surrounding the point.
  19792. The functions returns a cons cell whose car (resp. cdr) is the
  19793. position before START-RE (resp. after END-RE)."
  19794. (save-match-data
  19795. (let ((pos (point))
  19796. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  19797. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  19798. beg end)
  19799. (save-excursion
  19800. ;; Point is on a block when on START-RE or if START-RE can be
  19801. ;; found before it...
  19802. (and (or (org-in-regexp start-re)
  19803. (re-search-backward start-re limit-up t))
  19804. (setq beg (match-beginning 0))
  19805. ;; ... and END-RE after it...
  19806. (goto-char (match-end 0))
  19807. (re-search-forward end-re limit-down t)
  19808. (> (setq end (match-end 0)) pos)
  19809. ;; ... without another START-RE in-between.
  19810. (goto-char (match-beginning 0))
  19811. (not (re-search-backward start-re (1+ beg) t))
  19812. ;; Return value.
  19813. (cons beg end))))))
  19814. (defun org-in-block-p (names)
  19815. "Non-nil when point belongs to a block whose name belongs to NAMES.
  19816. NAMES is a list of strings containing names of blocks.
  19817. Return first block name matched, or nil. Beware that in case of
  19818. nested blocks, the returned name may not belong to the closest
  19819. block from point."
  19820. (save-match-data
  19821. (catch 'exit
  19822. (let ((case-fold-search t)
  19823. (lim-up (save-excursion (outline-previous-heading)))
  19824. (lim-down (save-excursion (outline-next-heading))))
  19825. (dolist (name names)
  19826. (let ((n (regexp-quote name)))
  19827. (when (org-between-regexps-p
  19828. (concat "^[ \t]*#\\+begin_" n)
  19829. (concat "^[ \t]*#\\+end_" n)
  19830. lim-up lim-down)
  19831. (throw 'exit n)))))
  19832. nil)))
  19833. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  19834. "Call `multi-occur' with buffers for all agenda files."
  19835. (interactive "sOrg-files matching: ")
  19836. (let* ((files (org-agenda-files))
  19837. (tnames (mapcar #'file-truename files))
  19838. (extra org-agenda-text-search-extra-files))
  19839. (when (eq (car extra) 'agenda-archives)
  19840. (setq extra (cdr extra))
  19841. (setq files (org-add-archive-files files)))
  19842. (dolist (f extra)
  19843. (unless (member (file-truename f) tnames)
  19844. (unless (member f files) (setq files (append files (list f))))
  19845. (setq tnames (append tnames (list (file-truename f))))))
  19846. (multi-occur
  19847. (mapcar (lambda (x)
  19848. (with-current-buffer
  19849. ;; FIXME: Why not just (find-file-noselect x)?
  19850. ;; Is it to avoid the "revert buffer" prompt?
  19851. (or (get-file-buffer x) (find-file-noselect x))
  19852. (widen)
  19853. (current-buffer)))
  19854. files)
  19855. regexp)))
  19856. (add-hook 'occur-mode-find-occurrence-hook
  19857. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  19858. (defun org-occur-link-in-agenda-files ()
  19859. "Create a link and search for it in the agendas.
  19860. The link is not stored in `org-stored-links', it is just created
  19861. for the search purpose."
  19862. (interactive)
  19863. (let ((link (condition-case nil
  19864. (org-store-link nil)
  19865. (error "Unable to create a link to here"))))
  19866. (org-occur-in-agenda-files (regexp-quote link))))
  19867. (defun org-back-over-empty-lines ()
  19868. "Move backwards over whitespace, to the beginning of the first empty line.
  19869. Returns the number of empty lines passed."
  19870. (let ((pos (point)))
  19871. (if (cdr (assq 'heading org-blank-before-new-entry))
  19872. (skip-chars-backward " \t\n\r")
  19873. (unless (eobp)
  19874. (forward-line -1)))
  19875. (beginning-of-line 2)
  19876. (goto-char (min (point) pos))
  19877. (count-lines (point) pos)))
  19878. (defun org-switch-to-buffer-other-window (&rest args)
  19879. "Switch to buffer in a second window on the current frame.
  19880. In particular, do not allow pop-up frames.
  19881. Returns the newly created buffer."
  19882. (org-no-popups
  19883. (apply 'switch-to-buffer-other-window args)))
  19884. (defun org-replace-escapes (string table)
  19885. "Replace %-escapes in STRING with values in TABLE.
  19886. TABLE is an association list with keys like \"%a\" and string values.
  19887. The sequences in STRING may contain normal field width and padding information,
  19888. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  19889. so values can contain further %-escapes if they are define later in TABLE."
  19890. (let ((tbl (copy-alist table))
  19891. (case-fold-search nil)
  19892. (pchg 0)
  19893. re rpl)
  19894. (dolist (e tbl)
  19895. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  19896. (when (and (cdr e) (string-match re (cdr e)))
  19897. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  19898. (safe "SREF"))
  19899. (add-text-properties 0 3 (list 'sref sref) safe)
  19900. (setcdr e (replace-match safe t t (cdr e)))))
  19901. (while (string-match re string)
  19902. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  19903. (cdr e)))
  19904. (setq string (replace-match rpl t t string))))
  19905. (while (setq pchg (next-property-change pchg string))
  19906. (let ((sref (get-text-property pchg 'sref string)))
  19907. (when (and sref (string-match "SREF" string pchg))
  19908. (setq string (replace-match sref t t string)))))
  19909. string))
  19910. ;;; TODO: Only called once, from ox-odt which should probably use
  19911. ;;; org-export-inline-image-p or something.
  19912. (defun org-file-image-p (file)
  19913. "Return non-nil if FILE is an image."
  19914. (save-match-data
  19915. (string-match (image-file-name-regexp) file)))
  19916. (defun org-get-cursor-date (&optional with-time)
  19917. "Return the date at cursor in as a time.
  19918. This works in the calendar and in the agenda, anywhere else it just
  19919. returns the current time.
  19920. If WITH-TIME is non-nil, returns the time of the event at point (in
  19921. the agenda) or the current time of the day."
  19922. (let (date day defd tp hod mod)
  19923. (when with-time
  19924. (setq tp (get-text-property (point) 'time))
  19925. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  19926. (setq hod (string-to-number (match-string 1 tp))
  19927. mod (string-to-number (match-string 2 tp))))
  19928. (or tp (let ((now (decode-time)))
  19929. (setq hod (nth 2 now)
  19930. mod (nth 1 now)))))
  19931. (cond
  19932. ((eq major-mode 'calendar-mode)
  19933. (setq date (calendar-cursor-to-date)
  19934. defd (encode-time 0 (or mod 0) (or hod 0)
  19935. (nth 1 date) (nth 0 date) (nth 2 date))))
  19936. ((eq major-mode 'org-agenda-mode)
  19937. (setq day (get-text-property (point) 'day))
  19938. (when day
  19939. (setq date (calendar-gregorian-from-absolute day)
  19940. defd (encode-time 0 (or mod 0) (or hod 0)
  19941. (nth 1 date) (nth 0 date) (nth 2 date))))))
  19942. (or defd (current-time))))
  19943. (defun org-mark-subtree (&optional up)
  19944. "Mark the current subtree.
  19945. This puts point at the start of the current subtree, and mark at
  19946. the end. If a numeric prefix UP is given, move up into the
  19947. hierarchy of headlines by UP levels before marking the subtree."
  19948. (interactive "P")
  19949. (org-with-limited-levels
  19950. (cond ((org-at-heading-p) (beginning-of-line))
  19951. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  19952. (t (outline-previous-visible-heading 1))))
  19953. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  19954. (if (called-interactively-p 'any)
  19955. (call-interactively 'org-mark-element)
  19956. (org-mark-element)))
  19957. (defun org-file-newer-than-p (file time)
  19958. "Non-nil if FILE is newer than TIME.
  19959. FILE is a filename, as a string, TIME is a list of integers, as
  19960. returned by, e.g., `current-time'."
  19961. (and (file-exists-p file)
  19962. ;; Only compare times up to whole seconds as some file-systems
  19963. ;; (e.g. HFS+) do not retain any finer granularity. As
  19964. ;; a consequence, make sure we return non-nil when the two
  19965. ;; times are equal.
  19966. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  19967. (cl-subseq time 0 2)))))
  19968. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  19969. "Compile a SOURCE file using PROCESS.
  19970. PROCESS is either a function or a list of shell commands, as
  19971. strings. EXT is a file extension, without the leading dot, as
  19972. a string. It is used to check if the process actually succeeded.
  19973. PROCESS must create a file with the same base name and directory
  19974. as SOURCE, but ending with EXT. The function then returns its
  19975. filename. Otherwise, it raises an error. The error message can
  19976. then be refined by providing string ERR-MSG, which is appended to
  19977. the standard message.
  19978. If PROCESS is a function, it is called with a single argument:
  19979. the SOURCE file.
  19980. If it is a list of commands, each of them is called using
  19981. `shell-command'. By default, in each command, %b, %f, %F, %o and
  19982. %O are replaced with, respectively, SOURCE base name, name, full
  19983. name, directory and absolute output file name. It is possible,
  19984. however, to use more place-holders by specifying them in optional
  19985. argument SPEC, as an alist following the pattern
  19986. (CHARACTER . REPLACEMENT-STRING).
  19987. When PROCESS is a list of commands, optional argument LOG-BUF can
  19988. be set to a buffer or a buffer name. `shell-command' then uses
  19989. it for output."
  19990. (let* ((base-name (file-name-base source))
  19991. (full-name (file-truename source))
  19992. (out-dir (or (file-name-directory source) "./"))
  19993. (output (expand-file-name (concat base-name "." ext) out-dir))
  19994. (time (current-time))
  19995. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  19996. (save-window-excursion
  19997. (pcase process
  19998. ((pred functionp) (funcall process (shell-quote-argument source)))
  19999. ((pred consp)
  20000. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  20001. (spec (append spec
  20002. `((?b . ,(shell-quote-argument base-name))
  20003. (?f . ,(shell-quote-argument source))
  20004. (?F . ,(shell-quote-argument full-name))
  20005. (?o . ,(shell-quote-argument out-dir))
  20006. (?O . ,(shell-quote-argument output))))))
  20007. (dolist (command process)
  20008. (shell-command (format-spec command spec) log-buf))
  20009. (when log-buf (with-current-buffer log-buf (compilation-mode)))))
  20010. (_ (error "No valid command to process %S%s" source err-msg))))
  20011. ;; Check for process failure. Output file is expected to be
  20012. ;; located in the same directory as SOURCE.
  20013. (unless (org-file-newer-than-p output time)
  20014. (error (format "File %S wasn't produced%s" output err-msg)))
  20015. output))
  20016. ;;; Indentation
  20017. (defvar org-element-greater-elements)
  20018. (defun org--get-expected-indentation (element contentsp)
  20019. "Expected indentation column for current line, according to ELEMENT.
  20020. ELEMENT is an element containing point. CONTENTSP is non-nil
  20021. when indentation is to be computed according to contents of
  20022. ELEMENT."
  20023. (let ((type (org-element-type element))
  20024. (start (org-element-property :begin element))
  20025. (post-affiliated (org-element-property :post-affiliated element)))
  20026. (org-with-wide-buffer
  20027. (cond
  20028. (contentsp
  20029. (cl-case type
  20030. ((diary-sexp footnote-definition) 0)
  20031. ((headline inlinetask nil)
  20032. (if (not org-adapt-indentation) 0
  20033. (let ((level (org-current-level)))
  20034. (if level (1+ level) 0))))
  20035. ((item plain-list) (org-list-item-body-column post-affiliated))
  20036. (t
  20037. (goto-char start)
  20038. (org-get-indentation))))
  20039. ((memq type '(headline inlinetask nil))
  20040. (if (org-match-line "[ \t]*$")
  20041. (org--get-expected-indentation element t)
  20042. 0))
  20043. ((memq type '(diary-sexp footnote-definition)) 0)
  20044. ;; First paragraph of a footnote definition or an item.
  20045. ;; Indent like parent.
  20046. ((< (line-beginning-position) start)
  20047. (org--get-expected-indentation
  20048. (org-element-property :parent element) t))
  20049. ;; At first line: indent according to previous sibling, if any,
  20050. ;; ignoring footnote definitions and inline tasks, or parent's
  20051. ;; contents.
  20052. ((= (line-beginning-position) start)
  20053. (catch 'exit
  20054. (while t
  20055. (if (= (point-min) start) (throw 'exit 0)
  20056. (goto-char (1- start))
  20057. (let* ((previous (org-element-at-point))
  20058. (parent previous))
  20059. (while (and parent (<= (org-element-property :end parent) start))
  20060. (setq previous parent
  20061. parent (org-element-property :parent parent)))
  20062. (cond
  20063. ((not previous) (throw 'exit 0))
  20064. ((> (org-element-property :end previous) start)
  20065. (throw 'exit (org--get-expected-indentation previous t)))
  20066. ((memq (org-element-type previous)
  20067. '(footnote-definition inlinetask))
  20068. (setq start (org-element-property :begin previous)))
  20069. (t (goto-char (org-element-property :begin previous))
  20070. (throw 'exit
  20071. (if (bolp) (org-get-indentation)
  20072. ;; At first paragraph in an item or
  20073. ;; a footnote definition.
  20074. (org--get-expected-indentation
  20075. (org-element-property :parent previous) t))))))))))
  20076. ;; Otherwise, move to the first non-blank line above.
  20077. (t
  20078. (beginning-of-line)
  20079. (let ((pos (point)))
  20080. (skip-chars-backward " \r\t\n")
  20081. (cond
  20082. ;; Two blank lines end a footnote definition or a plain
  20083. ;; list. When we indent an empty line after them, the
  20084. ;; containing list or footnote definition is over, so it
  20085. ;; qualifies as a previous sibling. Therefore, we indent
  20086. ;; like its first line.
  20087. ((and (memq type '(footnote-definition plain-list))
  20088. (> (count-lines (point) pos) 2))
  20089. (goto-char start)
  20090. (org-get-indentation))
  20091. ;; Line above is the first one of a paragraph at the
  20092. ;; beginning of an item or a footnote definition. Indent
  20093. ;; like parent.
  20094. ((< (line-beginning-position) start)
  20095. (org--get-expected-indentation
  20096. (org-element-property :parent element) t))
  20097. ;; Line above is the beginning of an element, i.e., point
  20098. ;; was originally on the blank lines between element's start
  20099. ;; and contents.
  20100. ((= (line-beginning-position) post-affiliated)
  20101. (org--get-expected-indentation element t))
  20102. ;; POS is after contents in a greater element. Indent like
  20103. ;; the beginning of the element.
  20104. ((and (memq type org-element-greater-elements)
  20105. (let ((cend (org-element-property :contents-end element)))
  20106. (and cend (<= cend pos))))
  20107. ;; As a special case, if point is at the end of a footnote
  20108. ;; definition or an item, indent like the very last element
  20109. ;; within. If that last element is an item, indent like
  20110. ;; its contents.
  20111. (if (memq type '(footnote-definition item plain-list))
  20112. (let ((last (org-element-at-point)))
  20113. (goto-char pos)
  20114. (org--get-expected-indentation
  20115. last (eq (org-element-type last) 'item)))
  20116. (goto-char start)
  20117. (org-get-indentation)))
  20118. ;; In any other case, indent like the current line.
  20119. (t (org-get-indentation)))))))))
  20120. (defun org--align-node-property ()
  20121. "Align node property at point.
  20122. Alignment is done according to `org-property-format', which see."
  20123. (when (save-excursion
  20124. (beginning-of-line)
  20125. (looking-at org-property-re))
  20126. (replace-match
  20127. (concat (match-string 4)
  20128. (org-trim
  20129. (format org-property-format (match-string 1) (match-string 3))))
  20130. t t)))
  20131. (defun org-indent-line ()
  20132. "Indent line depending on context.
  20133. Indentation is done according to the following rules:
  20134. - Footnote definitions, diary sexps, headlines and inline tasks
  20135. have to start at column 0.
  20136. - On the very first line of an element, consider, in order, the
  20137. next rules until one matches:
  20138. 1. If there's a sibling element before, ignoring footnote
  20139. definitions and inline tasks, indent like its first line.
  20140. 2. If element has a parent, indent like its contents. More
  20141. precisely, if parent is an item, indent after the
  20142. description part, if any, or the bullet (see
  20143. `org-list-description-max-indent'). Else, indent like
  20144. parent's first line.
  20145. 3. Otherwise, indent relatively to current level, if
  20146. `org-adapt-indentation' is non-nil, or to left margin.
  20147. - On a blank line at the end of an element, indent according to
  20148. the type of the element. More precisely
  20149. 1. If element is a plain list, an item, or a footnote
  20150. definition, indent like the very last element within.
  20151. 2. If element is a paragraph, indent like its last non blank
  20152. line.
  20153. 3. Otherwise, indent like its very first line.
  20154. - In the code part of a source block, use language major mode
  20155. to indent current line if `org-src-tab-acts-natively' is
  20156. non-nil. If it is nil, do nothing.
  20157. - Otherwise, indent like the first non-blank line above.
  20158. The function doesn't indent an item as it could break the whole
  20159. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  20160. `\\[org-shiftmetaright]'.
  20161. Also align node properties according to `org-property-format'."
  20162. (interactive)
  20163. (cond
  20164. (orgstruct-is-++
  20165. (let ((indent-line-function
  20166. (cl-cadadr (assq 'indent-line-function org-fb-vars))))
  20167. (indent-according-to-mode)))
  20168. ((org-at-heading-p) 'noindent)
  20169. (t
  20170. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  20171. (type (org-element-type element)))
  20172. (cond ((and (memq type '(plain-list item))
  20173. (= (line-beginning-position)
  20174. (org-element-property :post-affiliated element)))
  20175. 'noindent)
  20176. ((and (eq type 'latex-environment)
  20177. (>= (point) (org-element-property :post-affiliated element))
  20178. (< (point) (org-with-wide-buffer
  20179. (goto-char (org-element-property :end element))
  20180. (skip-chars-backward " \r\t\n")
  20181. (line-beginning-position 2))))
  20182. 'noindent)
  20183. ((and (eq type 'src-block)
  20184. org-src-tab-acts-natively
  20185. (> (line-beginning-position)
  20186. (org-element-property :post-affiliated element))
  20187. (< (line-beginning-position)
  20188. (org-with-wide-buffer
  20189. (goto-char (org-element-property :end element))
  20190. (skip-chars-backward " \r\t\n")
  20191. (line-beginning-position))))
  20192. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  20193. (t
  20194. (let ((column (org--get-expected-indentation element nil)))
  20195. ;; Preserve current column.
  20196. (if (<= (current-column) (current-indentation))
  20197. (indent-line-to column)
  20198. (save-excursion (indent-line-to column))))
  20199. ;; Align node property. Also preserve current column.
  20200. (when (eq type 'node-property)
  20201. (let ((column (current-column)))
  20202. (org--align-node-property)
  20203. (org-move-to-column column)))))))))
  20204. (defun org-indent-region (start end)
  20205. "Indent each non-blank line in the region.
  20206. Called from a program, START and END specify the region to
  20207. indent. The function will not indent contents of example blocks,
  20208. verse blocks and export blocks as leading white spaces are
  20209. assumed to be significant there."
  20210. (interactive "r")
  20211. (save-excursion
  20212. (goto-char start)
  20213. (skip-chars-forward " \r\t\n")
  20214. (unless (eobp) (beginning-of-line))
  20215. (let ((indent-to
  20216. (lambda (ind pos)
  20217. ;; Set IND as indentation for all lines between point and
  20218. ;; POS. Blank lines are ignored. Leave point after POS
  20219. ;; once done.
  20220. (let ((limit (copy-marker pos)))
  20221. (while (< (point) limit)
  20222. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  20223. (forward-line))
  20224. (set-marker limit nil))))
  20225. (end (copy-marker end)))
  20226. (while (< (point) end)
  20227. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  20228. (let* ((element (org-element-at-point))
  20229. (type (org-element-type element))
  20230. (element-end (copy-marker (org-element-property :end element)))
  20231. (ind (org--get-expected-indentation element nil)))
  20232. (cond
  20233. ;; Element indented as a single block. Example blocks
  20234. ;; preserving indentation are a special case since the
  20235. ;; "contents" must not be indented whereas the block
  20236. ;; boundaries can.
  20237. ((or (memq type '(export-block latex-environment))
  20238. (and (eq type 'example-block)
  20239. (not
  20240. (or org-src-preserve-indentation
  20241. (org-element-property :preserve-indent element)))))
  20242. (let ((offset (- ind (org-get-indentation))))
  20243. (unless (zerop offset)
  20244. (indent-rigidly (org-element-property :begin element)
  20245. (org-element-property :end element)
  20246. offset)))
  20247. (goto-char element-end))
  20248. ;; Elements indented line wise. Be sure to exclude
  20249. ;; example blocks (preserving indentation) and source
  20250. ;; blocks from this category as they are treated
  20251. ;; specially later.
  20252. ((or (memq type '(paragraph table table-row))
  20253. (not (or (org-element-property :contents-begin element)
  20254. (memq type '(example-block src-block)))))
  20255. (when (eq type 'node-property)
  20256. (org--align-node-property)
  20257. (beginning-of-line))
  20258. (funcall indent-to ind (min element-end end)))
  20259. ;; Elements consisting of three parts: before the
  20260. ;; contents, the contents, and after the contents. The
  20261. ;; contents are treated specially, according to the
  20262. ;; element type, or not indented at all. Other parts are
  20263. ;; indented as a single block.
  20264. (t
  20265. (let* ((post (copy-marker
  20266. (org-element-property :post-affiliated element)))
  20267. (cbeg
  20268. (copy-marker
  20269. (cond
  20270. ((not (org-element-property :contents-begin element))
  20271. ;; Fake contents for source blocks.
  20272. (org-with-wide-buffer
  20273. (goto-char post)
  20274. (line-beginning-position 2)))
  20275. ((memq type '(footnote-definition item plain-list))
  20276. ;; Contents in these elements could start on
  20277. ;; the same line as the beginning of the
  20278. ;; element. Make sure we start indenting
  20279. ;; from the second line.
  20280. (org-with-wide-buffer
  20281. (goto-char post)
  20282. (end-of-line)
  20283. (skip-chars-forward " \r\t\n")
  20284. (if (eobp) (point) (line-beginning-position))))
  20285. (t (org-element-property :contents-begin element)))))
  20286. (cend (copy-marker
  20287. (or (org-element-property :contents-end element)
  20288. ;; Fake contents for source blocks.
  20289. (org-with-wide-buffer
  20290. (goto-char element-end)
  20291. (skip-chars-backward " \r\t\n")
  20292. (line-beginning-position)))
  20293. t)))
  20294. ;; Do not change items indentation individually as it
  20295. ;; might break the list as a whole. On the other
  20296. ;; hand, when at a plain list, indent it as a whole.
  20297. (cond ((eq type 'plain-list)
  20298. (let ((offset (- ind (org-get-indentation))))
  20299. (unless (zerop offset)
  20300. (indent-rigidly (org-element-property :begin element)
  20301. (org-element-property :end element)
  20302. offset))
  20303. (goto-char cbeg)))
  20304. ((eq type 'item) (goto-char cbeg))
  20305. (t (funcall indent-to ind (min cbeg end))))
  20306. (when (< (point) end)
  20307. (cl-case type
  20308. ((example-block verse-block))
  20309. (src-block
  20310. ;; In a source block, indent source code
  20311. ;; according to language major mode, but only if
  20312. ;; `org-src-tab-acts-natively' is non-nil.
  20313. (when (and (< (point) end) org-src-tab-acts-natively)
  20314. (ignore-errors
  20315. (org-babel-do-in-edit-buffer
  20316. (indent-region (point-min) (point-max))))))
  20317. (t (org-indent-region (point) (min cend end))))
  20318. (goto-char (min cend end))
  20319. (when (< (point) end)
  20320. (funcall indent-to ind (min element-end end))))
  20321. (set-marker post nil)
  20322. (set-marker cbeg nil)
  20323. (set-marker cend nil))))
  20324. (set-marker element-end nil))))
  20325. (set-marker end nil))))
  20326. (defun org-indent-drawer ()
  20327. "Indent the drawer at point."
  20328. (interactive)
  20329. (unless (save-excursion
  20330. (beginning-of-line)
  20331. (looking-at-p org-drawer-regexp))
  20332. (user-error "Not at a drawer"))
  20333. (let ((element (org-element-at-point)))
  20334. (unless (memq (org-element-type element) '(drawer property-drawer))
  20335. (user-error "Not at a drawer"))
  20336. (org-with-wide-buffer
  20337. (org-indent-region (org-element-property :begin element)
  20338. (org-element-property :end element))))
  20339. (message "Drawer at point indented"))
  20340. (defun org-indent-block ()
  20341. "Indent the block at point."
  20342. (interactive)
  20343. (unless (save-excursion
  20344. (beginning-of-line)
  20345. (let ((case-fold-search t))
  20346. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  20347. (user-error "Not at a block"))
  20348. (let ((element (org-element-at-point)))
  20349. (unless (memq (org-element-type element)
  20350. '(comment-block center-block dynamic-block example-block
  20351. export-block quote-block special-block
  20352. src-block verse-block))
  20353. (user-error "Not at a block"))
  20354. (org-with-wide-buffer
  20355. (org-indent-region (org-element-property :begin element)
  20356. (org-element-property :end element))))
  20357. (message "Block at point indented"))
  20358. ;;; Filling
  20359. ;; We use our own fill-paragraph and auto-fill functions.
  20360. ;; `org-fill-paragraph' relies on adaptive filling and context
  20361. ;; checking. Appropriate `fill-prefix' is computed with
  20362. ;; `org-adaptive-fill-function'.
  20363. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  20364. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  20365. ;; `org-adaptive-fill-function' value. Internally,
  20366. ;; `org-comment-line-break-function' breaks the line.
  20367. ;; `org-setup-filling' installs filling and auto-filling related
  20368. ;; variables during `org-mode' initialization.
  20369. (defun org-setup-filling ()
  20370. (require 'org-element)
  20371. ;; Prevent auto-fill from inserting unwanted new items.
  20372. (when (boundp 'fill-nobreak-predicate)
  20373. (setq-local
  20374. fill-nobreak-predicate
  20375. (org-uniquify
  20376. (append fill-nobreak-predicate
  20377. '(org-fill-line-break-nobreak-p
  20378. org-fill-n-macro-as-item-nobreak-p
  20379. org-fill-paragraph-with-timestamp-nobreak-p)))))
  20380. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  20381. (setq-local paragraph-start paragraph-ending)
  20382. (setq-local paragraph-separate paragraph-ending))
  20383. (setq-local fill-paragraph-function 'org-fill-paragraph)
  20384. (setq-local auto-fill-inhibit-regexp nil)
  20385. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  20386. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  20387. (setq-local comment-line-break-function 'org-comment-line-break-function))
  20388. (defun org-fill-line-break-nobreak-p ()
  20389. "Non-nil when a new line at point would create an Org line break."
  20390. (save-excursion
  20391. (skip-chars-backward "[ \t]")
  20392. (skip-chars-backward "\\\\")
  20393. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  20394. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  20395. "Non-nil when a new line at point would split a timestamp."
  20396. (and (org-at-timestamp-p 'lax)
  20397. (not (looking-at org-ts-regexp-both))))
  20398. (defun org-fill-n-macro-as-item-nobreak-p ()
  20399. "Non-nil when a new line at point would create a new list."
  20400. ;; During export, a "n" macro followed by a dot or a closing
  20401. ;; parenthesis can end up being parsed as a new list item.
  20402. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  20403. (declare-function message-in-body-p "message" ())
  20404. (defvar orgtbl-line-start-regexp) ; From org-table.el
  20405. (defun org-adaptive-fill-function ()
  20406. "Compute a fill prefix for the current line.
  20407. Return fill prefix, as a string, or nil if current line isn't
  20408. meant to be filled. For convenience, if `adaptive-fill-regexp'
  20409. matches in paragraphs or comments, use it."
  20410. (catch 'exit
  20411. (when (derived-mode-p 'message-mode)
  20412. (save-excursion
  20413. (beginning-of-line)
  20414. (cond ((not (message-in-body-p)) (throw 'exit nil))
  20415. ((looking-at-p org-table-line-regexp) (throw 'exit nil))
  20416. ((looking-at message-cite-prefix-regexp)
  20417. (throw 'exit (match-string-no-properties 0)))
  20418. ((looking-at org-outline-regexp)
  20419. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  20420. (org-with-wide-buffer
  20421. (unless (org-at-heading-p)
  20422. (let* ((p (line-beginning-position))
  20423. (element (save-excursion
  20424. (beginning-of-line)
  20425. (org-element-at-point)))
  20426. (type (org-element-type element))
  20427. (post-affiliated (org-element-property :post-affiliated element)))
  20428. (unless (< p post-affiliated)
  20429. (cl-case type
  20430. (comment
  20431. (save-excursion
  20432. (beginning-of-line)
  20433. (looking-at "[ \t]*")
  20434. (concat (match-string 0) "# ")))
  20435. (footnote-definition "")
  20436. ((item plain-list)
  20437. (make-string (org-list-item-body-column post-affiliated) ?\s))
  20438. (paragraph
  20439. ;; Fill prefix is usually the same as the current line,
  20440. ;; unless the paragraph is at the beginning of an item.
  20441. (let ((parent (org-element-property :parent element)))
  20442. (save-excursion
  20443. (beginning-of-line)
  20444. (cond ((eq (org-element-type parent) 'item)
  20445. (make-string (org-list-item-body-column
  20446. (org-element-property :begin parent))
  20447. ?\s))
  20448. ((and adaptive-fill-regexp
  20449. ;; Locally disable
  20450. ;; `adaptive-fill-function' to let
  20451. ;; `fill-context-prefix' handle
  20452. ;; `adaptive-fill-regexp' variable.
  20453. (let (adaptive-fill-function)
  20454. (fill-context-prefix
  20455. post-affiliated
  20456. (org-element-property :end element)))))
  20457. ((looking-at "[ \t]+") (match-string 0))
  20458. (t "")))))
  20459. (comment-block
  20460. ;; Only fill contents if P is within block boundaries.
  20461. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  20462. (forward-line)
  20463. (point)))
  20464. (cend (save-excursion
  20465. (goto-char (org-element-property :end element))
  20466. (skip-chars-backward " \r\t\n")
  20467. (line-beginning-position))))
  20468. (when (and (>= p cbeg) (< p cend))
  20469. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  20470. (match-string 0)
  20471. "")))))))))))
  20472. (declare-function message-goto-body "message" ())
  20473. (defvar message-cite-prefix-regexp) ; From message.el
  20474. (defun org-fill-element (&optional justify)
  20475. "Fill element at point, when applicable.
  20476. This function only applies to comment blocks, comments, example
  20477. blocks and paragraphs. Also, as a special case, re-align table
  20478. when point is at one.
  20479. If JUSTIFY is non-nil (interactively, with prefix argument),
  20480. justify as well. If `sentence-end-double-space' is non-nil, then
  20481. period followed by one space does not end a sentence, so don't
  20482. break a line there. The variable `fill-column' controls the
  20483. width for filling.
  20484. For convenience, when point is at a plain list, an item or
  20485. a footnote definition, try to fill the first paragraph within."
  20486. (with-syntax-table org-mode-transpose-word-syntax-table
  20487. ;; Move to end of line in order to get the first paragraph within
  20488. ;; a plain list or a footnote definition.
  20489. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  20490. ;; First check if point is in a blank line at the beginning of
  20491. ;; the buffer. In that case, ignore filling.
  20492. (cl-case (org-element-type element)
  20493. ;; Use major mode filling function is src blocks.
  20494. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  20495. ;; Align Org tables, leave table.el tables as-is.
  20496. (table-row (org-table-align) t)
  20497. (table
  20498. (when (eq (org-element-property :type element) 'org)
  20499. (save-excursion
  20500. (goto-char (org-element-property :post-affiliated element))
  20501. (org-table-align)))
  20502. t)
  20503. (paragraph
  20504. ;; Paragraphs may contain `line-break' type objects.
  20505. (let ((beg (max (point-min)
  20506. (org-element-property :contents-begin element)))
  20507. (end (min (point-max)
  20508. (org-element-property :contents-end element))))
  20509. ;; Do nothing if point is at an affiliated keyword.
  20510. (if (< (line-end-position) beg) t
  20511. (when (derived-mode-p 'message-mode)
  20512. ;; In `message-mode', do not fill following citation
  20513. ;; in current paragraph nor text before message body.
  20514. (let ((body-start (save-excursion (message-goto-body))))
  20515. (when body-start (setq beg (max body-start beg))))
  20516. (when (save-excursion
  20517. (re-search-forward
  20518. (concat "^" message-cite-prefix-regexp) end t))
  20519. (setq end (match-beginning 0))))
  20520. ;; Fill paragraph, taking line breaks into account.
  20521. (save-excursion
  20522. (goto-char beg)
  20523. (let ((cuts (list beg)))
  20524. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  20525. (when (eq 'line-break
  20526. (org-element-type
  20527. (save-excursion (backward-char)
  20528. (org-element-context))))
  20529. (push (point) cuts)))
  20530. (dolist (c (delq end cuts))
  20531. (fill-region-as-paragraph c end justify)
  20532. (setq end c))))
  20533. t)))
  20534. ;; Contents of `comment-block' type elements should be
  20535. ;; filled as plain text, but only if point is within block
  20536. ;; markers.
  20537. (comment-block
  20538. (let* ((case-fold-search t)
  20539. (beg (save-excursion
  20540. (goto-char (org-element-property :begin element))
  20541. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  20542. (forward-line)
  20543. (point)))
  20544. (end (save-excursion
  20545. (goto-char (org-element-property :end element))
  20546. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  20547. (line-beginning-position))))
  20548. (if (or (< (point) beg) (> (point) end)) t
  20549. (fill-region-as-paragraph
  20550. (save-excursion (end-of-line)
  20551. (re-search-backward "^[ \t]*$" beg 'move)
  20552. (line-beginning-position))
  20553. (save-excursion (beginning-of-line)
  20554. (re-search-forward "^[ \t]*$" end 'move)
  20555. (line-beginning-position))
  20556. justify))))
  20557. ;; Fill comments.
  20558. (comment
  20559. (let ((begin (org-element-property :post-affiliated element))
  20560. (end (org-element-property :end element)))
  20561. (when (and (>= (point) begin) (<= (point) end))
  20562. (let ((begin (save-excursion
  20563. (end-of-line)
  20564. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  20565. (progn (forward-line) (point))
  20566. begin)))
  20567. (end (save-excursion
  20568. (end-of-line)
  20569. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  20570. (1- (line-beginning-position))
  20571. (skip-chars-backward " \r\t\n")
  20572. (line-end-position)))))
  20573. ;; Do not fill comments when at a blank line.
  20574. (when (> end begin)
  20575. (let ((fill-prefix
  20576. (save-excursion
  20577. (beginning-of-line)
  20578. (looking-at "[ \t]*#")
  20579. (let ((comment-prefix (match-string 0)))
  20580. (goto-char (match-end 0))
  20581. (if (looking-at adaptive-fill-regexp)
  20582. (concat comment-prefix (match-string 0))
  20583. (concat comment-prefix " "))))))
  20584. (save-excursion
  20585. (fill-region-as-paragraph begin end justify))))))
  20586. t))
  20587. ;; Ignore every other element.
  20588. (otherwise t)))))
  20589. (defun org-fill-paragraph (&optional justify region)
  20590. "Fill element at point, when applicable.
  20591. This function only applies to comment blocks, comments, example
  20592. blocks and paragraphs. Also, as a special case, re-align table
  20593. when point is at one.
  20594. For convenience, when point is at a plain list, an item or
  20595. a footnote definition, try to fill the first paragraph within.
  20596. If JUSTIFY is non-nil (interactively, with prefix argument),
  20597. justify as well. If `sentence-end-double-space' is non-nil, then
  20598. period followed by one space does not end a sentence, so don't
  20599. break a line there. The variable `fill-column' controls the
  20600. width for filling.
  20601. The REGION argument is non-nil if called interactively; in that
  20602. case, if Transient Mark mode is enabled and the mark is active,
  20603. fill each of the elements in the active region, instead of just
  20604. filling the current element."
  20605. (interactive (progn
  20606. (barf-if-buffer-read-only)
  20607. (list (if current-prefix-arg 'full) t)))
  20608. (cond
  20609. ((and (derived-mode-p 'message-mode)
  20610. (or (not (message-in-body-p))
  20611. (save-excursion (move-beginning-of-line 1)
  20612. (looking-at message-cite-prefix-regexp))))
  20613. ;; First ensure filling is correct in message-mode.
  20614. (let ((fill-paragraph-function
  20615. (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
  20616. (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
  20617. (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
  20618. (paragraph-separate
  20619. (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
  20620. (fill-paragraph nil)))
  20621. ((and region transient-mark-mode mark-active
  20622. (not (eq (region-beginning) (region-end))))
  20623. (let ((origin (point-marker))
  20624. (start (region-beginning)))
  20625. (unwind-protect
  20626. (progn
  20627. (goto-char (region-end))
  20628. (while (> (point) start)
  20629. (org-backward-paragraph)
  20630. (org-fill-element justify)))
  20631. (goto-char origin)
  20632. (set-marker origin nil))))
  20633. (t (org-fill-element justify))))
  20634. (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
  20635. (defun org-auto-fill-function ()
  20636. "Auto-fill function."
  20637. ;; Check if auto-filling is meaningful.
  20638. (let ((fc (current-fill-column)))
  20639. (when (and fc (> (current-column) fc))
  20640. (let* ((fill-prefix (org-adaptive-fill-function))
  20641. ;; Enforce empty fill prefix, if required. Otherwise, it
  20642. ;; will be computed again.
  20643. (adaptive-fill-mode (not (equal fill-prefix ""))))
  20644. (when fill-prefix (do-auto-fill))))))
  20645. (defun org-comment-line-break-function (&optional soft)
  20646. "Break line at point and indent, continuing comment if within one.
  20647. The inserted newline is marked hard if variable
  20648. `use-hard-newlines' is true, unless optional argument SOFT is
  20649. non-nil."
  20650. (if soft (insert-and-inherit ?\n) (newline 1))
  20651. (save-excursion (forward-char -1) (delete-horizontal-space))
  20652. (delete-horizontal-space)
  20653. (indent-to-left-margin)
  20654. (insert-before-markers-and-inherit fill-prefix))
  20655. ;;; Fixed Width Areas
  20656. (defun org-toggle-fixed-width ()
  20657. "Toggle fixed-width markup.
  20658. Add or remove fixed-width markup on current line, whenever it
  20659. makes sense. Return an error otherwise.
  20660. If a region is active and if it contains only fixed-width areas
  20661. or blank lines, remove all fixed-width markup in it. If the
  20662. region contains anything else, convert all non-fixed-width lines
  20663. to fixed-width ones.
  20664. Blank lines at the end of the region are ignored unless the
  20665. region only contains such lines."
  20666. (interactive)
  20667. (if (not (org-region-active-p))
  20668. ;; No region:
  20669. ;;
  20670. ;; Remove fixed width marker only in a fixed-with element.
  20671. ;;
  20672. ;; Add fixed width maker in paragraphs, in blank lines after
  20673. ;; elements or at the beginning of a headline or an inlinetask,
  20674. ;; and before any one-line elements (e.g., a clock).
  20675. (progn
  20676. (beginning-of-line)
  20677. (let* ((element (org-element-at-point))
  20678. (type (org-element-type element)))
  20679. (cond
  20680. ((and (eq type 'fixed-width)
  20681. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  20682. (replace-match
  20683. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  20684. ((and (memq type '(babel-call clock comment diary-sexp headline
  20685. horizontal-rule keyword paragraph
  20686. planning))
  20687. (<= (org-element-property :post-affiliated element) (point)))
  20688. (skip-chars-forward " \t")
  20689. (insert ": "))
  20690. ((and (looking-at-p "[ \t]*$")
  20691. (or (eq type 'inlinetask)
  20692. (save-excursion
  20693. (skip-chars-forward " \r\t\n")
  20694. (<= (org-element-property :end element) (point)))))
  20695. (delete-region (point) (line-end-position))
  20696. (org-indent-line)
  20697. (insert ": "))
  20698. (t (user-error "Cannot insert a fixed-width line here")))))
  20699. ;; Region active.
  20700. (let* ((begin (save-excursion
  20701. (goto-char (region-beginning))
  20702. (line-beginning-position)))
  20703. (end (copy-marker
  20704. (save-excursion
  20705. (goto-char (region-end))
  20706. (unless (eolp) (beginning-of-line))
  20707. (if (save-excursion (re-search-backward "\\S-" begin t))
  20708. (progn (skip-chars-backward " \r\t\n") (point))
  20709. (point)))))
  20710. (all-fixed-width-p
  20711. (catch 'not-all-p
  20712. (save-excursion
  20713. (goto-char begin)
  20714. (skip-chars-forward " \r\t\n")
  20715. (when (eobp) (throw 'not-all-p nil))
  20716. (while (< (point) end)
  20717. (let ((element (org-element-at-point)))
  20718. (if (eq (org-element-type element) 'fixed-width)
  20719. (goto-char (org-element-property :end element))
  20720. (throw 'not-all-p nil))))
  20721. t))))
  20722. (if all-fixed-width-p
  20723. (save-excursion
  20724. (goto-char begin)
  20725. (while (< (point) end)
  20726. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  20727. (replace-match
  20728. "" nil nil nil
  20729. (if (= (line-end-position) (match-end 0)) 0 1)))
  20730. (forward-line)))
  20731. (let ((min-ind (point-max)))
  20732. ;; Find minimum indentation across all lines.
  20733. (save-excursion
  20734. (goto-char begin)
  20735. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  20736. (setq min-ind 0)
  20737. (catch 'zerop
  20738. (while (< (point) end)
  20739. (unless (looking-at-p "[ \t]*$")
  20740. (let ((ind (org-get-indentation)))
  20741. (setq min-ind (min min-ind ind))
  20742. (when (zerop ind) (throw 'zerop t))))
  20743. (forward-line)))))
  20744. ;; Loop over all lines and add fixed-width markup everywhere
  20745. ;; but in fixed-width lines.
  20746. (save-excursion
  20747. (goto-char begin)
  20748. (while (< (point) end)
  20749. (cond
  20750. ((org-at-heading-p)
  20751. (insert ": ")
  20752. (forward-line)
  20753. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  20754. (insert ":")
  20755. (forward-line)))
  20756. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  20757. (let* ((element (org-element-at-point))
  20758. (element-end (org-element-property :end element)))
  20759. (if (eq (org-element-type element) 'fixed-width)
  20760. (progn (goto-char element-end)
  20761. (skip-chars-backward " \r\t\n")
  20762. (forward-line))
  20763. (let ((limit (min end element-end)))
  20764. (while (< (point) limit)
  20765. (org-move-to-column min-ind t)
  20766. (insert ": ")
  20767. (forward-line))))))
  20768. (t
  20769. (org-move-to-column min-ind t)
  20770. (insert ": ")
  20771. (forward-line)))))))
  20772. (set-marker end nil))))
  20773. ;;; Comments
  20774. ;; Org comments syntax is quite complex. It requires the entire line
  20775. ;; to be just a comment. Also, even with the right syntax at the
  20776. ;; beginning of line, some elements (e.g., verse-block or
  20777. ;; example-block) don't accept comments. Usual Emacs comment commands
  20778. ;; cannot cope with those requirements. Therefore, Org replaces them.
  20779. ;; Org still relies on `comment-dwim', but cannot trust
  20780. ;; `comment-only-p'. So, `comment-region-function' and
  20781. ;; `uncomment-region-function' both point
  20782. ;; to`org-comment-or-uncomment-region'. Eventually,
  20783. ;; `org-insert-comment' takes care of insertion of comments at the
  20784. ;; beginning of line.
  20785. ;; `org-setup-comments-handling' install comments related variables
  20786. ;; during `org-mode' initialization.
  20787. (defun org-setup-comments-handling ()
  20788. (interactive)
  20789. (setq-local comment-use-syntax nil)
  20790. (setq-local comment-start "# ")
  20791. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  20792. (setq-local comment-insert-comment-function 'org-insert-comment)
  20793. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  20794. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  20795. (defun org-insert-comment ()
  20796. "Insert an empty comment above current line.
  20797. If the line is empty, insert comment at its beginning. When
  20798. point is within a source block, comment according to the related
  20799. major mode."
  20800. (if (let ((element (org-element-at-point)))
  20801. (and (eq (org-element-type element) 'src-block)
  20802. (< (save-excursion
  20803. (goto-char (org-element-property :post-affiliated element))
  20804. (line-end-position))
  20805. (point))
  20806. (> (save-excursion
  20807. (goto-char (org-element-property :end element))
  20808. (skip-chars-backward " \r\t\n")
  20809. (line-beginning-position))
  20810. (point))))
  20811. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  20812. (beginning-of-line)
  20813. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  20814. (open-line 1))
  20815. (org-indent-line)
  20816. (insert "# ")))
  20817. (defvar comment-empty-lines) ; From newcomment.el.
  20818. (defun org-comment-or-uncomment-region (beg end &rest _)
  20819. "Comment or uncomment each non-blank line in the region.
  20820. Uncomment each non-blank line between BEG and END if it only
  20821. contains commented lines. Otherwise, comment them. If region is
  20822. strictly within a source block, use appropriate comment syntax."
  20823. (if (let ((element (org-element-at-point)))
  20824. (and (eq (org-element-type element) 'src-block)
  20825. (< (save-excursion
  20826. (goto-char (org-element-property :post-affiliated element))
  20827. (line-end-position))
  20828. beg)
  20829. (>= (save-excursion
  20830. (goto-char (org-element-property :end element))
  20831. (skip-chars-backward " \r\t\n")
  20832. (line-beginning-position))
  20833. end)))
  20834. ;; Translate region boundaries for the Org buffer to the source
  20835. ;; buffer.
  20836. (let ((offset (- end beg)))
  20837. (save-excursion
  20838. (goto-char beg)
  20839. (org-babel-do-in-edit-buffer
  20840. (comment-or-uncomment-region (point) (+ offset (point))))))
  20841. (save-restriction
  20842. ;; Restrict region
  20843. (narrow-to-region (save-excursion (goto-char beg)
  20844. (skip-chars-forward " \r\t\n" end)
  20845. (line-beginning-position))
  20846. (save-excursion (goto-char end)
  20847. (skip-chars-backward " \r\t\n" beg)
  20848. (line-end-position)))
  20849. (let ((uncommentp
  20850. ;; UNCOMMENTP is non-nil when every non blank line between
  20851. ;; BEG and END is a comment.
  20852. (save-excursion
  20853. (goto-char (point-min))
  20854. (while (and (not (eobp))
  20855. (let ((element (org-element-at-point)))
  20856. (and (eq (org-element-type element) 'comment)
  20857. (goto-char (min (point-max)
  20858. (org-element-property
  20859. :end element)))))))
  20860. (eobp))))
  20861. (if uncommentp
  20862. ;; Only blank lines and comments in region: uncomment it.
  20863. (save-excursion
  20864. (goto-char (point-min))
  20865. (while (not (eobp))
  20866. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  20867. (replace-match "" nil nil nil 1))
  20868. (forward-line)))
  20869. ;; Comment each line in region.
  20870. (let ((min-indent (point-max)))
  20871. ;; First find the minimum indentation across all lines.
  20872. (save-excursion
  20873. (goto-char (point-min))
  20874. (while (and (not (eobp)) (not (zerop min-indent)))
  20875. (unless (looking-at "[ \t]*$")
  20876. (setq min-indent (min min-indent (current-indentation))))
  20877. (forward-line)))
  20878. ;; Then loop over all lines.
  20879. (save-excursion
  20880. (goto-char (point-min))
  20881. (while (not (eobp))
  20882. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  20883. ;; Don't get fooled by invisible text (e.g. link path)
  20884. ;; when moving to column MIN-INDENT.
  20885. (let ((buffer-invisibility-spec nil))
  20886. (org-move-to-column min-indent t))
  20887. (insert comment-start))
  20888. (forward-line)))))))))
  20889. (defun org-comment-dwim (_arg)
  20890. "Call `comment-dwim' within a source edit buffer if needed."
  20891. (interactive "*P")
  20892. (if (org-in-src-block-p)
  20893. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  20894. (call-interactively 'comment-dwim)))
  20895. ;;; Timestamps API
  20896. ;; This section contains tools to operate on timestamp objects, as
  20897. ;; returned by, e.g. `org-element-context'.
  20898. (defun org-timestamp--to-internal-time (timestamp &optional end)
  20899. "Encode TIMESTAMP object into Emacs internal time.
  20900. Use end of date range or time range when END is non-nil."
  20901. (apply #'encode-time
  20902. (cons 0
  20903. (mapcar
  20904. (lambda (prop) (or (org-element-property prop timestamp) 0))
  20905. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  20906. '(:minute-start :hour-start :day-start :month-start
  20907. :year-start))))))
  20908. (defun org-timestamp-has-time-p (timestamp)
  20909. "Non-nil when TIMESTAMP has a time specified."
  20910. (org-element-property :hour-start timestamp))
  20911. (defun org-timestamp-format (timestamp format &optional end utc)
  20912. "Format a TIMESTAMP object into a string.
  20913. FORMAT is a format specifier to be passed to
  20914. `format-time-string'.
  20915. When optional argument END is non-nil, use end of date-range or
  20916. time-range, if possible.
  20917. When optional argument UTC is non-nil, time will be expressed as
  20918. Universal Time."
  20919. (format-time-string
  20920. format (org-timestamp--to-internal-time timestamp end)
  20921. (and utc t)))
  20922. (defun org-timestamp-split-range (timestamp &optional end)
  20923. "Extract a TIMESTAMP object from a date or time range.
  20924. END, when non-nil, means extract the end of the range.
  20925. Otherwise, extract its start.
  20926. Return a new timestamp object."
  20927. (let ((type (org-element-property :type timestamp)))
  20928. (if (memq type '(active inactive diary)) timestamp
  20929. (let ((split-ts (org-element-copy timestamp)))
  20930. ;; Set new type.
  20931. (org-element-put-property
  20932. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  20933. ;; Copy start properties over end properties if END is
  20934. ;; non-nil. Otherwise, copy end properties over `start' ones.
  20935. (let ((p-alist '((:minute-start . :minute-end)
  20936. (:hour-start . :hour-end)
  20937. (:day-start . :day-end)
  20938. (:month-start . :month-end)
  20939. (:year-start . :year-end))))
  20940. (dolist (p-cell p-alist)
  20941. (org-element-put-property
  20942. split-ts
  20943. (funcall (if end #'car #'cdr) p-cell)
  20944. (org-element-property
  20945. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  20946. ;; Eventually refresh `:raw-value'.
  20947. (org-element-put-property split-ts :raw-value nil)
  20948. (org-element-put-property
  20949. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  20950. (defun org-timestamp-translate (timestamp &optional boundary)
  20951. "Translate TIMESTAMP object to custom format.
  20952. Format string is defined in `org-time-stamp-custom-formats',
  20953. which see.
  20954. When optional argument BOUNDARY is non-nil, it is either the
  20955. symbol `start' or `end'. In this case, only translate the
  20956. starting or ending part of TIMESTAMP if it is a date or time
  20957. range. Otherwise, translate both parts.
  20958. Return timestamp as-is if `org-display-custom-times' is nil or if
  20959. it has a `diary' type."
  20960. (let ((type (org-element-property :type timestamp)))
  20961. (if (or (not org-display-custom-times) (eq type 'diary))
  20962. (org-element-interpret-data timestamp)
  20963. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  20964. org-time-stamp-custom-formats)))
  20965. (if (and (not boundary) (memq type '(active-range inactive-range)))
  20966. (concat (org-timestamp-format timestamp fmt)
  20967. "--"
  20968. (org-timestamp-format timestamp fmt t))
  20969. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  20970. ;;; Other stuff.
  20971. (defvar reftex-docstruct-symbol)
  20972. (defvar org--rds)
  20973. (defun org-reftex-citation ()
  20974. "Use reftex-citation to insert a citation into the buffer.
  20975. This looks for a line like
  20976. #+BIBLIOGRAPHY: foo plain option:-d
  20977. and derives from it that foo.bib is the bibliography file relevant
  20978. for this document. It then installs the necessary environment for RefTeX
  20979. to work in this buffer and calls `reftex-citation' to insert a citation
  20980. into the buffer.
  20981. Export of such citations to both LaTeX and HTML is handled by the contributed
  20982. package ox-bibtex by Taru Karttunen."
  20983. (interactive)
  20984. (let ((reftex-docstruct-symbol 'org--rds)
  20985. org--rds bib)
  20986. (org-with-wide-buffer
  20987. (let ((case-fold-search t)
  20988. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  20989. (if (not (save-excursion
  20990. (or (re-search-forward re nil t)
  20991. (re-search-backward re nil t))))
  20992. (user-error "No bibliography defined in file")
  20993. (setq bib (concat (match-string 1) ".bib")
  20994. org--rds (list (list 'bib bib))))))
  20995. (call-interactively 'reftex-citation)))
  20996. ;;;; Functions extending outline functionality
  20997. (defun org-beginning-of-line (&optional n)
  20998. "Go to the beginning of the current visible line.
  20999. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21000. tags on the first attempt, and only move to after the tags when
  21001. the cursor is already beyond the end of the headline.
  21002. With argument N not nil or 1, move forward N - 1 lines first."
  21003. (interactive "^p")
  21004. (let ((origin (point))
  21005. (special (pcase org-special-ctrl-a/e
  21006. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  21007. deactivate-mark)
  21008. ;; First move to a visible line.
  21009. (if (bound-and-true-p visual-line-mode)
  21010. (beginning-of-visual-line n)
  21011. (move-beginning-of-line n)
  21012. ;; `move-beginning-of-line' may leave point after invisible
  21013. ;; characters if line starts with such of these (e.g., with
  21014. ;; a link at column 0). Really move to the beginning of the
  21015. ;; current visible line.
  21016. (beginning-of-line))
  21017. (cond
  21018. ;; No special behavior. Point is already at the beginning of
  21019. ;; a line, logical or visual.
  21020. ((not special))
  21021. ;; `beginning-of-visual-line' left point before logical beginning
  21022. ;; of line: point is at the beginning of a visual line. Bail
  21023. ;; out.
  21024. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  21025. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  21026. ;; At a headline, special position is before the title, but
  21027. ;; after any TODO keyword or priority cookie.
  21028. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21029. (line-end-position)))
  21030. (bol (point)))
  21031. (if (eq special 'reversed)
  21032. (when (and (= origin bol) (eq last-command this-command))
  21033. (goto-char refpos))
  21034. (when (or (> origin refpos) (= origin bol))
  21035. (goto-char refpos)))))
  21036. ((and (looking-at org-list-full-item-re)
  21037. (memq (org-element-type (save-match-data (org-element-at-point)))
  21038. '(item plain-list)))
  21039. ;; Set special position at first white space character after
  21040. ;; bullet, and check-box, if any.
  21041. (let ((after-bullet
  21042. (let ((box (match-end 3)))
  21043. (cond ((not box) (match-end 1))
  21044. ((eq (char-after box) ?\s) (1+ box))
  21045. (t box)))))
  21046. (if (eq special 'reversed)
  21047. (when (and (= (point) origin) (eq last-command this-command))
  21048. (goto-char after-bullet))
  21049. (when (or (> origin after-bullet) (= (point) origin))
  21050. (goto-char after-bullet)))))
  21051. ;; No special context. Point is already at beginning of line.
  21052. (t nil))))
  21053. (defun org-end-of-line (&optional n)
  21054. "Go to the end of the line, but before ellipsis, if any.
  21055. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21056. tags on the first attempt, and only move to after the tags when
  21057. the cursor is already beyond the end of the headline.
  21058. With argument N not nil or 1, move forward N - 1 lines first."
  21059. (interactive "^p")
  21060. (let ((origin (point))
  21061. (special (pcase org-special-ctrl-a/e
  21062. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  21063. deactivate-mark)
  21064. ;; First move to a visible line.
  21065. (if (bound-and-true-p visual-line-mode)
  21066. (beginning-of-visual-line n)
  21067. (move-beginning-of-line n))
  21068. (cond
  21069. ;; At a headline, with tags.
  21070. ((and special
  21071. (save-excursion
  21072. (beginning-of-line)
  21073. (let ((case-fold-search nil))
  21074. (looking-at org-complex-heading-regexp)))
  21075. (match-end 5))
  21076. (let ((tags (save-excursion
  21077. (goto-char (match-beginning 5))
  21078. (skip-chars-backward " \t")
  21079. (point)))
  21080. (visual-end (and (bound-and-true-p visual-line-mode)
  21081. (save-excursion
  21082. (end-of-visual-line)
  21083. (point)))))
  21084. ;; If `end-of-visual-line' brings us before end of line or
  21085. ;; even tags, i.e., the headline spans over multiple visual
  21086. ;; lines, move there.
  21087. (cond ((and visual-end
  21088. (< visual-end tags)
  21089. (<= origin visual-end))
  21090. (goto-char visual-end))
  21091. ((eq special 'reversed)
  21092. (if (and (= origin (line-end-position))
  21093. (eq this-command last-command))
  21094. (goto-char tags)
  21095. (end-of-line)))
  21096. (t
  21097. (if (or (< origin tags) (= origin (line-end-position)))
  21098. (goto-char tags)
  21099. (end-of-line))))))
  21100. ((bound-and-true-p visual-line-mode)
  21101. (let ((bol (line-beginning-position)))
  21102. (end-of-visual-line)
  21103. ;; If `end-of-visual-line' gets us past the ellipsis at the
  21104. ;; end of a line, backtrack and use `end-of-line' instead.
  21105. (when (/= bol (line-beginning-position))
  21106. (goto-char bol)
  21107. (end-of-line))))
  21108. (t (end-of-line)))))
  21109. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21110. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21111. (defun org-backward-sentence (&optional _arg)
  21112. "Go to beginning of sentence, or beginning of table field.
  21113. This will call `backward-sentence' or `org-table-beginning-of-field',
  21114. depending on context."
  21115. (interactive)
  21116. (let* ((element (org-element-at-point))
  21117. (contents-begin (org-element-property :contents-begin element))
  21118. (table (org-element-lineage element '(table) t)))
  21119. (if (and table
  21120. (> (point) contents-begin)
  21121. (<= (point) (org-element-property :contents-end table)))
  21122. (call-interactively #'org-table-beginning-of-field)
  21123. (save-restriction
  21124. (when (and contents-begin
  21125. (< (point-min) contents-begin)
  21126. (> (point) contents-begin))
  21127. (narrow-to-region contents-begin
  21128. (org-element-property :contents-end element)))
  21129. (call-interactively #'backward-sentence)))))
  21130. (defun org-forward-sentence (&optional _arg)
  21131. "Go to end of sentence, or end of table field.
  21132. This will call `forward-sentence' or `org-table-end-of-field',
  21133. depending on context."
  21134. (interactive)
  21135. (if (and (org-at-heading-p)
  21136. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  21137. (save-restriction
  21138. (narrow-to-region (line-beginning-position) (line-end-position))
  21139. (call-interactively #'forward-sentence))
  21140. (let* ((element (org-element-at-point))
  21141. (contents-end (org-element-property :contents-end element))
  21142. (table (org-element-lineage element '(table) t)))
  21143. (if (and table
  21144. (>= (point) (org-element-property :contents-begin table))
  21145. (< (point) contents-end))
  21146. (call-interactively #'org-table-end-of-field)
  21147. (save-restriction
  21148. (when (and contents-end
  21149. (> (point-max) contents-end)
  21150. ;; Skip blank lines between elements.
  21151. (< (org-element-property :end element)
  21152. (save-excursion (goto-char contents-end)
  21153. (skip-chars-forward " \r\t\n"))))
  21154. (narrow-to-region (org-element-property :contents-begin element)
  21155. contents-end))
  21156. ;; End of heading is considered as the end of a sentence.
  21157. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  21158. (call-interactively #'forward-sentence)))))))
  21159. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21160. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21161. (defun org-kill-line (&optional _arg)
  21162. "Kill line, to tags or end of line."
  21163. (interactive)
  21164. (cond
  21165. ((or (not org-special-ctrl-k)
  21166. (bolp)
  21167. (not (org-at-heading-p)))
  21168. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  21169. org-ctrl-k-protect-subtree
  21170. (or (eq org-ctrl-k-protect-subtree 'error)
  21171. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21172. (user-error "C-k aborted as it would kill a hidden subtree"))
  21173. (call-interactively
  21174. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21175. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  21176. (kill-region (point) (match-beginning 1))
  21177. (org-set-tags nil t))
  21178. (t (kill-region (point) (point-at-eol)))))
  21179. (define-key org-mode-map "\C-k" 'org-kill-line)
  21180. (defun org-yank (&optional arg)
  21181. "Yank. If the kill is a subtree, treat it specially.
  21182. This command will look at the current kill and check if is a single
  21183. subtree, or a series of subtrees[1]. If it passes the test, and if the
  21184. cursor is at the beginning of a line or after the stars of a currently
  21185. empty headline, then the yank is handled specially. How exactly depends
  21186. on the value of the following variables.
  21187. `org-yank-folded-subtrees'
  21188. By default, this variable is non-nil, which results in
  21189. subtree(s) being folded after insertion, except if doing so
  21190. would swallow text after the yanked text.
  21191. `org-yank-adjusted-subtrees'
  21192. When non-nil (the default value is nil), the subtree will be
  21193. promoted or demoted in order to fit into the local outline tree
  21194. structure, which means that the level will be adjusted so that it
  21195. becomes the smaller one of the two *visible* surrounding headings.
  21196. Any prefix to this command will cause `yank' to be called directly with
  21197. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  21198. will just
  21199. plainly yank the text as it is.
  21200. \[1] The test checks if the first non-white line is a heading
  21201. and if there are no other headings with fewer stars."
  21202. (interactive "P")
  21203. (org-yank-generic 'yank arg))
  21204. (defun org-yank-generic (command arg)
  21205. "Perform some yank-like command.
  21206. This function implements the behavior described in the `org-yank'
  21207. documentation. However, it has been generalized to work for any
  21208. interactive command with similar behavior."
  21209. ;; pretend to be command COMMAND
  21210. (setq this-command command)
  21211. (if arg
  21212. (call-interactively command)
  21213. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  21214. (and (org-kill-is-subtree-p)
  21215. (or (bolp)
  21216. (and (looking-at "[ \t]*$")
  21217. (string-match
  21218. "\\`\\*+\\'"
  21219. (buffer-substring (point-at-bol) (point)))))))
  21220. swallowp)
  21221. (cond
  21222. ((and subtreep org-yank-folded-subtrees)
  21223. (let ((beg (point))
  21224. end)
  21225. (if (and subtreep org-yank-adjusted-subtrees)
  21226. (org-paste-subtree nil nil 'for-yank)
  21227. (call-interactively command))
  21228. (setq end (point))
  21229. (goto-char beg)
  21230. (when (and (bolp) subtreep
  21231. (not (setq swallowp
  21232. (org-yank-folding-would-swallow-text beg end))))
  21233. (org-with-limited-levels
  21234. (or (looking-at org-outline-regexp)
  21235. (re-search-forward org-outline-regexp-bol end t))
  21236. (while (and (< (point) end) (looking-at org-outline-regexp))
  21237. (outline-hide-subtree)
  21238. (org-cycle-show-empty-lines 'folded)
  21239. (condition-case nil
  21240. (outline-forward-same-level 1)
  21241. (error (goto-char end))))))
  21242. (when swallowp
  21243. (message
  21244. "Inserted text not folded because that would swallow text"))
  21245. (goto-char end)
  21246. (skip-chars-forward " \t\n\r")
  21247. (beginning-of-line 1)
  21248. (push-mark beg 'nomsg)))
  21249. ((and subtreep org-yank-adjusted-subtrees)
  21250. (let ((beg (point-at-bol)))
  21251. (org-paste-subtree nil nil 'for-yank)
  21252. (push-mark beg 'nomsg)))
  21253. (t
  21254. (call-interactively command))))))
  21255. (defun org-yank-folding-would-swallow-text (beg end)
  21256. "Would hide-subtree at BEG swallow any text after END?"
  21257. (let (level)
  21258. (org-with-limited-levels
  21259. (save-excursion
  21260. (goto-char beg)
  21261. (when (or (looking-at org-outline-regexp)
  21262. (re-search-forward org-outline-regexp-bol end t))
  21263. (setq level (org-outline-level)))
  21264. (goto-char end)
  21265. (skip-chars-forward " \t\r\n\v\f")
  21266. (not (or (eobp)
  21267. (and (bolp) (looking-at-p org-outline-regexp)
  21268. (<= (org-outline-level) level))))))))
  21269. (define-key org-mode-map "\C-y" 'org-yank)
  21270. (defun org-back-to-heading (&optional invisible-ok)
  21271. "Call `outline-back-to-heading', but provide a better error message."
  21272. (condition-case nil
  21273. (outline-back-to-heading invisible-ok)
  21274. (error (error "Before first headline at position %d in buffer %s"
  21275. (point) (current-buffer)))))
  21276. (defun org-before-first-heading-p ()
  21277. "Before first heading?"
  21278. (save-excursion
  21279. (end-of-line)
  21280. (null (re-search-backward org-outline-regexp-bol nil t))))
  21281. (defun org-at-heading-p (&optional ignored)
  21282. (outline-on-heading-p t))
  21283. (defun org-in-commented-heading-p (&optional no-inheritance)
  21284. "Non-nil if point is under a commented heading.
  21285. This function also checks ancestors of the current headline,
  21286. unless optional argument NO-INHERITANCE is non-nil."
  21287. (cond
  21288. ((org-before-first-heading-p) nil)
  21289. ((let ((headline (nth 4 (org-heading-components))))
  21290. (and headline
  21291. (let ((case-fold-search nil))
  21292. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  21293. headline)))))
  21294. (no-inheritance nil)
  21295. (t
  21296. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  21297. (defun org-at-comment-p nil
  21298. "Is cursor in a commented line?"
  21299. (save-excursion
  21300. (save-match-data
  21301. (beginning-of-line)
  21302. (looking-at "^[ \t]*# "))))
  21303. (defun org-at-drawer-p nil
  21304. "Is cursor at a drawer keyword?"
  21305. (save-excursion
  21306. (move-beginning-of-line 1)
  21307. (looking-at org-drawer-regexp)))
  21308. (defun org-at-block-p nil
  21309. "Is cursor at a block keyword?"
  21310. (save-excursion
  21311. (move-beginning-of-line 1)
  21312. (looking-at org-block-regexp)))
  21313. (defun org-point-at-end-of-empty-headline ()
  21314. "If point is at the end of an empty headline, return t, else nil.
  21315. If the heading only contains a TODO keyword, it is still still considered
  21316. empty."
  21317. (let ((case-fold-search nil))
  21318. (and (looking-at "[ \t]*$")
  21319. org-todo-line-regexp
  21320. (save-excursion
  21321. (beginning-of-line)
  21322. (looking-at org-todo-line-regexp)
  21323. (string= (match-string 3) "")))))
  21324. (defun org-at-heading-or-item-p ()
  21325. (or (org-at-heading-p) (org-at-item-p)))
  21326. (defun org-at-target-p ()
  21327. (or (org-in-regexp org-radio-target-regexp)
  21328. (org-in-regexp org-target-regexp)))
  21329. ;; Compatibility alias with Org versions < 7.8.03
  21330. (defalias 'org-on-target-p 'org-at-target-p)
  21331. (defun org-up-heading-all (arg)
  21332. "Move to the heading line of which the present line is a subheading.
  21333. This function considers both visible and invisible heading lines.
  21334. With argument, move up ARG levels."
  21335. (outline-up-heading arg t))
  21336. (defun org-up-heading-safe ()
  21337. "Move to the heading line of which the present line is a subheading.
  21338. This version will not throw an error. It will return the level of the
  21339. headline found, or nil if no higher level is found.
  21340. Also, this function will be a lot faster than `outline-up-heading',
  21341. because it relies on stars being the outline starters. This can really
  21342. make a significant difference in outlines with very many siblings."
  21343. (when (ignore-errors (org-back-to-heading t))
  21344. (let ((level-up (1- (funcall outline-level))))
  21345. (and (> level-up 0)
  21346. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  21347. (funcall outline-level)))))
  21348. (defun org-first-sibling-p ()
  21349. "Is this heading the first child of its parents?"
  21350. (interactive)
  21351. (let ((re org-outline-regexp-bol)
  21352. level l)
  21353. (unless (org-at-heading-p t)
  21354. (user-error "Not at a heading"))
  21355. (setq level (funcall outline-level))
  21356. (save-excursion
  21357. (if (not (re-search-backward re nil t))
  21358. t
  21359. (setq l (funcall outline-level))
  21360. (< l level)))))
  21361. (defun org-goto-sibling (&optional previous)
  21362. "Goto the next sibling, even if it is invisible.
  21363. When PREVIOUS is set, go to the previous sibling instead. Returns t
  21364. when a sibling was found. When none is found, return nil and don't
  21365. move point."
  21366. (let ((fun (if previous 're-search-backward 're-search-forward))
  21367. (pos (point))
  21368. (re org-outline-regexp-bol)
  21369. level l)
  21370. (when (ignore-errors (org-back-to-heading t))
  21371. (setq level (funcall outline-level))
  21372. (catch 'exit
  21373. (or previous (forward-char 1))
  21374. (while (funcall fun re nil t)
  21375. (setq l (funcall outline-level))
  21376. (when (< l level) (goto-char pos) (throw 'exit nil))
  21377. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21378. (goto-char pos)
  21379. nil))))
  21380. (defun org-show-siblings ()
  21381. "Show all siblings of the current headline."
  21382. (save-excursion
  21383. (while (org-goto-sibling) (org-flag-heading nil)))
  21384. (save-excursion
  21385. (while (org-goto-sibling 'previous)
  21386. (org-flag-heading nil))))
  21387. (defun org-goto-first-child ()
  21388. "Goto the first child, even if it is invisible.
  21389. Return t when a child was found. Otherwise don't move point and
  21390. return nil."
  21391. (let (level (pos (point)) (re org-outline-regexp-bol))
  21392. (when (ignore-errors (org-back-to-heading t))
  21393. (setq level (outline-level))
  21394. (forward-char 1)
  21395. (if (and (re-search-forward re nil t) (> (outline-level) level))
  21396. (progn (goto-char (match-beginning 0)) t)
  21397. (goto-char pos) nil))))
  21398. (defun org-show-hidden-entry ()
  21399. "Show an entry where even the heading is hidden."
  21400. (save-excursion
  21401. (org-show-entry)))
  21402. (defun org-flag-heading (flag &optional entry)
  21403. "Flag the current heading. FLAG non-nil means make invisible.
  21404. When ENTRY is non-nil, show the entire entry."
  21405. (save-excursion
  21406. (org-back-to-heading t)
  21407. ;; Check if we should show the entire entry
  21408. (if entry
  21409. (progn
  21410. (org-show-entry)
  21411. (save-excursion
  21412. (and (outline-next-heading)
  21413. (org-flag-heading nil))))
  21414. (outline-flag-region (max (point-min) (1- (point)))
  21415. (save-excursion (outline-end-of-heading) (point))
  21416. flag))))
  21417. (defun org-get-next-sibling ()
  21418. "Move to next heading of the same level, and return point.
  21419. If there is no such heading, return nil.
  21420. This is like outline-next-sibling, but invisible headings are ok."
  21421. (let ((level (funcall outline-level)))
  21422. (outline-next-heading)
  21423. (while (and (not (eobp)) (> (funcall outline-level) level))
  21424. (outline-next-heading))
  21425. (unless (or (eobp) (< (funcall outline-level) level))
  21426. (point))))
  21427. (defun org-get-last-sibling ()
  21428. "Move to previous heading of the same level, and return point.
  21429. If there is no such heading, return nil."
  21430. (let ((opoint (point))
  21431. (level (funcall outline-level)))
  21432. (outline-previous-heading)
  21433. (when (and (/= (point) opoint) (outline-on-heading-p t))
  21434. (while (and (> (funcall outline-level) level)
  21435. (not (bobp)))
  21436. (outline-previous-heading))
  21437. (unless (< (funcall outline-level) level)
  21438. (point)))))
  21439. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  21440. "Goto to the end of a subtree."
  21441. ;; This contains an exact copy of the original function, but it uses
  21442. ;; `org-back-to-heading', to make it work also in invisible
  21443. ;; trees. And is uses an invisible-ok argument.
  21444. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  21445. ;; Furthermore, when used inside Org, finding the end of a large subtree
  21446. ;; with many children and grandchildren etc, this can be much faster
  21447. ;; than the outline version.
  21448. (org-back-to-heading invisible-ok)
  21449. (let ((first t)
  21450. (level (funcall outline-level)))
  21451. (if (and (derived-mode-p 'org-mode) (< level 1000))
  21452. ;; A true heading (not a plain list item), in Org
  21453. ;; This means we can easily find the end by looking
  21454. ;; only for the right number of stars. Using a regexp to do
  21455. ;; this is so much faster than using a Lisp loop.
  21456. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  21457. (forward-char 1)
  21458. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  21459. ;; something else, do it the slow way
  21460. (while (and (not (eobp))
  21461. (or first (> (funcall outline-level) level)))
  21462. (setq first nil)
  21463. (outline-next-heading)))
  21464. (unless to-heading
  21465. (when (memq (preceding-char) '(?\n ?\^M))
  21466. ;; Go to end of line before heading
  21467. (forward-char -1)
  21468. (when (memq (preceding-char) '(?\n ?\^M))
  21469. ;; leave blank line before heading
  21470. (forward-char -1)))))
  21471. (point))
  21472. (defun org-end-of-meta-data (&optional full)
  21473. "Skip planning line and properties drawer in current entry.
  21474. When optional argument FULL is non-nil, also skip empty lines,
  21475. clocking lines and regular drawers at the beginning of the
  21476. entry."
  21477. (org-back-to-heading t)
  21478. (forward-line)
  21479. (when (looking-at-p org-planning-line-re) (forward-line))
  21480. (when (looking-at org-property-drawer-re)
  21481. (goto-char (match-end 0))
  21482. (forward-line))
  21483. (when (and full (not (org-at-heading-p)))
  21484. (catch 'exit
  21485. (let ((end (save-excursion (outline-next-heading) (point)))
  21486. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  21487. (while (not (eobp))
  21488. (cond ((looking-at-p org-drawer-regexp)
  21489. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21490. (forward-line)
  21491. (throw 'exit t)))
  21492. ((looking-at-p re) (forward-line))
  21493. (t (throw 'exit t))))))))
  21494. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  21495. "Move forward to the ARG'th subheading at same level as this one.
  21496. Stop at the first and last subheadings of a superior heading.
  21497. Normally this only looks at visible headings, but when INVISIBLE-OK is
  21498. non-nil it will also look at invisible ones."
  21499. (interactive "p")
  21500. (let ((backward? (and arg (< arg 0))))
  21501. (if (org-before-first-heading-p)
  21502. (if backward? (goto-char (point-min)) (outline-next-heading))
  21503. (org-back-to-heading invisible-ok)
  21504. (unless backward? (end-of-line)) ;do not match current headline
  21505. (let ((level (- (match-end 0) (match-beginning 0) 1))
  21506. (f (if backward? #'re-search-backward #'re-search-forward))
  21507. (count (if arg (abs arg) 1))
  21508. (result (point)))
  21509. (while (and (> count 0)
  21510. (funcall f org-outline-regexp-bol nil 'move))
  21511. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  21512. (cond ((< l level) (setq count 0))
  21513. ((and (= l level)
  21514. (or invisible-ok
  21515. (not (org-invisible-p
  21516. (line-beginning-position)))))
  21517. (cl-decf count)
  21518. (when (= l level) (setq result (point)))))))
  21519. (goto-char result))
  21520. (beginning-of-line))))
  21521. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  21522. "Move backward to the ARG'th subheading at same level as this one.
  21523. Stop at the first and last subheadings of a superior heading."
  21524. (interactive "p")
  21525. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  21526. (defun org-next-visible-heading (arg)
  21527. "Move to the next visible heading.
  21528. This function wraps `outline-next-visible-heading' with
  21529. `org-with-limited-levels' in order to skip over inline tasks and
  21530. respect customization of `org-odd-levels-only'."
  21531. (interactive "p")
  21532. (org-with-limited-levels
  21533. (outline-next-visible-heading arg)))
  21534. (defun org-previous-visible-heading (arg)
  21535. "Move to the previous visible heading.
  21536. This function wraps `outline-previous-visible-heading' with
  21537. `org-with-limited-levels' in order to skip over inline tasks and
  21538. respect customization of `org-odd-levels-only'."
  21539. (interactive "p")
  21540. (org-with-limited-levels
  21541. (outline-previous-visible-heading arg)))
  21542. (defun org-next-block (arg &optional backward block-regexp)
  21543. "Jump to the next block.
  21544. With a prefix argument ARG, jump forward ARG many blocks.
  21545. When BACKWARD is non-nil, jump to the previous block.
  21546. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  21547. Match data is set according to this regexp when the function
  21548. returns.
  21549. Return point at beginning of the opening line of found block.
  21550. Throw an error if no block is found."
  21551. (interactive "p")
  21552. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  21553. (case-fold-search t)
  21554. (search-fn (if backward #'re-search-backward #'re-search-forward))
  21555. (count (or arg 1))
  21556. (origin (point))
  21557. last-element)
  21558. (if backward (beginning-of-line) (end-of-line))
  21559. (while (and (> count 0) (funcall search-fn re nil t))
  21560. (let ((element (save-excursion
  21561. (goto-char (match-beginning 0))
  21562. (save-match-data (org-element-at-point)))))
  21563. (when (and (memq (org-element-type element)
  21564. '(center-block comment-block dynamic-block
  21565. example-block export-block quote-block
  21566. special-block src-block verse-block))
  21567. (<= (match-beginning 0)
  21568. (org-element-property :post-affiliated element)))
  21569. (setq last-element element)
  21570. (cl-decf count))))
  21571. (if (= count 0)
  21572. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  21573. (save-match-data (org-show-context)))
  21574. (goto-char origin)
  21575. (user-error "No %s code blocks" (if backward "previous" "further")))))
  21576. (defun org-previous-block (arg &optional block-regexp)
  21577. "Jump to the previous block.
  21578. With a prefix argument ARG, jump backward ARG many source blocks.
  21579. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  21580. (interactive "p")
  21581. (org-next-block arg t block-regexp))
  21582. (defun org-forward-paragraph ()
  21583. "Move forward to beginning of next paragraph or equivalent.
  21584. The function moves point to the beginning of the next visible
  21585. structural element, which can be a paragraph, a table, a list
  21586. item, etc. It also provides some special moves for convenience:
  21587. - On an affiliated keyword, jump to the beginning of the
  21588. relative element.
  21589. - On an item or a footnote definition, move to the second
  21590. element inside, if any.
  21591. - On a table or a property drawer, jump after it.
  21592. - On a verse or source block, stop after blank lines."
  21593. (interactive)
  21594. (unless (eobp)
  21595. (let* ((deactivate-mark nil)
  21596. (element (org-element-at-point))
  21597. (type (org-element-type element))
  21598. (post-affiliated (org-element-property :post-affiliated element))
  21599. (contents-begin (org-element-property :contents-begin element))
  21600. (contents-end (org-element-property :contents-end element))
  21601. (end (let ((end (org-element-property :end element)) (parent element))
  21602. (while (and (setq parent (org-element-property :parent parent))
  21603. (= (org-element-property :contents-end parent) end))
  21604. (setq end (org-element-property :end parent)))
  21605. end)))
  21606. (cond ((not element)
  21607. (skip-chars-forward " \r\t\n")
  21608. (or (eobp) (beginning-of-line)))
  21609. ;; On affiliated keywords, move to element's beginning.
  21610. ((< (point) post-affiliated)
  21611. (goto-char post-affiliated))
  21612. ;; At a table row, move to the end of the table. Similarly,
  21613. ;; at a node property, move to the end of the property
  21614. ;; drawer.
  21615. ((memq type '(node-property table-row))
  21616. (goto-char (org-element-property
  21617. :end (org-element-property :parent element))))
  21618. ((memq type '(property-drawer table)) (goto-char end))
  21619. ;; Consider blank lines as separators in verse and source
  21620. ;; blocks to ease editing.
  21621. ((memq type '(src-block verse-block))
  21622. (when (eq type 'src-block)
  21623. (setq contents-end
  21624. (save-excursion (goto-char end)
  21625. (skip-chars-backward " \r\t\n")
  21626. (line-beginning-position))))
  21627. (beginning-of-line)
  21628. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  21629. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  21630. (goto-char end)
  21631. (skip-chars-forward " \r\t\n")
  21632. (if (= (point) contents-end) (goto-char end)
  21633. (beginning-of-line))))
  21634. ;; With no contents, just skip element.
  21635. ((not contents-begin) (goto-char end))
  21636. ;; If contents are invisible, skip the element altogether.
  21637. ((org-invisible-p (line-end-position))
  21638. (cl-case type
  21639. (headline
  21640. (org-with-limited-levels (outline-next-visible-heading 1)))
  21641. ;; At a plain list, make sure we move to the next item
  21642. ;; instead of skipping the whole list.
  21643. (plain-list (forward-char)
  21644. (org-forward-paragraph))
  21645. (otherwise (goto-char end))))
  21646. ((>= (point) contents-end) (goto-char end))
  21647. ((>= (point) contents-begin)
  21648. ;; This can only happen on paragraphs and plain lists.
  21649. (cl-case type
  21650. (paragraph (goto-char end))
  21651. ;; At a plain list, try to move to second element in
  21652. ;; first item, if possible.
  21653. (plain-list (end-of-line)
  21654. (org-forward-paragraph))))
  21655. ;; When contents start on the middle of a line (e.g. in
  21656. ;; items and footnote definitions), try to reach first
  21657. ;; element starting after current line.
  21658. ((> (line-end-position) contents-begin)
  21659. (end-of-line)
  21660. (org-forward-paragraph))
  21661. (t (goto-char contents-begin))))))
  21662. (defun org-backward-paragraph ()
  21663. "Move backward to start of previous paragraph or equivalent.
  21664. The function moves point to the beginning of the current
  21665. structural element, which can be a paragraph, a table, a list
  21666. item, etc., or to the beginning of the previous visible one if
  21667. point is already there. It also provides some special moves for
  21668. convenience:
  21669. - On an affiliated keyword, jump to the first one.
  21670. - On a table or a property drawer, move to its beginning.
  21671. - On comment, example, export, src and verse blocks, stop
  21672. before blank lines."
  21673. (interactive)
  21674. (unless (bobp)
  21675. (let* ((deactivate-mark nil)
  21676. (element (org-element-at-point))
  21677. (type (org-element-type element))
  21678. (contents-end (org-element-property :contents-end element))
  21679. (post-affiliated (org-element-property :post-affiliated element))
  21680. (begin (org-element-property :begin element))
  21681. (special? ;blocks handled specially
  21682. (memq type '(comment-block example-block export-block src-block
  21683. verse-block)))
  21684. (contents-begin
  21685. (if special?
  21686. ;; These types have no proper contents. Fake line
  21687. ;; below the block opening line as contents beginning.
  21688. (save-excursion (goto-char begin) (line-beginning-position 2))
  21689. (org-element-property :contents-begin element))))
  21690. (cond
  21691. ((not element) (goto-char (point-min)))
  21692. ((= (point) begin)
  21693. (backward-char)
  21694. (org-backward-paragraph))
  21695. ((<= (point) post-affiliated) (goto-char begin))
  21696. ;; Special behavior: on a table or a property drawer, move to
  21697. ;; its beginning.
  21698. ((memq type '(node-property table-row))
  21699. (goto-char (org-element-property
  21700. :post-affiliated (org-element-property :parent element))))
  21701. (special?
  21702. (if (<= (point) contents-begin) (goto-char post-affiliated)
  21703. ;; Inside a verse block, see blank lines as paragraph
  21704. ;; separators.
  21705. (let ((origin (point)))
  21706. (skip-chars-backward " \r\t\n" contents-begin)
  21707. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  21708. (skip-chars-forward " \r\t\n" origin)
  21709. (if (= (point) origin) (goto-char contents-begin)
  21710. (beginning-of-line))))))
  21711. ((eq type 'paragraph) (goto-char contents-begin)
  21712. ;; When at first paragraph in an item or a footnote definition,
  21713. ;; move directly to beginning of line.
  21714. (let ((parent-contents
  21715. (org-element-property
  21716. :contents-begin (org-element-property :parent element))))
  21717. (when (and parent-contents (= parent-contents contents-begin))
  21718. (beginning-of-line))))
  21719. ;; At the end of a greater element, move to the beginning of
  21720. ;; the last element within.
  21721. ((and contents-end (>= (point) contents-end))
  21722. (goto-char (1- contents-end))
  21723. (org-backward-paragraph))
  21724. (t (goto-char (or post-affiliated begin))))
  21725. ;; Ensure we never leave point invisible.
  21726. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  21727. (defun org-forward-element ()
  21728. "Move forward by one element.
  21729. Move to the next element at the same level, when possible."
  21730. (interactive)
  21731. (cond ((eobp) (user-error "Cannot move further down"))
  21732. ((org-with-limited-levels (org-at-heading-p))
  21733. (let ((origin (point)))
  21734. (goto-char (org-end-of-subtree nil t))
  21735. (unless (org-with-limited-levels (org-at-heading-p))
  21736. (goto-char origin)
  21737. (user-error "Cannot move further down"))))
  21738. (t
  21739. (let* ((elem (org-element-at-point))
  21740. (end (org-element-property :end elem))
  21741. (parent (org-element-property :parent elem)))
  21742. (cond ((and parent (= (org-element-property :contents-end parent) end))
  21743. (goto-char (org-element-property :end parent)))
  21744. ((integer-or-marker-p end) (goto-char end))
  21745. (t (message "No element at point")))))))
  21746. (defun org-backward-element ()
  21747. "Move backward by one element.
  21748. Move to the previous element at the same level, when possible."
  21749. (interactive)
  21750. (cond ((bobp) (user-error "Cannot move further up"))
  21751. ((org-with-limited-levels (org-at-heading-p))
  21752. ;; At a headline, move to the previous one, if any, or stay
  21753. ;; here.
  21754. (let ((origin (point)))
  21755. (org-with-limited-levels (org-backward-heading-same-level 1))
  21756. ;; When current headline has no sibling above, move to its
  21757. ;; parent.
  21758. (when (= (point) origin)
  21759. (or (org-with-limited-levels (org-up-heading-safe))
  21760. (progn (goto-char origin)
  21761. (user-error "Cannot move further up"))))))
  21762. (t
  21763. (let* ((elem (org-element-at-point))
  21764. (beg (org-element-property :begin elem)))
  21765. (cond
  21766. ;; Move to beginning of current element if point isn't
  21767. ;; there already.
  21768. ((null beg) (message "No element at point"))
  21769. ((/= (point) beg) (goto-char beg))
  21770. (t (goto-char beg)
  21771. (skip-chars-backward " \r\t\n")
  21772. (unless (bobp)
  21773. (let ((prev (org-element-at-point)))
  21774. (goto-char (org-element-property :begin prev))
  21775. (while (and (setq prev (org-element-property :parent prev))
  21776. (<= (org-element-property :end prev) beg))
  21777. (goto-char (org-element-property :begin prev)))))))))))
  21778. (defun org-up-element ()
  21779. "Move to upper element."
  21780. (interactive)
  21781. (if (org-with-limited-levels (org-at-heading-p))
  21782. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  21783. (let* ((elem (org-element-at-point))
  21784. (parent (org-element-property :parent elem)))
  21785. (if parent (goto-char (org-element-property :begin parent))
  21786. (if (org-with-limited-levels (org-before-first-heading-p))
  21787. (user-error "No surrounding element")
  21788. (org-with-limited-levels (org-back-to-heading)))))))
  21789. (defun org-down-element ()
  21790. "Move to inner element."
  21791. (interactive)
  21792. (let ((element (org-element-at-point)))
  21793. (cond
  21794. ((memq (org-element-type element) '(plain-list table))
  21795. (goto-char (org-element-property :contents-begin element))
  21796. (forward-char))
  21797. ((memq (org-element-type element) org-element-greater-elements)
  21798. ;; If contents are hidden, first disclose them.
  21799. (when (org-invisible-p (line-end-position)) (org-cycle))
  21800. (goto-char (or (org-element-property :contents-begin element)
  21801. (user-error "No content for this element"))))
  21802. (t (user-error "No inner element")))))
  21803. (defun org-drag-element-backward ()
  21804. "Move backward element at point."
  21805. (interactive)
  21806. (let ((elem (or (org-element-at-point)
  21807. (user-error "No element at point"))))
  21808. (if (eq (org-element-type elem) 'headline)
  21809. ;; Preserve point when moving a whole tree, even if point was
  21810. ;; on blank lines below the headline.
  21811. (let ((offset (skip-chars-backward " \t\n")))
  21812. (unwind-protect (org-move-subtree-up)
  21813. (forward-char (- offset))))
  21814. (let ((prev-elem
  21815. (save-excursion
  21816. (goto-char (org-element-property :begin elem))
  21817. (skip-chars-backward " \r\t\n")
  21818. (unless (bobp)
  21819. (let* ((beg (org-element-property :begin elem))
  21820. (prev (org-element-at-point))
  21821. (up prev))
  21822. (while (and (setq up (org-element-property :parent up))
  21823. (<= (org-element-property :end up) beg))
  21824. (setq prev up))
  21825. prev)))))
  21826. ;; Error out if no previous element or previous element is
  21827. ;; a parent of the current one.
  21828. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  21829. (user-error "Cannot drag element backward")
  21830. (let ((pos (point)))
  21831. (org-element-swap-A-B prev-elem elem)
  21832. (goto-char (+ (org-element-property :begin prev-elem)
  21833. (- pos (org-element-property :begin elem))))))))))
  21834. (defun org-drag-element-forward ()
  21835. "Move forward element at point."
  21836. (interactive)
  21837. (let* ((pos (point))
  21838. (elem (or (org-element-at-point)
  21839. (user-error "No element at point"))))
  21840. (when (= (point-max) (org-element-property :end elem))
  21841. (user-error "Cannot drag element forward"))
  21842. (goto-char (org-element-property :end elem))
  21843. (let ((next-elem (org-element-at-point)))
  21844. (when (or (org-element-nested-p elem next-elem)
  21845. (and (eq (org-element-type next-elem) 'headline)
  21846. (not (eq (org-element-type elem) 'headline))))
  21847. (goto-char pos)
  21848. (user-error "Cannot drag element forward"))
  21849. ;; Compute new position of point: it's shifted by NEXT-ELEM
  21850. ;; body's length (without final blanks) and by the length of
  21851. ;; blanks between ELEM and NEXT-ELEM.
  21852. (let ((size-next (- (save-excursion
  21853. (goto-char (org-element-property :end next-elem))
  21854. (skip-chars-backward " \r\t\n")
  21855. (forward-line)
  21856. ;; Small correction if buffer doesn't end
  21857. ;; with a newline character.
  21858. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  21859. (org-element-property :begin next-elem)))
  21860. (size-blank (- (org-element-property :end elem)
  21861. (save-excursion
  21862. (goto-char (org-element-property :end elem))
  21863. (skip-chars-backward " \r\t\n")
  21864. (forward-line)
  21865. (point)))))
  21866. (org-element-swap-A-B elem next-elem)
  21867. (goto-char (+ pos size-next size-blank))))))
  21868. (defun org-drag-line-forward (arg)
  21869. "Drag the line at point ARG lines forward."
  21870. (interactive "p")
  21871. (dotimes (_ (abs arg))
  21872. (let ((c (current-column)))
  21873. (if (< 0 arg)
  21874. (progn
  21875. (beginning-of-line 2)
  21876. (transpose-lines 1)
  21877. (beginning-of-line 0))
  21878. (transpose-lines 1)
  21879. (beginning-of-line -1))
  21880. (org-move-to-column c))))
  21881. (defun org-drag-line-backward (arg)
  21882. "Drag the line at point ARG lines backward."
  21883. (interactive "p")
  21884. (org-drag-line-forward (- arg)))
  21885. (defun org-mark-element ()
  21886. "Put point at beginning of this element, mark at end.
  21887. Interactively, if this command is repeated or (in Transient Mark
  21888. mode) if the mark is active, it marks the next element after the
  21889. ones already marked."
  21890. (interactive)
  21891. (let (deactivate-mark)
  21892. (if (and (called-interactively-p 'any)
  21893. (or (and (eq last-command this-command) (mark t))
  21894. (and transient-mark-mode mark-active)))
  21895. (set-mark
  21896. (save-excursion
  21897. (goto-char (mark))
  21898. (goto-char (org-element-property :end (org-element-at-point)))))
  21899. (let ((element (org-element-at-point)))
  21900. (end-of-line)
  21901. (push-mark (org-element-property :end element) t t)
  21902. (goto-char (org-element-property :begin element))))))
  21903. (defun org-narrow-to-element ()
  21904. "Narrow buffer to current element."
  21905. (interactive)
  21906. (let ((elem (org-element-at-point)))
  21907. (cond
  21908. ((eq (car elem) 'headline)
  21909. (narrow-to-region
  21910. (org-element-property :begin elem)
  21911. (org-element-property :end elem)))
  21912. ((memq (car elem) org-element-greater-elements)
  21913. (narrow-to-region
  21914. (org-element-property :contents-begin elem)
  21915. (org-element-property :contents-end elem)))
  21916. (t
  21917. (narrow-to-region
  21918. (org-element-property :begin elem)
  21919. (org-element-property :end elem))))))
  21920. (defun org-transpose-element ()
  21921. "Transpose current and previous elements, keeping blank lines between.
  21922. Point is moved after both elements."
  21923. (interactive)
  21924. (org-skip-whitespace)
  21925. (let ((end (org-element-property :end (org-element-at-point))))
  21926. (org-drag-element-backward)
  21927. (goto-char end)))
  21928. (defun org-unindent-buffer ()
  21929. "Un-indent the visible part of the buffer.
  21930. Relative indentation (between items, inside blocks, etc.) isn't
  21931. modified."
  21932. (interactive)
  21933. (unless (eq major-mode 'org-mode)
  21934. (user-error "Cannot un-indent a buffer not in Org mode"))
  21935. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  21936. (unindent-tree
  21937. (lambda (contents)
  21938. (dolist (element (reverse contents))
  21939. (if (memq (org-element-type element) '(headline section))
  21940. (funcall unindent-tree (org-element-contents element))
  21941. (save-excursion
  21942. (save-restriction
  21943. (narrow-to-region
  21944. (org-element-property :begin element)
  21945. (org-element-property :end element))
  21946. (org-do-remove-indentation))))))))
  21947. (funcall unindent-tree (org-element-contents parse-tree))))
  21948. (defun org-show-children (&optional level)
  21949. "Show all direct subheadings of this heading.
  21950. Prefix arg LEVEL is how many levels below the current level
  21951. should be shown. Default is enough to cause the following
  21952. heading to appear."
  21953. (interactive "p")
  21954. ;; If `orgstruct-mode' is active, use the slower version.
  21955. (if orgstruct-mode (call-interactively #'outline-show-children)
  21956. (save-excursion
  21957. (org-back-to-heading t)
  21958. (let* ((current-level (funcall outline-level))
  21959. (max-level (org-get-valid-level
  21960. current-level
  21961. (if level (prefix-numeric-value level) 1)))
  21962. (end (save-excursion (org-end-of-subtree t t)))
  21963. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  21964. (past-first-child nil)
  21965. ;; Make sure to skip inlinetasks.
  21966. (re (format regexp-fmt
  21967. current-level
  21968. (cond
  21969. ((not (featurep 'org-inlinetask)) "")
  21970. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  21971. 3))
  21972. (t (1- org-inlinetask-min-level))))))
  21973. ;; Display parent heading.
  21974. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  21975. (forward-line)
  21976. ;; Display children. First child may be deeper than expected
  21977. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  21978. ;; MAX-LEVEL accordingly.
  21979. (while (re-search-forward re end t)
  21980. (unless past-first-child
  21981. (setq re (format regexp-fmt
  21982. current-level
  21983. (max (funcall outline-level) max-level)))
  21984. (setq past-first-child t))
  21985. (outline-flag-region
  21986. (line-end-position 0) (line-end-position) nil))))))
  21987. (defun org-show-subtree ()
  21988. "Show everything after this heading at deeper levels."
  21989. (interactive)
  21990. (outline-flag-region
  21991. (point)
  21992. (save-excursion
  21993. (org-end-of-subtree t t))
  21994. nil))
  21995. (defun org-show-entry ()
  21996. "Show the body directly following this heading.
  21997. Show the heading too, if it is currently invisible."
  21998. (interactive)
  21999. (save-excursion
  22000. (ignore-errors
  22001. (org-back-to-heading t)
  22002. (outline-flag-region
  22003. (max (point-min) (1- (point)))
  22004. (save-excursion
  22005. (if (re-search-forward
  22006. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22007. (match-beginning 1)
  22008. (point-max)))
  22009. nil)
  22010. (org-cycle-hide-drawers 'children))))
  22011. (defun org-make-options-regexp (kwds &optional extra)
  22012. "Make a regular expression for keyword lines.
  22013. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22014. when non-nil, is a regexp matching keywords names."
  22015. (concat "^[ \t]*#\\+\\("
  22016. (regexp-opt kwds)
  22017. (and extra (concat (and kwds "\\|") extra))
  22018. "\\):[ \t]*\\(.*\\)"))
  22019. ;;;; Finish up
  22020. (provide 'org)
  22021. (run-hooks 'org-load-hook)
  22022. ;;; org.el ends here