org.el 896 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2018 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: https://orgmode.org
  9. ;; Version: 9.1.10
  10. ;;
  11. ;; This file is part of GNU Emacs.
  12. ;;
  13. ;; GNU Emacs is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;; GNU Emacs is distributed in the hope that it will be useful,
  18. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ;; GNU General Public License for more details.
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  23. ;;
  24. ;;; Commentary:
  25. ;;
  26. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  27. ;; project planning with a fast and effective plain-text system.
  28. ;;
  29. ;; Org mode develops organizational tasks around NOTES files that
  30. ;; contain information about projects as plain text. Org mode is
  31. ;; implemented on top of outline-mode, which makes it possible to keep
  32. ;; the content of large files well structured. Visibility cycling and
  33. ;; structure editing help to work with the tree. Tables are easily
  34. ;; created with a built-in table editor. Org mode supports ToDo
  35. ;; items, deadlines, time stamps, and scheduling. It dynamically
  36. ;; compiles entries into an agenda that utilizes and smoothly
  37. ;; integrates much of the Emacs calendar and diary. Plain text
  38. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  39. ;; entries, and any files related to the projects. For printing and
  40. ;; sharing of notes, an Org file can be exported as a structured ASCII
  41. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  42. ;; file. It can also serve as a publishing tool for a set of linked
  43. ;; webpages.
  44. ;;
  45. ;; Installation and Activation
  46. ;; ---------------------------
  47. ;; See the corresponding sections in the manual at
  48. ;;
  49. ;; https://orgmode.org/org.html#Installation
  50. ;;
  51. ;; Documentation
  52. ;; -------------
  53. ;; The documentation of Org mode can be found in the TeXInfo file. The
  54. ;; distribution also contains a PDF version of it. At the homepage of
  55. ;; Org mode, you can read the same text online as HTML. There is also an
  56. ;; excellent reference card made by Philip Rooke. This card can be found
  57. ;; in the doc/ directory.
  58. ;;
  59. ;; A list of recent changes can be found at
  60. ;; https://orgmode.org/Changes.html
  61. ;;
  62. ;;; Code:
  63. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  64. (defvar-local org-table-formula-constants-local nil
  65. "Local version of `org-table-formula-constants'.")
  66. (defvar org-inlinetask-min-level)
  67. ;;;; Require other packages
  68. (require 'cl-lib)
  69. (eval-when-compile (require 'gnus-sum))
  70. (require 'calendar)
  71. (require 'find-func)
  72. (require 'format-spec)
  73. (or (eq this-command 'eval-buffer)
  74. (condition-case nil
  75. (load (concat (file-name-directory load-file-name)
  76. "org-loaddefs.el")
  77. nil t t t)
  78. (error
  79. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  80. (sit-for 3)
  81. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  82. (sit-for 3))))
  83. (require 'org-macs)
  84. (require 'org-compat)
  85. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  86. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  87. (defvar org-outline-regexp "\\*+ "
  88. "Regexp to match Org headlines.")
  89. (defvar org-outline-regexp-bol "^\\*+ "
  90. "Regexp to match Org headlines.
  91. This is similar to `org-outline-regexp' but additionally makes
  92. sure that we are at the beginning of the line.")
  93. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  94. "Matches a headline, putting stars and text into groups.
  95. Stars are put in group 1 and the trimmed body in group 2.")
  96. (declare-function calendar-check-holidays "holidays" (date))
  97. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  98. (declare-function cdlatex-math-symbol "ext:cdlatex")
  99. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  100. (declare-function org-add-archive-files "org-archive" (files))
  101. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  102. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  103. (declare-function org-agenda-redo "org-agenda" (&optional all))
  104. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  105. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  106. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  107. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  108. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  109. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  110. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  111. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  112. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  113. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  114. (declare-function org-clock-update-time-maybe "org-clock" ())
  115. (declare-function org-clocking-buffer "org-clock" ())
  116. (declare-function org-clocktable-shift "org-clock" (dir n))
  117. (declare-function
  118. org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  119. (declare-function org-element-at-point "org-element" ())
  120. (declare-function org-element-cache-refresh "org-element" (pos))
  121. (declare-function org-element-cache-reset "org-element" (&optional all))
  122. (declare-function org-element-contents "org-element" (element))
  123. (declare-function org-element-context "org-element" (&optional element))
  124. (declare-function org-element-copy "org-element" (datum))
  125. (declare-function org-element-interpret-data "org-element" (data))
  126. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  127. (declare-function org-element-link-parser "org-element" ())
  128. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  129. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  130. (declare-function org-element-property "org-element" (property element))
  131. (declare-function org-element-put-property "org-element" (element property value))
  132. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  133. (declare-function org-element-type "org-element" (element))
  134. (declare-function org-element-update-syntax "org-element" ())
  135. (declare-function org-id-find-id-file "org-id" (id))
  136. (declare-function org-id-get-create "org-id" (&optional force))
  137. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  138. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  139. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  140. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  141. (declare-function org-table-align "org-table" ())
  142. (declare-function org-table-begin "org-table" (&optional table-type))
  143. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  144. (declare-function org-table-blank-field "org-table" ())
  145. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  146. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  147. (declare-function org-table-cut-region "org-table" (beg end))
  148. (declare-function org-table-edit-field "org-table" (arg))
  149. (declare-function org-table-end "org-table" (&optional table-type))
  150. (declare-function org-table-end-of-field "org-table" (&optional n))
  151. (declare-function org-table-insert-row "org-table" (&optional arg))
  152. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  153. (declare-function org-table-maybe-eval-formula "org-table" ())
  154. (declare-function org-table-maybe-recalculate-line "org-table" ())
  155. (declare-function org-table-next-row "org-table" ())
  156. (declare-function org-table-paste-rectangle "org-table" ())
  157. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  158. (declare-function
  159. org-table-sort-lines "org-table"
  160. (&optional with-case sorting-type getkey-func compare-func interactive?))
  161. (declare-function org-table-shrink "org-table" (&optional begin end))
  162. (declare-function org-table-toggle-column-width "org-table" (&optional arg))
  163. (declare-function org-table-wrap-region "org-table" (arg))
  164. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  165. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  166. (declare-function orgtbl-mode "org-table" (&optional arg))
  167. (declare-function org-export-get-backend "ox" (name))
  168. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  169. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  170. (defvar ffap-url-regexp)
  171. (defvar org-element-paragraph-separate)
  172. ;; load languages based on value of `org-babel-load-languages'
  173. (defvar org-babel-load-languages)
  174. ;;;###autoload
  175. (defun org-babel-do-load-languages (sym value)
  176. "Load the languages defined in `org-babel-load-languages'."
  177. (set-default sym value)
  178. (dolist (pair org-babel-load-languages)
  179. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  180. (if active
  181. (require (intern (concat "ob-" lang)))
  182. (funcall 'fmakunbound
  183. (intern (concat "org-babel-execute:" lang)))
  184. (funcall 'fmakunbound
  185. (intern (concat "org-babel-expand-body:" lang)))))))
  186. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  187. ;;;###autoload
  188. (defun org-babel-load-file (file &optional compile)
  189. "Load Emacs Lisp source code blocks in the Org FILE.
  190. This function exports the source code using `org-babel-tangle'
  191. and then loads the resulting file using `load-file'. With prefix
  192. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  193. file to byte-code before it is loaded."
  194. (interactive "fFile to load: \nP")
  195. (let* ((age (lambda (file)
  196. (float-time
  197. (time-subtract (current-time)
  198. (nth 5 (or (file-attributes (file-truename file))
  199. (file-attributes file)))))))
  200. (base-name (file-name-sans-extension file))
  201. (exported-file (concat base-name ".el")))
  202. ;; tangle if the Org file is newer than the elisp file
  203. (unless (and (file-exists-p exported-file)
  204. (> (funcall age file) (funcall age exported-file)))
  205. ;; Tangle-file traversal returns reversed list of tangled files
  206. ;; and we want to evaluate the first target.
  207. (setq exported-file
  208. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  209. (message "%s %s"
  210. (if compile
  211. (progn (byte-compile-file exported-file 'load)
  212. "Compiled and loaded")
  213. (progn (load-file exported-file) "Loaded"))
  214. exported-file)))
  215. (defcustom org-babel-load-languages '((emacs-lisp . t))
  216. "Languages which can be evaluated in Org buffers.
  217. This list can be used to load support for any of the languages
  218. below, note that each language will depend on a different set of
  219. system executables and/or Emacs modes. When a language is
  220. \"loaded\", then code blocks in that language can be evaluated
  221. with `org-babel-execute-src-block' bound by default to C-c
  222. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  223. be set to remove code block evaluation from the C-c C-c
  224. keybinding. By default only Emacs Lisp (which has no
  225. requirements) is loaded."
  226. :group 'org-babel
  227. :set 'org-babel-do-load-languages
  228. :version "24.1"
  229. :type '(alist :tag "Babel Languages"
  230. :key-type
  231. (choice
  232. (const :tag "Awk" awk)
  233. (const :tag "C" C)
  234. (const :tag "R" R)
  235. (const :tag "Asymptote" asymptote)
  236. (const :tag "Calc" calc)
  237. (const :tag "Clojure" clojure)
  238. (const :tag "CSS" css)
  239. (const :tag "Ditaa" ditaa)
  240. (const :tag "Dot" dot)
  241. (const :tag "Ebnf2ps" ebnf2ps)
  242. (const :tag "Emacs Lisp" emacs-lisp)
  243. (const :tag "Forth" forth)
  244. (const :tag "Fortran" fortran)
  245. (const :tag "Gnuplot" gnuplot)
  246. (const :tag "Haskell" haskell)
  247. (const :tag "hledger" hledger)
  248. (const :tag "IO" io)
  249. (const :tag "J" J)
  250. (const :tag "Java" java)
  251. (const :tag "Javascript" js)
  252. (const :tag "LaTeX" latex)
  253. (const :tag "Ledger" ledger)
  254. (const :tag "Lilypond" lilypond)
  255. (const :tag "Lisp" lisp)
  256. (const :tag "Makefile" makefile)
  257. (const :tag "Maxima" maxima)
  258. (const :tag "Matlab" matlab)
  259. (const :tag "Mscgen" mscgen)
  260. (const :tag "Ocaml" ocaml)
  261. (const :tag "Octave" octave)
  262. (const :tag "Org" org)
  263. (const :tag "Perl" perl)
  264. (const :tag "Pico Lisp" picolisp)
  265. (const :tag "PlantUML" plantuml)
  266. (const :tag "Python" python)
  267. (const :tag "Ruby" ruby)
  268. (const :tag "Sass" sass)
  269. (const :tag "Scala" scala)
  270. (const :tag "Scheme" scheme)
  271. (const :tag "Screen" screen)
  272. (const :tag "Shell Script" shell)
  273. (const :tag "Shen" shen)
  274. (const :tag "Sql" sql)
  275. (const :tag "Sqlite" sqlite)
  276. (const :tag "Stan" stan)
  277. (const :tag "Vala" vala))
  278. :value-type (boolean :tag "Activate" :value t)))
  279. ;;;; Customization variables
  280. (defcustom org-clone-delete-id nil
  281. "Remove ID property of clones of a subtree.
  282. When non-nil, clones of a subtree don't inherit the ID property.
  283. Otherwise they inherit the ID property with a new unique
  284. identifier."
  285. :type 'boolean
  286. :version "24.1"
  287. :group 'org-id)
  288. ;;; Version
  289. (org-check-version)
  290. ;;;###autoload
  291. (defun org-version (&optional here full message)
  292. "Show the Org version.
  293. Interactively, or when MESSAGE is non-nil, show it in echo area.
  294. With prefix argument, or when HERE is non-nil, insert it at point.
  295. In non-interactive uses, a reduced version string is output unless
  296. FULL is given."
  297. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  298. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  299. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  300. (load-suffixes (list ".el"))
  301. (org-install-dir
  302. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  303. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  304. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  305. (let* ((load-suffixes save-load-suffixes)
  306. (release (org-release))
  307. (git-version (org-git-version))
  308. (version (format "Org mode version %s (%s @ %s)"
  309. release
  310. git-version
  311. (if org-install-dir
  312. (if (string= org-dir org-install-dir)
  313. org-install-dir
  314. (concat "mixed installation! "
  315. org-install-dir
  316. " and "
  317. org-dir))
  318. "org-loaddefs.el can not be found!")))
  319. (version1 (if full version release)))
  320. (when here (insert version1))
  321. (when message (message "%s" version1))
  322. version1)))
  323. (defconst org-version (org-version))
  324. ;;; Syntax Constants
  325. ;;;; Block
  326. (defconst org-block-regexp
  327. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  328. "Regular expression for hiding blocks.")
  329. (defconst org-dblock-start-re
  330. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  331. "Matches the start line of a dynamic block, with parameters.")
  332. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  333. "Matches the end of a dynamic block.")
  334. ;;;; Clock and Planning
  335. (defconst org-clock-string "CLOCK:"
  336. "String used as prefix for timestamps clocking work hours on an item.")
  337. (defvar org-closed-string "CLOSED:"
  338. "String used as the prefix for timestamps logging closing a TODO entry.")
  339. (defvar org-deadline-string "DEADLINE:"
  340. "String to mark deadline entries.
  341. \\<org-mode-map>
  342. A deadline is this string, followed by a time stamp. It must be
  343. a word, terminated by a colon. You can insert a schedule keyword
  344. and a timestamp with `\\[org-deadline]'.")
  345. (defvar org-scheduled-string "SCHEDULED:"
  346. "String to mark scheduled TODO entries.
  347. \\<org-mode-map>
  348. A schedule is this string, followed by a time stamp. It must be
  349. a word, terminated by a colon. You can insert a schedule keyword
  350. and a timestamp with `\\[org-schedule]'.")
  351. (defconst org-ds-keyword-length
  352. (+ 2
  353. (apply #'max
  354. (mapcar #'length
  355. (list org-deadline-string org-scheduled-string
  356. org-clock-string org-closed-string))))
  357. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  358. (defconst org-planning-line-re
  359. (concat "^[ \t]*"
  360. (regexp-opt
  361. (list org-closed-string org-deadline-string org-scheduled-string)
  362. t))
  363. "Matches a line with planning info.
  364. Matched keyword is in group 1.")
  365. (defconst org-clock-line-re
  366. (concat "^[ \t]*" org-clock-string)
  367. "Matches a line with clock info.")
  368. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  369. "Matches the DEADLINE keyword.")
  370. (defconst org-deadline-time-regexp
  371. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  372. "Matches the DEADLINE keyword together with a time stamp.")
  373. (defconst org-deadline-time-hour-regexp
  374. (concat "\\<" org-deadline-string
  375. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  376. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  377. (defconst org-deadline-line-regexp
  378. (concat "\\<\\(" org-deadline-string "\\).*")
  379. "Matches the DEADLINE keyword and the rest of the line.")
  380. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  381. "Matches the SCHEDULED keyword.")
  382. (defconst org-scheduled-time-regexp
  383. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  384. "Matches the SCHEDULED keyword together with a time stamp.")
  385. (defconst org-scheduled-time-hour-regexp
  386. (concat "\\<" org-scheduled-string
  387. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  388. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  389. (defconst org-closed-time-regexp
  390. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  391. "Matches the CLOSED keyword together with a time stamp.")
  392. (defconst org-keyword-time-regexp
  393. (concat "\\<"
  394. (regexp-opt
  395. (list org-scheduled-string org-deadline-string org-closed-string
  396. org-clock-string)
  397. t)
  398. " *[[<]\\([^]>]+\\)[]>]")
  399. "Matches any of the 4 keywords, together with the time stamp.")
  400. (defconst org-keyword-time-not-clock-regexp
  401. (concat
  402. "\\<"
  403. (regexp-opt
  404. (list org-scheduled-string org-deadline-string org-closed-string) t)
  405. " *[[<]\\([^]>]+\\)[]>]")
  406. "Matches any of the 3 keywords, together with the time stamp.")
  407. (defconst org-maybe-keyword-time-regexp
  408. (concat "\\(\\<"
  409. (regexp-opt
  410. (list org-scheduled-string org-deadline-string org-closed-string
  411. org-clock-string)
  412. t)
  413. "\\)?"
  414. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  415. "\\|"
  416. "<%%([^\r\n>]*>\\)")
  417. "Matches a timestamp, possibly preceded by a keyword.")
  418. (defconst org-all-time-keywords
  419. (mapcar (lambda (w) (substring w 0 -1))
  420. (list org-scheduled-string org-deadline-string
  421. org-clock-string org-closed-string))
  422. "List of time keywords.")
  423. ;;;; Drawer
  424. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  425. "Matches first or last line of a hidden block.
  426. Group 1 contains drawer's name or \"END\".")
  427. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  428. "Regular expression matching the first line of a property drawer.")
  429. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  430. "Regular expression matching the last line of a property drawer.")
  431. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  432. "Regular expression matching the first line of a clock drawer.")
  433. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  434. "Regular expression matching the last line of a clock drawer.")
  435. (defconst org-property-drawer-re
  436. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  437. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  438. "[ \t]*:END:[ \t]*$")
  439. "Matches an entire property drawer.")
  440. (defconst org-clock-drawer-re
  441. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  442. org-clock-drawer-end-re "\\)\n?")
  443. "Matches an entire clock drawer.")
  444. ;;;; Headline
  445. (defconst org-heading-keyword-regexp-format
  446. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  447. "Printf format for a regexp matching a headline with some keyword.
  448. This regexp will match the headline of any node which has the
  449. exact keyword that is put into the format. The keyword isn't in
  450. any group by default, but the stars and the body are.")
  451. (defconst org-heading-keyword-maybe-regexp-format
  452. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  453. "Printf format for a regexp matching a headline, possibly with some keyword.
  454. This regexp can match any headline with the specified keyword, or
  455. without a keyword. The keyword isn't in any group by default,
  456. but the stars and the body are.")
  457. (defconst org-archive-tag "ARCHIVE"
  458. "The tag that marks a subtree as archived.
  459. An archived subtree does not open during visibility cycling, and does
  460. not contribute to the agenda listings.")
  461. (defconst org-tag-re "[[:alnum:]_@#%]+"
  462. "Regexp matching a single tag.")
  463. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  464. "Regexp matching the tag group at the end of a line, with leading spaces.
  465. Tags are stored in match group 1. Match group 2 stores the tags
  466. without the enclosing colons.")
  467. (defconst org-tag-line-re
  468. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  469. "Regexp matching tags in a headline.
  470. Tags are stored in match group 1. Match group 2 stores the tags
  471. without the enclosing colons.")
  472. (eval-and-compile
  473. (defconst org-comment-string "COMMENT"
  474. "Entries starting with this keyword will never be exported.
  475. \\<org-mode-map>
  476. An entry can be toggled between COMMENT and normal with
  477. `\\[org-toggle-comment]'."))
  478. ;;;; LaTeX Environments and Fragments
  479. (defconst org-latex-regexps
  480. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  481. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  482. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  483. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  484. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  485. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  486. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  487. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  488. "Regular expressions for matching embedded LaTeX.")
  489. ;;;; Node Property
  490. (defconst org-effort-property "Effort"
  491. "The property that is being used to keep track of effort estimates.
  492. Effort estimates given in this property need to have the format H:MM.")
  493. ;;;; Table
  494. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  495. "Detect an org-type or table-type table.")
  496. (defconst org-table-line-regexp "^[ \t]*|"
  497. "Detect an org-type table line.")
  498. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  499. "Detect an org-type table line.")
  500. (defconst org-table-hline-regexp "^[ \t]*|-"
  501. "Detect an org-type table hline.")
  502. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  503. "Detect a table-type table hline.")
  504. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  505. "Detect the first line outside a table when searching from within it.
  506. This works for both table types.")
  507. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  508. "Detect a #+TBLFM line.")
  509. ;;;; Timestamp
  510. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  511. "Regular expression for fast time stamp matching.")
  512. (defconst org-ts-regexp-inactive
  513. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  514. "Regular expression for fast inactive time stamp matching.")
  515. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  516. "Regular expression for fast time stamp matching.")
  517. (defconst org-ts-regexp0
  518. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  519. "Regular expression matching time strings for analysis.
  520. This one does not require the space after the date, so it can be used
  521. on a string that terminates immediately after the date.")
  522. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  523. "Regular expression matching time strings for analysis.")
  524. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  525. "Regular expression matching time stamps, with groups.")
  526. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  527. "Regular expression matching time stamps (also [..]), with groups.")
  528. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  529. "Regular expression matching a time stamp range.")
  530. (defconst org-tr-regexp-both
  531. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  532. "Regular expression matching a time stamp range.")
  533. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  534. org-ts-regexp "\\)?")
  535. "Regular expression matching a time stamp or time stamp range.")
  536. (defconst org-tsr-regexp-both
  537. (concat org-ts-regexp-both "\\(--?-?"
  538. org-ts-regexp-both "\\)?")
  539. "Regular expression matching a time stamp or time stamp range.
  540. The time stamps may be either active or inactive.")
  541. (defconst org-repeat-re
  542. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  543. "Regular expression for specifying repeated events.
  544. After a match, group 1 contains the repeat expression.")
  545. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  546. "Formats for `format-time-string' which are used for time stamps.")
  547. ;;; The custom variables
  548. (defgroup org nil
  549. "Outline-based notes management and organizer."
  550. :tag "Org"
  551. :group 'outlines
  552. :group 'calendar)
  553. (defcustom org-mode-hook nil
  554. "Mode hook for Org mode, run after the mode was turned on."
  555. :group 'org
  556. :type 'hook)
  557. (defcustom org-load-hook nil
  558. "Hook that is run after org.el has been loaded."
  559. :group 'org
  560. :type 'hook)
  561. (defcustom org-log-buffer-setup-hook nil
  562. "Hook that is run after an Org log buffer is created."
  563. :group 'org
  564. :version "24.1"
  565. :type 'hook)
  566. (defvar org-modules) ; defined below
  567. (defvar org-modules-loaded nil
  568. "Have the modules been loaded already?")
  569. (defun org-load-modules-maybe (&optional force)
  570. "Load all extensions listed in `org-modules'."
  571. (when (or force (not org-modules-loaded))
  572. (dolist (ext org-modules)
  573. (condition-case nil (require ext)
  574. (error (message "Problems while trying to load feature `%s'" ext))))
  575. (setq org-modules-loaded t)))
  576. (defun org-set-modules (var value)
  577. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  578. (set var value)
  579. (when (featurep 'org)
  580. (org-load-modules-maybe 'force)
  581. (org-element-cache-reset 'all)))
  582. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  583. "Modules that should always be loaded together with org.el.
  584. If a description starts with <C>, the file is not part of Emacs
  585. and loading it will require that you have downloaded and properly
  586. installed the Org mode distribution.
  587. You can also use this system to load external packages (i.e. neither Org
  588. core modules, nor modules from the CONTRIB directory). Just add symbols
  589. to the end of the list. If the package is called org-xyz.el, then you need
  590. to add the symbol `xyz', and the package must have a call to:
  591. (provide \\='org-xyz)
  592. For export specific modules, see also `org-export-backends'."
  593. :group 'org
  594. :set 'org-set-modules
  595. :version "24.4"
  596. :package-version '(Org . "8.0")
  597. :type
  598. '(set :greedy t
  599. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  600. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  601. (const :tag " crypt: Encryption of subtrees" org-crypt)
  602. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  603. (const :tag " docview: Links to doc-view buffers" org-docview)
  604. (const :tag " eww: Store link to url of eww" org-eww)
  605. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  606. (const :tag " habit: Track your consistency with habits" org-habit)
  607. (const :tag " id: Global IDs for identifying entries" org-id)
  608. (const :tag " info: Links to Info nodes" org-info)
  609. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  610. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  611. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  612. (const :tag " mouse: Additional mouse support" org-mouse)
  613. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  614. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  615. (const :tag " tempo: Fast completion for structures" org-tempo)
  616. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  617. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  618. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  619. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  620. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  621. (const :tag "C collector: Collect properties into tables" org-collector)
  622. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  623. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  624. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  625. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  626. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  627. (const :tag "C eval: Include command output as text" org-eval)
  628. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  629. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  630. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  631. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  632. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  633. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  634. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  635. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  636. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  637. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  638. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  639. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  640. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  641. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  642. (const :tag "C registry: A registry for Org links" org-registry)
  643. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  644. (const :tag "C secretary: Team management with Org" org-secretary)
  645. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  646. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  647. (const :tag "C track: Keep up with Org mode development" org-track)
  648. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  649. (const :tag "C vm: Links to VM folders/messages" org-vm)
  650. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  651. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  652. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  653. (defvar org-export-registered-backends) ; From ox.el.
  654. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  655. (declare-function org-export-backend-name "ox" (backend) t)
  656. (defcustom org-export-backends '(ascii html icalendar latex odt)
  657. "List of export back-ends that should be always available.
  658. If a description starts with <C>, the file is not part of Emacs
  659. and loading it will require that you have downloaded and properly
  660. installed the Org mode distribution.
  661. Unlike to `org-modules', libraries in this list will not be
  662. loaded along with Org, but only once the export framework is
  663. needed.
  664. This variable needs to be set before org.el is loaded. If you
  665. need to make a change while Emacs is running, use the customize
  666. interface or run the following code, where VAL stands for the new
  667. value of the variable, after updating it:
  668. (progn
  669. (setq org-export-registered-backends
  670. (cl-remove-if-not
  671. (lambda (backend)
  672. (let ((name (org-export-backend-name backend)))
  673. (or (memq name val)
  674. (catch \\='parentp
  675. (dolist (b val)
  676. (and (org-export-derived-backend-p b name)
  677. (throw \\='parentp t)))))))
  678. org-export-registered-backends))
  679. (let ((new-list (mapcar #\\='org-export-backend-name
  680. org-export-registered-backends)))
  681. (dolist (backend val)
  682. (cond
  683. ((not (load (format \"ox-%s\" backend) t t))
  684. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  685. backend))
  686. ((not (memq backend new-list)) (push backend new-list))))
  687. (set-default \\='org-export-backends new-list)))
  688. Adding a back-end to this list will also pull the back-end it
  689. depends on, if any."
  690. :group 'org
  691. :group 'org-export
  692. :version "26.1"
  693. :package-version '(Org . "9.0")
  694. :initialize 'custom-initialize-set
  695. :set (lambda (var val)
  696. (if (not (featurep 'ox)) (set-default var val)
  697. ;; Any back-end not required anymore (not present in VAL and not
  698. ;; a parent of any back-end in the new value) is removed from the
  699. ;; list of registered back-ends.
  700. (setq org-export-registered-backends
  701. (cl-remove-if-not
  702. (lambda (backend)
  703. (let ((name (org-export-backend-name backend)))
  704. (or (memq name val)
  705. (catch 'parentp
  706. (dolist (b val)
  707. (and (org-export-derived-backend-p b name)
  708. (throw 'parentp t)))))))
  709. org-export-registered-backends))
  710. ;; Now build NEW-LIST of both new back-ends and required
  711. ;; parents.
  712. (let ((new-list (mapcar #'org-export-backend-name
  713. org-export-registered-backends)))
  714. (dolist (backend val)
  715. (cond
  716. ((not (load (format "ox-%s" backend) t t))
  717. (message "Problems while trying to load export back-end `%s'"
  718. backend))
  719. ((not (memq backend new-list)) (push backend new-list))))
  720. ;; Set VAR to that list with fixed dependencies.
  721. (set-default var new-list))))
  722. :type '(set :greedy t
  723. (const :tag " ascii Export buffer to ASCII format" ascii)
  724. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  725. (const :tag " html Export buffer to HTML format" html)
  726. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  727. (const :tag " latex Export buffer to LaTeX format" latex)
  728. (const :tag " man Export buffer to MAN format" man)
  729. (const :tag " md Export buffer to Markdown format" md)
  730. (const :tag " odt Export buffer to ODT format" odt)
  731. (const :tag " org Export buffer to Org format" org)
  732. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  733. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  734. (const :tag "C deck Export buffer to deck.js presentations" deck)
  735. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  736. (const :tag "C groff Export buffer to Groff format" groff)
  737. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  738. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  739. (const :tag "C s5 Export buffer to s5 presentations" s5)
  740. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  741. (eval-after-load 'ox
  742. '(dolist (backend org-export-backends)
  743. (condition-case nil (require (intern (format "ox-%s" backend)))
  744. (error (message "Problems while trying to load export back-end `%s'"
  745. backend)))))
  746. (defcustom org-support-shift-select nil
  747. "Non-nil means make shift-cursor commands select text when possible.
  748. \\<org-mode-map>\
  749. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  750. start selecting a region, or enlarge regions started in this way.
  751. In Org mode, in special contexts, these same keys are used for
  752. other purposes, important enough to compete with shift selection.
  753. Org tries to balance these needs by supporting `shift-select-mode'
  754. outside these special contexts, under control of this variable.
  755. The default of this variable is nil, to avoid confusing behavior. Shifted
  756. cursor keys will then execute Org commands in the following contexts:
  757. - on a headline, changing TODO state (left/right) and priority (up/down)
  758. - on a time stamp, changing the time
  759. - in a plain list item, changing the bullet type
  760. - in a property definition line, switching between allowed values
  761. - in the BEGIN line of a clock table (changing the time block).
  762. Outside these contexts, the commands will throw an error.
  763. When this variable is t and the cursor is not in a special
  764. context, Org mode will support shift-selection for making and
  765. enlarging regions. To make this more effective, the bullet
  766. cycling will no longer happen anywhere in an item line, but only
  767. if the cursor is exactly on the bullet.
  768. If you set this variable to the symbol `always', then the keys
  769. will not be special in headlines, property lines, and item lines,
  770. to make shift selection work there as well. If this is what you
  771. want, you can use the following alternative commands:
  772. `\\[org-todo]' and `\\[org-priority]' \
  773. to change TODO state and priority,
  774. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  775. can be used to switch TODO sets,
  776. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  777. and properties can be edited by hand or in column view.
  778. However, when the cursor is on a timestamp, shift-cursor commands
  779. will still edit the time stamp - this is just too good to give up."
  780. :group 'org
  781. :type '(choice
  782. (const :tag "Never" nil)
  783. (const :tag "When outside special context" t)
  784. (const :tag "Everywhere except timestamps" always)))
  785. (defcustom org-loop-over-headlines-in-active-region nil
  786. "Shall some commands act upon headlines in the active region?
  787. When set to t, some commands will be performed in all headlines
  788. within the active region.
  789. When set to `start-level', some commands will be performed in all
  790. headlines within the active region, provided that these headlines
  791. are of the same level than the first one.
  792. When set to a string, those commands will be performed on the
  793. matching headlines within the active region. Such string must be
  794. a tags/property/todo match as it is used in the agenda tags view.
  795. The list of commands is: `org-schedule', `org-deadline',
  796. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  797. `org-archive-to-archive-sibling'. The archiving commands skip
  798. already archived entries."
  799. :type '(choice (const :tag "Don't loop" nil)
  800. (const :tag "All headlines in active region" t)
  801. (const :tag "In active region, headlines at the same level than the first one" start-level)
  802. (string :tag "Tags/Property/Todo matcher"))
  803. :version "24.1"
  804. :group 'org-todo
  805. :group 'org-archive)
  806. (defcustom org-startup-folded t
  807. "Non-nil means entering Org mode will switch to OVERVIEW.
  808. This can also be configured on a per-file basis by adding one of
  809. the following lines anywhere in the buffer:
  810. #+STARTUP: fold (or `overview', this is equivalent)
  811. #+STARTUP: nofold (or `showall', this is equivalent)
  812. #+STARTUP: content
  813. #+STARTUP: showeverything
  814. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  815. to ignore this option when Org opens agenda files for the first
  816. time."
  817. :group 'org-startup
  818. :type '(choice
  819. (const :tag "nofold: show all" nil)
  820. (const :tag "fold: overview" t)
  821. (const :tag "content: all headlines" content)
  822. (const :tag "show everything, even drawers" showeverything)))
  823. (defcustom org-startup-truncated t
  824. "Non-nil means entering Org mode will set `truncate-lines'.
  825. This is useful since some lines containing links can be very long and
  826. uninteresting. Also tables look terrible when wrapped.
  827. The variable `org-startup-truncated' allows to configure
  828. truncation for Org mode different to the other modes that use the
  829. variable `truncate-lines' and as a shortcut instead of putting
  830. the variable `truncate-lines' into the `org-mode-hook'. If one
  831. wants to configure truncation for Org mode not statically but
  832. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  833. the variable `truncate-lines' has to be used because in such a
  834. case it is too late to set the variable `org-startup-truncated'."
  835. :group 'org-startup
  836. :type 'boolean)
  837. (defcustom org-startup-indented nil
  838. "Non-nil means turn on `org-indent-mode' on startup.
  839. This can also be configured on a per-file basis by adding one of
  840. the following lines anywhere in the buffer:
  841. #+STARTUP: indent
  842. #+STARTUP: noindent"
  843. :group 'org-structure
  844. :type '(choice
  845. (const :tag "Not" nil)
  846. (const :tag "Globally (slow on startup in large files)" t)))
  847. (defcustom org-use-sub-superscripts t
  848. "Non-nil means interpret \"_\" and \"^\" for display.
  849. If you want to control how Org exports those characters, see
  850. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  851. used to be an alias for `org-export-with-sub-superscripts' in
  852. Org <8.0, it is not anymore.
  853. When this option is turned on, you can use TeX-like syntax for
  854. sub- and superscripts within the buffer. Several characters after
  855. \"_\" or \"^\" will be considered as a single item - so grouping
  856. with {} is normally not needed. For example, the following things
  857. will be parsed as single sub- or superscripts:
  858. 10^24 or 10^tau several digits will be considered 1 item.
  859. 10^-12 or 10^-tau a leading sign with digits or a word
  860. x^2-y^3 will be read as x^2 - y^3, because items are
  861. terminated by almost any nonword/nondigit char.
  862. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  863. Still, ambiguity is possible. So when in doubt, use {} to enclose
  864. the sub/superscript. If you set this variable to the symbol `{}',
  865. the braces are *required* in order to trigger interpretations as
  866. sub/superscript. This can be helpful in documents that need \"_\"
  867. frequently in plain text."
  868. :group 'org-startup
  869. :version "24.4"
  870. :package-version '(Org . "8.0")
  871. :type '(choice
  872. (const :tag "Always interpret" t)
  873. (const :tag "Only with braces" {})
  874. (const :tag "Never interpret" nil)))
  875. (defcustom org-startup-with-beamer-mode nil
  876. "Non-nil means turn on `org-beamer-mode' on startup.
  877. This can also be configured on a per-file basis by adding one of
  878. the following lines anywhere in the buffer:
  879. #+STARTUP: beamer"
  880. :group 'org-startup
  881. :version "24.1"
  882. :type 'boolean)
  883. (defcustom org-startup-align-all-tables nil
  884. "Non-nil means align all tables when visiting a file.
  885. This can also be configured on a per-file basis by adding one of
  886. the following lines anywhere in the buffer:
  887. #+STARTUP: align
  888. #+STARTUP: noalign"
  889. :group 'org-startup
  890. :type 'boolean)
  891. (defcustom org-startup-shrink-all-tables nil
  892. "Non-nil means shrink all table columns with a width cookie.
  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: shrink"
  896. :group 'org-startup
  897. :type 'boolean
  898. :version "27.1"
  899. :package-version '(Org . "9.2")
  900. :safe #'booleanp)
  901. (defcustom org-startup-with-inline-images nil
  902. "Non-nil means show inline images when loading a new Org file.
  903. This can also be configured on a per-file basis by adding one of
  904. the following lines anywhere in the buffer:
  905. #+STARTUP: inlineimages
  906. #+STARTUP: noinlineimages"
  907. :group 'org-startup
  908. :version "24.1"
  909. :type 'boolean)
  910. (defcustom org-startup-with-latex-preview nil
  911. "Non-nil means preview LaTeX fragments when loading a new Org file.
  912. This can also be configured on a per-file basis by adding one of
  913. the following lines anywhere in the buffer:
  914. #+STARTUP: latexpreview
  915. #+STARTUP: nolatexpreview"
  916. :group 'org-startup
  917. :version "24.4"
  918. :package-version '(Org . "8.0")
  919. :type 'boolean)
  920. (defcustom org-insert-mode-line-in-empty-file nil
  921. "Non-nil means insert the first line setting Org mode in empty files.
  922. When the function `org-mode' is called interactively in an empty file, this
  923. normally means that the file name does not automatically trigger Org mode.
  924. To ensure that the file will always be in Org mode in the future, a
  925. line enforcing Org mode will be inserted into the buffer, if this option
  926. has been set."
  927. :group 'org-startup
  928. :type 'boolean)
  929. (defcustom org-replace-disputed-keys nil
  930. "Non-nil means use alternative key bindings for some keys.
  931. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  932. These keys are also used by other packages like Shift Select mode,
  933. CUA mode or Windmove. If you want to use Org mode together with
  934. one of these other modes, or more generally if you would like to
  935. move some Org mode commands to other keys, set this variable and
  936. configure the keys with the variable `org-disputed-keys'.
  937. This option is only relevant at load-time of Org mode, and must be set
  938. *before* org.el is loaded. Changing it requires a restart of Emacs to
  939. become effective."
  940. :group 'org-startup
  941. :type 'boolean)
  942. (defcustom org-use-extra-keys nil
  943. "Non-nil means use extra key sequence definitions for certain commands.
  944. This happens automatically if `window-system' is nil. This
  945. variable lets you do the same manually. You must set it before
  946. loading Org."
  947. :group 'org-startup
  948. :type 'boolean)
  949. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  950. (defcustom org-disputed-keys
  951. '(([(shift up)] . [(meta p)])
  952. ([(shift down)] . [(meta n)])
  953. ([(shift left)] . [(meta -)])
  954. ([(shift right)] . [(meta +)])
  955. ([(control shift right)] . [(meta shift +)])
  956. ([(control shift left)] . [(meta shift -)]))
  957. "Keys for which Org mode and other modes compete.
  958. This is an alist, cars are the default keys, second element specifies
  959. the alternative to use when `org-replace-disputed-keys' is t.
  960. Keys can be specified in any syntax supported by `define-key'.
  961. The value of this option takes effect only at Org mode startup,
  962. therefore you'll have to restart Emacs to apply it after changing."
  963. :group 'org-startup
  964. :type 'alist)
  965. (defun org-key (key)
  966. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  967. Or return the original if not disputed."
  968. (when org-replace-disputed-keys
  969. (let* ((nkey (key-description key))
  970. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  971. org-disputed-keys)))
  972. (setq key (if x (cdr x) key))))
  973. key)
  974. (defun org-defkey (keymap key def)
  975. "Define a key, possibly translated, as returned by `org-key'."
  976. (define-key keymap (org-key key) def))
  977. (defcustom org-ellipsis nil
  978. "The ellipsis to use in the Org mode outline.
  979. When nil, just use the standard three dots. When a non-empty string,
  980. use that string instead.
  981. The change affects only Org mode (which will then use its own display table).
  982. Changing this requires executing `\\[org-mode]' in a buffer to become
  983. effective."
  984. :group 'org-startup
  985. :type '(choice (const :tag "Default" nil)
  986. (string :tag "String" :value "...#"))
  987. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  988. (defvar org-display-table nil
  989. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  990. (defgroup org-keywords nil
  991. "Keywords in Org mode."
  992. :tag "Org Keywords"
  993. :group 'org)
  994. (defcustom org-closed-keep-when-no-todo nil
  995. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  996. :group 'org-todo
  997. :group 'org-keywords
  998. :version "24.4"
  999. :package-version '(Org . "8.0")
  1000. :type 'boolean)
  1001. (defgroup org-structure nil
  1002. "Options concerning the general structure of Org files."
  1003. :tag "Org Structure"
  1004. :group 'org)
  1005. (defgroup org-reveal-location nil
  1006. "Options about how to make context of a location visible."
  1007. :tag "Org Reveal Location"
  1008. :group 'org-structure)
  1009. (defcustom org-show-context-detail '((agenda . local)
  1010. (bookmark-jump . lineage)
  1011. (isearch . lineage)
  1012. (default . ancestors))
  1013. "Alist between context and visibility span when revealing a location.
  1014. \\<org-mode-map>Some actions may move point into invisible
  1015. locations. As a consequence, Org always expose a neighborhood
  1016. around point. How much is shown depends on the initial action,
  1017. or context. Valid contexts are
  1018. agenda when exposing an entry from the agenda
  1019. org-goto when using the command `org-goto' (`\\[org-goto]')
  1020. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1021. tags-tree when constructing a sparse tree based on tags matches
  1022. link-search when exposing search matches associated with a link
  1023. mark-goto when exposing the jump goal of a mark
  1024. bookmark-jump when exposing a bookmark location
  1025. isearch when exiting from an incremental search
  1026. default default for all contexts not set explicitly
  1027. Allowed visibility spans are
  1028. minimal show current headline; if point is not on headline,
  1029. also show entry
  1030. local show current headline, entry and next headline
  1031. ancestors show current headline and its direct ancestors; if
  1032. point is not on headline, also show entry
  1033. lineage show current headline, its direct ancestors and all
  1034. their children; if point is not on headline, also show
  1035. entry and first child
  1036. tree show current headline, its direct ancestors and all
  1037. their children; if point is not on headline, also show
  1038. entry and all children
  1039. canonical show current headline, its direct ancestors along with
  1040. their entries and children; if point is not located on
  1041. the headline, also show current entry and all children
  1042. As special cases, a nil or t value means show all contexts in
  1043. `minimal' or `canonical' view, respectively.
  1044. Some views can make displayed information very compact, but also
  1045. make it harder to edit the location of the match. In such
  1046. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1047. more context."
  1048. :group 'org-reveal-location
  1049. :version "26.1"
  1050. :package-version '(Org . "9.0")
  1051. :type '(choice
  1052. (const :tag "Canonical" t)
  1053. (const :tag "Minimal" nil)
  1054. (repeat :greedy t :tag "Individual contexts"
  1055. (cons
  1056. (choice :tag "Context"
  1057. (const agenda)
  1058. (const org-goto)
  1059. (const occur-tree)
  1060. (const tags-tree)
  1061. (const link-search)
  1062. (const mark-goto)
  1063. (const bookmark-jump)
  1064. (const isearch)
  1065. (const default))
  1066. (choice :tag "Detail level"
  1067. (const minimal)
  1068. (const local)
  1069. (const ancestors)
  1070. (const lineage)
  1071. (const tree)
  1072. (const canonical))))))
  1073. (defcustom org-indirect-buffer-display 'other-window
  1074. "How should indirect tree buffers be displayed?
  1075. This applies to indirect buffers created with the commands
  1076. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1077. Valid values are:
  1078. current-window Display in the current window
  1079. other-window Just display in another window.
  1080. dedicated-frame Create one new frame, and re-use it each time.
  1081. new-frame Make a new frame each time. Note that in this case
  1082. previously-made indirect buffers are kept, and you need to
  1083. kill these buffers yourself."
  1084. :group 'org-structure
  1085. :group 'org-agenda-windows
  1086. :type '(choice
  1087. (const :tag "In current window" current-window)
  1088. (const :tag "In current frame, other window" other-window)
  1089. (const :tag "Each time a new frame" new-frame)
  1090. (const :tag "One dedicated frame" dedicated-frame)))
  1091. (defcustom org-use-speed-commands nil
  1092. "Non-nil means activate single letter commands at beginning of a headline.
  1093. This may also be a function to test for appropriate locations where speed
  1094. commands should be active.
  1095. For example, to activate speed commands when the point is on any
  1096. star at the beginning of the headline, you can do this:
  1097. (setq org-use-speed-commands
  1098. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1099. :group 'org-structure
  1100. :type '(choice
  1101. (const :tag "Never" nil)
  1102. (const :tag "At beginning of headline stars" t)
  1103. (function)))
  1104. (defcustom org-speed-commands-user nil
  1105. "Alist of additional speed commands.
  1106. This list will be checked before `org-speed-commands-default'
  1107. when the variable `org-use-speed-commands' is non-nil
  1108. and when the cursor is at the beginning of a headline.
  1109. The car of each entry is a string with a single letter, which must
  1110. be assigned to `self-insert-command' in the global map.
  1111. The cdr is either a command to be called interactively, a function
  1112. to be called, or a form to be evaluated.
  1113. An entry that is just a list with a single string will be interpreted
  1114. as a descriptive headline that will be added when listing the speed
  1115. commands in the Help buffer using the `?' speed command."
  1116. :group 'org-structure
  1117. :type '(repeat :value ("k" . ignore)
  1118. (choice :value ("k" . ignore)
  1119. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1120. (cons :tag "Letter and Command"
  1121. (string :tag "Command letter")
  1122. (choice
  1123. (function)
  1124. (sexp))))))
  1125. (defcustom org-bookmark-names-plist
  1126. '(:last-capture "org-capture-last-stored"
  1127. :last-refile "org-refile-last-stored"
  1128. :last-capture-marker "org-capture-last-stored-marker")
  1129. "Names for bookmarks automatically set by some Org commands.
  1130. This can provide strings as names for a number of bookmarks Org sets
  1131. automatically. The following keys are currently implemented:
  1132. :last-capture
  1133. :last-capture-marker
  1134. :last-refile
  1135. When a key does not show up in the property list, the corresponding bookmark
  1136. is not set."
  1137. :group 'org-structure
  1138. :type 'plist)
  1139. (defgroup org-cycle nil
  1140. "Options concerning visibility cycling in Org mode."
  1141. :tag "Org Cycle"
  1142. :group 'org-structure)
  1143. (defcustom org-cycle-skip-children-state-if-no-children t
  1144. "Non-nil means skip CHILDREN state in entries that don't have any."
  1145. :group 'org-cycle
  1146. :type 'boolean)
  1147. (defcustom org-cycle-max-level nil
  1148. "Maximum level which should still be subject to visibility cycling.
  1149. Levels higher than this will, for cycling, be treated as text, not a headline.
  1150. When `org-odd-levels-only' is set, a value of N in this variable actually
  1151. means 2N-1 stars as the limiting headline.
  1152. When nil, cycle all levels.
  1153. Note that the limiting level of cycling is also influenced by
  1154. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1155. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1156. than its value."
  1157. :group 'org-cycle
  1158. :type '(choice
  1159. (const :tag "No limit" nil)
  1160. (integer :tag "Maximum level")))
  1161. (defcustom org-hide-block-startup nil
  1162. "Non-nil means entering Org mode will fold all blocks.
  1163. This can also be set in on a per-file basis with
  1164. #+STARTUP: hideblocks
  1165. #+STARTUP: showblocks"
  1166. :group 'org-startup
  1167. :group 'org-cycle
  1168. :type 'boolean)
  1169. (defcustom org-cycle-global-at-bob nil
  1170. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1171. This makes it possible to do global cycling without having to use `S-TAB'
  1172. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1173. line of the buffer
  1174. must not be a headline -- it may be empty or some other text.
  1175. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1176. sure the cursor stays at the beginning of the buffer.
  1177. When this option is nil, don't do anything special at the beginning of
  1178. the buffer."
  1179. :group 'org-cycle
  1180. :type 'boolean)
  1181. (defcustom org-cycle-level-after-item/entry-creation t
  1182. "Non-nil means cycle entry level or item indentation in new empty entries.
  1183. When the cursor is at the end of an empty headline, i.e., with only stars
  1184. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1185. and then all possible ancestor states, before returning to the original state.
  1186. This makes data entry extremely fast: M-RET to create a new headline,
  1187. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1188. When the cursor is at the end of an empty plain list item, one TAB will
  1189. make it a subitem, two or more tabs will back up to make this an item
  1190. higher up in the item hierarchy."
  1191. :group 'org-cycle
  1192. :type 'boolean)
  1193. (defcustom org-cycle-emulate-tab t
  1194. "Where should `org-cycle' emulate TAB.
  1195. nil Never
  1196. white Only in completely white lines
  1197. whitestart Only at the beginning of lines, before the first non-white char
  1198. t Everywhere except in headlines
  1199. exc-hl-bol Everywhere except at the start of a headline
  1200. If TAB is used in a place where it does not emulate TAB, the current subtree
  1201. visibility is cycled."
  1202. :group 'org-cycle
  1203. :type '(choice (const :tag "Never" nil)
  1204. (const :tag "Only in completely white lines" white)
  1205. (const :tag "Before first char in a line" whitestart)
  1206. (const :tag "Everywhere except in headlines" t)
  1207. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1208. (defcustom org-cycle-separator-lines 2
  1209. "Number of empty lines needed to keep an empty line between collapsed trees.
  1210. If you leave an empty line between the end of a subtree and the following
  1211. headline, this empty line is hidden when the subtree is folded.
  1212. Org mode will leave (exactly) one empty line visible if the number of
  1213. empty lines is equal or larger to the number given in this variable.
  1214. So the default 2 means at least 2 empty lines after the end of a subtree
  1215. are needed to produce free space between a collapsed subtree and the
  1216. following headline.
  1217. If the number is negative, and the number of empty lines is at least -N,
  1218. all empty lines are shown.
  1219. Special case: when 0, never leave empty lines in collapsed view."
  1220. :group 'org-cycle
  1221. :type 'integer)
  1222. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1223. (defcustom org-pre-cycle-hook nil
  1224. "Hook that is run before visibility cycling is happening.
  1225. The function(s) in this hook must accept a single argument which indicates
  1226. the new state that will be set right after running this hook. The
  1227. argument is a symbol. Before a global state change, it can have the values
  1228. `overview', `content', or `all'. Before a local state change, it can have
  1229. the values `folded', `children', or `subtree'."
  1230. :group 'org-cycle
  1231. :type 'hook)
  1232. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1233. org-cycle-show-empty-lines
  1234. org-optimize-window-after-visibility-change)
  1235. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1236. The function(s) in this hook must accept a single argument which indicates
  1237. the new state that was set by the most recent `org-cycle' command. The
  1238. argument is a symbol. After a global state change, it can have the values
  1239. `overview', `contents', or `all'. After a local state change, it can have
  1240. the values `folded', `children', or `subtree'."
  1241. :group 'org-cycle
  1242. :type 'hook
  1243. :version "26.1"
  1244. :package-version '(Org . "8.3"))
  1245. (defgroup org-edit-structure nil
  1246. "Options concerning structure editing in Org mode."
  1247. :tag "Org Edit Structure"
  1248. :group 'org-structure)
  1249. (defcustom org-odd-levels-only nil
  1250. "Non-nil means skip even levels and only use odd levels for the outline.
  1251. This has the effect that two stars are being added/taken away in
  1252. promotion/demotion commands. It also influences how levels are
  1253. handled by the exporters.
  1254. Changing it requires restart of `font-lock-mode' to become effective
  1255. for fontification also in regions already fontified.
  1256. You may also set this on a per-file basis by adding one of the following
  1257. lines to the buffer:
  1258. #+STARTUP: odd
  1259. #+STARTUP: oddeven"
  1260. :group 'org-edit-structure
  1261. :group 'org-appearance
  1262. :type 'boolean)
  1263. (defcustom org-adapt-indentation t
  1264. "Non-nil means adapt indentation to outline node level.
  1265. When this variable is set, Org assumes that you write outlines by
  1266. indenting text in each node to align with the headline (after the
  1267. stars). The following issues are influenced by this variable:
  1268. - The indentation is increased by one space in a demotion
  1269. command, and decreased by one in a promotion command. However,
  1270. in the latter case, if shifting some line in the entry body
  1271. would alter document structure (e.g., insert a new headline),
  1272. indentation is not changed at all.
  1273. - Property drawers and planning information is inserted indented
  1274. when this variable is set. When nil, they will not be indented.
  1275. - TAB indents a line relative to current level. The lines below
  1276. a headline will be indented when this variable is set.
  1277. Note that this is all about true indentation, by adding and
  1278. removing space characters. See also \"org-indent.el\" which does
  1279. level-dependent indentation in a virtual way, i.e. at display
  1280. time in Emacs."
  1281. :group 'org-edit-structure
  1282. :type 'boolean
  1283. :safe #'booleanp)
  1284. (defcustom org-special-ctrl-a/e nil
  1285. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1286. When t, `C-a' will bring back the cursor to the beginning of the
  1287. headline text, i.e. after the stars and after a possible TODO
  1288. keyword. In an item, this will be the position after bullet and
  1289. check-box, if any. When the cursor is already at that position,
  1290. another `C-a' will bring it to the beginning of the line.
  1291. `C-e' will jump to the end of the headline, ignoring the presence
  1292. of tags in the headline. A second `C-e' will then jump to the
  1293. true end of the line, after any tags. This also means that, when
  1294. this variable is non-nil, `C-e' also will never jump beyond the
  1295. end of the heading of a folded section, i.e. not after the
  1296. ellipses.
  1297. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1298. normally, going to the true line boundary first. Only a directly
  1299. following, identical keypress will bring the cursor to the
  1300. special positions.
  1301. This may also be a cons cell where the behavior for `C-a' and
  1302. `C-e' is set separately."
  1303. :group 'org-edit-structure
  1304. :type '(choice
  1305. (const :tag "off" nil)
  1306. (const :tag "on: after stars/bullet and before tags first" t)
  1307. (const :tag "reversed: true line boundary first" reversed)
  1308. (cons :tag "Set C-a and C-e separately"
  1309. (choice :tag "Special C-a"
  1310. (const :tag "off" nil)
  1311. (const :tag "on: after stars/bullet first" t)
  1312. (const :tag "reversed: before stars/bullet first" reversed))
  1313. (choice :tag "Special C-e"
  1314. (const :tag "off" nil)
  1315. (const :tag "on: before tags first" t)
  1316. (const :tag "reversed: after tags first" reversed)))))
  1317. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1318. (defcustom org-special-ctrl-k nil
  1319. "Non-nil means `C-k' will behave specially in headlines.
  1320. When nil, `C-k' will call the default `kill-line' command.
  1321. When t, the following will happen while the cursor is in the headline:
  1322. - When the cursor is at the beginning of a headline, kill the entire
  1323. line and possible the folded subtree below the line.
  1324. - When in the middle of the headline text, kill the headline up to the tags.
  1325. - When after the headline text, kill the tags."
  1326. :group 'org-edit-structure
  1327. :type 'boolean)
  1328. (defcustom org-ctrl-k-protect-subtree nil
  1329. "Non-nil means, do not delete a hidden subtree with C-k.
  1330. When set to the symbol `error', simply throw an error when C-k is
  1331. used to kill (part-of) a headline that has hidden text behind it.
  1332. Any other non-nil value will result in a query to the user, if it is
  1333. OK to kill that hidden subtree. When nil, kill without remorse."
  1334. :group 'org-edit-structure
  1335. :version "24.1"
  1336. :type '(choice
  1337. (const :tag "Do not protect hidden subtrees" nil)
  1338. (const :tag "Protect hidden subtrees with a security query" t)
  1339. (const :tag "Never kill a hidden subtree with C-k" error)))
  1340. (defcustom org-special-ctrl-o t
  1341. "Non-nil means, make `C-o' insert a row in tables."
  1342. :group 'org-edit-structure
  1343. :type 'boolean)
  1344. (defcustom org-catch-invisible-edits nil
  1345. "Check if in invisible region before inserting or deleting a character.
  1346. Valid values are:
  1347. nil Do not check, so just do invisible edits.
  1348. error Throw an error and do nothing.
  1349. show Make point visible, and do the requested edit.
  1350. show-and-error Make point visible, then throw an error and abort the edit.
  1351. smart Make point visible, and do insertion/deletion if it is
  1352. adjacent to visible text and the change feels predictable.
  1353. Never delete a previously invisible character or add in the
  1354. middle or right after an invisible region. Basically, this
  1355. allows insertion and backward-delete right before ellipses.
  1356. FIXME: maybe in this case we should not even show?"
  1357. :group 'org-edit-structure
  1358. :version "24.1"
  1359. :type '(choice
  1360. (const :tag "Do not check" nil)
  1361. (const :tag "Throw error when trying to edit" error)
  1362. (const :tag "Unhide, but do not do the edit" show-and-error)
  1363. (const :tag "Show invisible part and do the edit" show)
  1364. (const :tag "Be smart and do the right thing" smart)))
  1365. (defcustom org-yank-folded-subtrees t
  1366. "Non-nil means when yanking subtrees, fold them.
  1367. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1368. it starts with a heading and all other headings in it are either children
  1369. or siblings, then fold all the subtrees. However, do this only if no
  1370. text after the yank would be swallowed into a folded tree by this action."
  1371. :group 'org-edit-structure
  1372. :type 'boolean)
  1373. (defcustom org-yank-adjusted-subtrees nil
  1374. "Non-nil means when yanking subtrees, adjust the level.
  1375. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1376. this function for details."
  1377. :group 'org-edit-structure
  1378. :type 'boolean)
  1379. (defcustom org-M-RET-may-split-line '((default . t))
  1380. "Non-nil means M-RET will split the line at the cursor position.
  1381. When nil, it will go to the end of the line before making a
  1382. new line.
  1383. You may also set this option in a different way for different
  1384. contexts. Valid contexts are:
  1385. headline when creating a new headline
  1386. item when creating a new item
  1387. table in a table field
  1388. default the value to be used for all contexts not explicitly
  1389. customized"
  1390. :group 'org-structure
  1391. :group 'org-table
  1392. :type '(choice
  1393. (const :tag "Always" t)
  1394. (const :tag "Never" nil)
  1395. (repeat :greedy t :tag "Individual contexts"
  1396. (cons
  1397. (choice :tag "Context"
  1398. (const headline)
  1399. (const item)
  1400. (const table)
  1401. (const default))
  1402. (boolean)))))
  1403. (defcustom org-insert-heading-respect-content nil
  1404. "Non-nil means insert new headings after the current subtree.
  1405. \\<org-mode-map>
  1406. When nil, the new heading is created directly after the current line.
  1407. The commands `\\[org-insert-heading-respect-content]' and \
  1408. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1409. for the duration of the command."
  1410. :group 'org-structure
  1411. :type 'boolean)
  1412. (defcustom org-blank-before-new-entry '((heading . auto)
  1413. (plain-list-item . auto))
  1414. "Should `org-insert-heading' leave a blank line before new heading/item?
  1415. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1416. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1417. which case Org will look at the surrounding headings/items and try to
  1418. make an intelligent decision whether to insert a blank line or not."
  1419. :group 'org-edit-structure
  1420. :type '(list
  1421. (cons (const heading)
  1422. (choice (const :tag "Never" nil)
  1423. (const :tag "Always" t)
  1424. (const :tag "Auto" auto)))
  1425. (cons (const plain-list-item)
  1426. (choice (const :tag "Never" nil)
  1427. (const :tag "Always" t)
  1428. (const :tag "Auto" auto)))))
  1429. (defcustom org-insert-heading-hook nil
  1430. "Hook being run after inserting a new heading."
  1431. :group 'org-edit-structure
  1432. :type 'hook)
  1433. (defcustom org-enable-fixed-width-editor t
  1434. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1435. This currently only means they are never auto-wrapped.
  1436. When nil, such lines will be treated like ordinary lines."
  1437. :group 'org-edit-structure
  1438. :type 'boolean)
  1439. (defgroup org-sparse-trees nil
  1440. "Options concerning sparse trees in Org mode."
  1441. :tag "Org Sparse Trees"
  1442. :group 'org-structure)
  1443. (defcustom org-highlight-sparse-tree-matches t
  1444. "Non-nil means highlight all matches that define a sparse tree.
  1445. The highlights will automatically disappear the next time the buffer is
  1446. changed by an edit command."
  1447. :group 'org-sparse-trees
  1448. :type 'boolean)
  1449. (defcustom org-remove-highlights-with-change t
  1450. "Non-nil means any change to the buffer will remove temporary highlights.
  1451. \\<org-mode-map>\
  1452. Such highlights are created by `org-occur' and `org-clock-display'.
  1453. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1454. to get rid of the highlights.
  1455. The highlights created by `org-toggle-latex-fragment' always need
  1456. `\\[org-toggle-latex-fragment]' to be removed."
  1457. :group 'org-sparse-trees
  1458. :group 'org-time
  1459. :type 'boolean)
  1460. (defcustom org-occur-case-fold-search t
  1461. "Non-nil means `org-occur' should be case-insensitive.
  1462. If set to `smart' the search will be case-insensitive only if it
  1463. doesn't specify any upper case character."
  1464. :group 'org-sparse-trees
  1465. :version "26.1"
  1466. :type '(choice
  1467. (const :tag "Case-sensitive" nil)
  1468. (const :tag "Case-insensitive" t)
  1469. (const :tag "Case-insensitive for lower case searches only" smart)))
  1470. (defcustom org-occur-hook '(org-first-headline-recenter)
  1471. "Hook that is run after `org-occur' has constructed a sparse tree.
  1472. This can be used to recenter the window to show as much of the structure
  1473. as possible."
  1474. :group 'org-sparse-trees
  1475. :type 'hook)
  1476. (defgroup org-table nil
  1477. "Options concerning tables in Org mode."
  1478. :tag "Org Table"
  1479. :group 'org)
  1480. (defcustom org-self-insert-cluster-for-undo nil
  1481. "Non-nil means cluster self-insert commands for undo when possible.
  1482. If this is set, then, like in the Emacs command loop, 20 consecutive
  1483. characters will be undone together.
  1484. This is configurable, because there is some impact on typing performance."
  1485. :group 'org-table
  1486. :type 'boolean)
  1487. (defcustom org-table-tab-recognizes-table.el t
  1488. "Non-nil means TAB will automatically notice a table.el table.
  1489. When it sees such a table, it moves point into it and - if necessary -
  1490. calls `table-recognize-table'."
  1491. :group 'org-table-editing
  1492. :type 'boolean)
  1493. (defgroup org-link nil
  1494. "Options concerning links in Org mode."
  1495. :tag "Org Link"
  1496. :group 'org)
  1497. (defvar-local org-link-abbrev-alist-local nil
  1498. "Buffer-local version of `org-link-abbrev-alist', which see.
  1499. The value of this is taken from the #+LINK lines.")
  1500. (defcustom org-link-parameters
  1501. '(("doi" :follow org--open-doi-link)
  1502. ("elisp" :follow org--open-elisp-link)
  1503. ("file" :complete org-file-complete-link)
  1504. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1505. ("help" :follow org--open-help-link)
  1506. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1507. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1508. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1509. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1510. ("shell" :follow org--open-shell-link))
  1511. "An alist of properties that defines all the links in Org mode.
  1512. The key in each association is a string of the link type.
  1513. Subsequent optional elements make up a p-list of link properties.
  1514. :follow - A function that takes the link path as an argument.
  1515. :export - A function that takes the link path, description and
  1516. export-backend as arguments.
  1517. :store - A function responsible for storing the link. See the
  1518. function `org-store-link-functions'.
  1519. :complete - A function that inserts a link with completion. The
  1520. function takes one optional prefix arg.
  1521. :face - A face for the link, or a function that returns a face.
  1522. The function takes one argument which is the link path. The
  1523. default face is `org-link'.
  1524. :mouse-face - The mouse-face. The default is `highlight'.
  1525. :display - `full' will not fold the link in descriptive
  1526. display. Default is `org-link'.
  1527. :help-echo - A string or function that takes (window object position)
  1528. as arguments and returns a string.
  1529. :keymap - A keymap that is active on the link. The default is
  1530. `org-mouse-map'.
  1531. :htmlize-link - A function for the htmlize-link. Defaults
  1532. to (list :uri \"type:path\")
  1533. :activate-func - A function to run at the end of font-lock
  1534. activation. The function must accept (link-start link-end path bracketp)
  1535. as arguments."
  1536. :group 'org-link
  1537. :type '(alist :tag "Link display parameters"
  1538. :value-type plist)
  1539. :version "26.1"
  1540. :package-version '(Org . "9.1"))
  1541. (defun org-link-get-parameter (type key)
  1542. "Get TYPE link property for KEY.
  1543. TYPE is a string and KEY is a plist keyword."
  1544. (plist-get
  1545. (cdr (assoc type org-link-parameters))
  1546. key))
  1547. (defun org-link-set-parameters (type &rest parameters)
  1548. "Set link TYPE properties to PARAMETERS.
  1549. PARAMETERS should be :key val pairs."
  1550. (let ((data (assoc type org-link-parameters)))
  1551. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1552. (push (cons type parameters) org-link-parameters)
  1553. (org-make-link-regexps)
  1554. (org-element-update-syntax))))
  1555. (defun org-link-types ()
  1556. "Return a list of known link types."
  1557. (mapcar #'car org-link-parameters))
  1558. (defcustom org-link-abbrev-alist nil
  1559. "Alist of link abbreviations.
  1560. The car of each element is a string, to be replaced at the start of a link.
  1561. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1562. links in Org buffers can have an optional tag after a double colon, e.g.,
  1563. [[linkkey:tag][description]]
  1564. The `linkkey' must be a single word, starting with a letter, followed
  1565. by letters, numbers, `-' or `_'.
  1566. If REPLACE is a string, the tag will simply be appended to create the link.
  1567. If the string contains \"%s\", the tag will be inserted there. If the string
  1568. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1569. at that point (see the function `url-hexify-string'). If the string contains
  1570. the specifier \"%(my-function)\", then the custom function `my-function' will
  1571. be invoked: this function takes the tag as its only argument and must return
  1572. a string.
  1573. REPLACE may also be a function that will be called with the tag as the
  1574. only argument to create the link, which should be returned as a string.
  1575. See the manual for examples."
  1576. :group 'org-link
  1577. :type '(repeat
  1578. (cons
  1579. (string :tag "Protocol")
  1580. (choice
  1581. (string :tag "Format")
  1582. (function)))))
  1583. (defcustom org-descriptive-links t
  1584. "Non-nil means Org will display descriptive links.
  1585. E.g. [[https://orgmode.org][Org website]] will be displayed as
  1586. \"Org Website\", hiding the link itself and just displaying its
  1587. description. When set to nil, Org will display the full links
  1588. literally.
  1589. You can interactively set the value of this variable by calling
  1590. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1591. :group 'org-link
  1592. :type 'boolean)
  1593. (defcustom org-link-file-path-type 'adaptive
  1594. "How the path name in file links should be stored.
  1595. Valid values are:
  1596. relative Relative to the current directory, i.e. the directory of the file
  1597. into which the link is being inserted.
  1598. absolute Absolute path, if possible with ~ for home directory.
  1599. noabbrev Absolute path, no abbreviation of home directory.
  1600. adaptive Use relative path for files in the current directory and sub-
  1601. directories of it. For other files, use an absolute path."
  1602. :group 'org-link
  1603. :type '(choice
  1604. (const relative)
  1605. (const absolute)
  1606. (const noabbrev)
  1607. (const adaptive)))
  1608. (defvaralias 'org-activate-links 'org-highlight-links)
  1609. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1610. "Types of links that should be highlighted in Org files.
  1611. This is a list of symbols, each one of them leading to the
  1612. highlighting of a certain link type.
  1613. You can still open links that are not highlighted.
  1614. In principle, it does not hurt to turn on highlighting for all
  1615. link types. There may be a small gain when turning off unused
  1616. link types. The types are:
  1617. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1618. angle Links in angular brackets that may contain whitespace like
  1619. <bbdb:Carsten Dominik>.
  1620. plain Plain links in normal text, no whitespace, like http://google.com.
  1621. radio Text that is matched by a radio target, see manual for details.
  1622. tag Tag settings in a headline (link to tag search).
  1623. date Time stamps (link to calendar).
  1624. footnote Footnote labels.
  1625. If you set this variable during an Emacs session, use `org-mode-restart'
  1626. in the Org buffer so that the change takes effect."
  1627. :group 'org-link
  1628. :group 'org-appearance
  1629. :type '(set :greedy t
  1630. (const :tag "Double bracket links" bracket)
  1631. (const :tag "Angular bracket links" angle)
  1632. (const :tag "Plain text links" plain)
  1633. (const :tag "Radio target matches" radio)
  1634. (const :tag "Tags" tag)
  1635. (const :tag "Timestamps" date)
  1636. (const :tag "Footnotes" footnote)))
  1637. (defcustom org-make-link-description-function nil
  1638. "Function to use for generating link descriptions from links.
  1639. This function must take two parameters: the first one is the
  1640. link, the second one is the description generated by
  1641. `org-insert-link'. The function should return the description to
  1642. use."
  1643. :group 'org-link
  1644. :type '(choice (const nil) (function)))
  1645. (defgroup org-link-store nil
  1646. "Options concerning storing links in Org mode."
  1647. :tag "Org Store Link"
  1648. :group 'org-link)
  1649. (defcustom org-url-hexify-p t
  1650. "When non-nil, hexify URL when creating a link."
  1651. :type 'boolean
  1652. :version "24.3"
  1653. :group 'org-link-store)
  1654. (defcustom org-email-link-description-format "Email %c: %.30s"
  1655. "Format of the description part of a link to an email or usenet message.
  1656. The following %-escapes will be replaced by corresponding information:
  1657. %F full \"From\" field
  1658. %f name, taken from \"From\" field, address if no name
  1659. %T full \"To\" field
  1660. %t first name in \"To\" field, address if no name
  1661. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1662. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1663. %s subject
  1664. %d date
  1665. %m message-id.
  1666. You may use normal field width specification between the % and the letter.
  1667. This is for example useful to limit the length of the subject.
  1668. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1669. :group 'org-link-store
  1670. :type 'string)
  1671. (defcustom org-from-is-user-regexp
  1672. (let (r1 r2)
  1673. (when (and user-mail-address (not (string= user-mail-address "")))
  1674. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1675. (when (and user-full-name (not (string= user-full-name "")))
  1676. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1677. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1678. "Regexp matched against the \"From:\" header of an email or usenet message.
  1679. It should match if the message is from the user him/herself."
  1680. :group 'org-link-store
  1681. :type 'regexp)
  1682. (defcustom org-context-in-file-links t
  1683. "Non-nil means file links from `org-store-link' contain context.
  1684. \\<org-mode-map>
  1685. A search string will be added to the file name with :: as separator
  1686. and used to find the context when the link is activated by the command
  1687. `org-open-at-point'. When this option is t, the entire active region
  1688. will be placed in the search string of the file link. If set to a
  1689. positive integer, only the first n lines of context will be stored.
  1690. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1691. \\[org-store-link]')
  1692. negates this setting for the duration of the command."
  1693. :group 'org-link-store
  1694. :type '(choice boolean integer))
  1695. (defcustom org-keep-stored-link-after-insertion nil
  1696. "Non-nil means keep link in list for entire session.
  1697. \\<org-mode-map>
  1698. The command `org-store-link' adds a link pointing to the current
  1699. location to an internal list. These links accumulate during a session.
  1700. The command `org-insert-link' can be used to insert links into any
  1701. Org file (offering completion for all stored links).
  1702. When this option is nil, every link which has been inserted once using
  1703. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1704. unused
  1705. links more efficient."
  1706. :group 'org-link-store
  1707. :type 'boolean)
  1708. (defgroup org-link-follow nil
  1709. "Options concerning following links in Org mode."
  1710. :tag "Org Follow Link"
  1711. :group 'org-link)
  1712. (defcustom org-link-translation-function nil
  1713. "Function to translate links with different syntax to Org syntax.
  1714. This can be used to translate links created for example by the Planner
  1715. or emacs-wiki packages to Org syntax.
  1716. The function must accept two parameters, a TYPE containing the link
  1717. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1718. which is everything after the link protocol. It should return a cons
  1719. with possibly modified values of type and path.
  1720. Org contains a function for this, so if you set this variable to
  1721. `org-translate-link-from-planner', you should be able follow many
  1722. links created by planner."
  1723. :group 'org-link-follow
  1724. :type '(choice (const nil) (function)))
  1725. (defcustom org-follow-link-hook nil
  1726. "Hook that is run after a link has been followed."
  1727. :group 'org-link-follow
  1728. :type 'hook)
  1729. (defcustom org-tab-follows-link nil
  1730. "Non-nil means on links TAB will follow the link.
  1731. Needs to be set before org.el is loaded.
  1732. This really should not be used, it does not make sense, and the
  1733. implementation is bad."
  1734. :group 'org-link-follow
  1735. :type 'boolean)
  1736. (defcustom org-return-follows-link nil
  1737. "Non-nil means on links RET will follow the link.
  1738. In tables, the special behavior of RET has precedence."
  1739. :group 'org-link-follow
  1740. :type 'boolean)
  1741. (defcustom org-mouse-1-follows-link
  1742. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1743. "Non-nil means mouse-1 on a link will follow the link.
  1744. A longer mouse click will still set point. Needs to be set
  1745. before org.el is loaded."
  1746. :group 'org-link-follow
  1747. :version "26.1"
  1748. :package-version '(Org . "8.3")
  1749. :type '(choice
  1750. (const :tag "A double click follows the link" double)
  1751. (const :tag "Unconditionally follow the link with mouse-1" t)
  1752. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1753. (defcustom org-mark-ring-length 4
  1754. "Number of different positions to be recorded in the ring.
  1755. Changing this requires a restart of Emacs to work correctly."
  1756. :group 'org-link-follow
  1757. :type 'integer)
  1758. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1759. "Non-nil means internal fuzzy links can only match headlines.
  1760. When nil, the a fuzzy link may point to a target or a named
  1761. construct in the document. When set to the special value
  1762. `query-to-create', offer to create a new headline when none
  1763. matched.
  1764. Spaces and statistics cookies are ignored during heading searches."
  1765. :group 'org-link-follow
  1766. :version "24.1"
  1767. :type '(choice
  1768. (const :tag "Use fuzzy text search" nil)
  1769. (const :tag "Match only exact headline" t)
  1770. (const :tag "Match exact headline or query to create it"
  1771. query-to-create))
  1772. :safe #'symbolp)
  1773. (defcustom org-link-frame-setup
  1774. '((vm . vm-visit-folder-other-frame)
  1775. (vm-imap . vm-visit-imap-folder-other-frame)
  1776. (gnus . org-gnus-no-new-news)
  1777. (file . find-file-other-window)
  1778. (wl . wl-other-frame))
  1779. "Setup the frame configuration for following links.
  1780. When following a link with Emacs, it may often be useful to display
  1781. this link in another window or frame. This variable can be used to
  1782. set this up for the different types of links.
  1783. For VM, use any of
  1784. `vm-visit-folder'
  1785. `vm-visit-folder-other-window'
  1786. `vm-visit-folder-other-frame'
  1787. For Gnus, use any of
  1788. `gnus'
  1789. `gnus-other-frame'
  1790. `org-gnus-no-new-news'
  1791. For FILE, use any of
  1792. `find-file'
  1793. `find-file-other-window'
  1794. `find-file-other-frame'
  1795. For Wanderlust use any of
  1796. `wl'
  1797. `wl-other-frame'
  1798. For the calendar, use the variable `calendar-setup'.
  1799. For BBDB, it is currently only possible to display the matches in
  1800. another window."
  1801. :group 'org-link-follow
  1802. :type '(list
  1803. (cons (const vm)
  1804. (choice
  1805. (const vm-visit-folder)
  1806. (const vm-visit-folder-other-window)
  1807. (const vm-visit-folder-other-frame)))
  1808. (cons (const vm-imap)
  1809. (choice
  1810. (const vm-visit-imap-folder)
  1811. (const vm-visit-imap-folder-other-window)
  1812. (const vm-visit-imap-folder-other-frame)))
  1813. (cons (const gnus)
  1814. (choice
  1815. (const gnus)
  1816. (const gnus-other-frame)
  1817. (const org-gnus-no-new-news)))
  1818. (cons (const file)
  1819. (choice
  1820. (const find-file)
  1821. (const find-file-other-window)
  1822. (const find-file-other-frame)))
  1823. (cons (const wl)
  1824. (choice
  1825. (const wl)
  1826. (const wl-other-frame)))))
  1827. (defcustom org-display-internal-link-with-indirect-buffer nil
  1828. "Non-nil means use indirect buffer to display infile links.
  1829. Activating internal links (from one location in a file to another location
  1830. in the same file) normally just jumps to the location. When the link is
  1831. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1832. is displayed in
  1833. another window. When this option is set, the other window actually displays
  1834. an indirect buffer clone of the current buffer, to avoid any visibility
  1835. changes to the current buffer."
  1836. :group 'org-link-follow
  1837. :type 'boolean)
  1838. (defcustom org-open-non-existing-files nil
  1839. "Non-nil means `org-open-file' will open non-existing files.
  1840. When nil, an error will be generated.
  1841. This variable applies only to external applications because they
  1842. might choke on non-existing files. If the link is to a file that
  1843. will be opened in Emacs, the variable is ignored."
  1844. :group 'org-link-follow
  1845. :type 'boolean)
  1846. (defcustom org-open-directory-means-index-dot-org nil
  1847. "Non-nil means a link to a directory really means to index.org.
  1848. When nil, following a directory link will run dired or open a finder/explorer
  1849. window on that directory."
  1850. :group 'org-link-follow
  1851. :type 'boolean)
  1852. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1853. "Non-nil means ask for confirmation before executing shell links.
  1854. Shell links can be dangerous: just think about a link
  1855. [[shell:rm -rf ~/*][Google Search]]
  1856. This link would show up in your Org document as \"Google Search\",
  1857. but really it would remove your entire home directory.
  1858. Therefore we advise against setting this variable to nil.
  1859. Just change it to `y-or-n-p' if you want to confirm with a
  1860. single keystroke rather than having to type \"yes\"."
  1861. :group 'org-link-follow
  1862. :type '(choice
  1863. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1864. (const :tag "with y-or-n (faster)" y-or-n-p)
  1865. (const :tag "no confirmation (dangerous)" nil)))
  1866. (put 'org-confirm-shell-link-function
  1867. 'safe-local-variable
  1868. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1869. (defcustom org-confirm-shell-link-not-regexp ""
  1870. "A regexp to skip confirmation for shell links."
  1871. :group 'org-link-follow
  1872. :version "24.1"
  1873. :type 'regexp)
  1874. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1875. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1876. Elisp links can be dangerous: just think about a link
  1877. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1878. This link would show up in your Org document as \"Google Search\",
  1879. but really it would remove your entire home directory.
  1880. Therefore we advise against setting this variable to nil.
  1881. Just change it to `y-or-n-p' if you want to confirm with a
  1882. single keystroke rather than having to type \"yes\"."
  1883. :group 'org-link-follow
  1884. :type '(choice
  1885. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1886. (const :tag "with y-or-n (faster)" y-or-n-p)
  1887. (const :tag "no confirmation (dangerous)" nil)))
  1888. (put 'org-confirm-shell-link-function
  1889. 'safe-local-variable
  1890. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1891. (defcustom org-confirm-elisp-link-not-regexp ""
  1892. "A regexp to skip confirmation for Elisp links."
  1893. :group 'org-link-follow
  1894. :version "24.1"
  1895. :type 'regexp)
  1896. (defconst org-file-apps-defaults-gnu
  1897. '((remote . emacs)
  1898. (system . mailcap)
  1899. (t . mailcap))
  1900. "Default file applications on a UNIX or GNU/Linux system.
  1901. See `org-file-apps'.")
  1902. (defconst org-file-apps-defaults-macosx
  1903. '((remote . emacs)
  1904. (system . "open %s")
  1905. ("ps.gz" . "gv %s")
  1906. ("eps.gz" . "gv %s")
  1907. ("dvi" . "xdvi %s")
  1908. ("fig" . "xfig %s")
  1909. (t . "open %s"))
  1910. "Default file applications on a macOS system.
  1911. The system \"open\" is known as a default, but we use X11 applications
  1912. for some files for which the OS does not have a good default.
  1913. See `org-file-apps'.")
  1914. (defconst org-file-apps-defaults-windowsnt
  1915. (list '(remote . emacs)
  1916. (cons 'system (lambda (file _path)
  1917. (with-no-warnings (w32-shell-execute "open" file))))
  1918. (cons t (lambda (file _path)
  1919. (with-no-warnings (w32-shell-execute "open" file)))))
  1920. "Default file applications on a Windows NT system.
  1921. The system \"open\" is used for most files.
  1922. See `org-file-apps'.")
  1923. (defcustom org-file-apps
  1924. '((auto-mode . emacs)
  1925. ("\\.mm\\'" . default)
  1926. ("\\.x?html?\\'" . default)
  1927. ("\\.pdf\\'" . default))
  1928. "External applications for opening `file:path' items in a document.
  1929. \\<org-mode-map>\
  1930. Org mode uses system defaults for different file types, but
  1931. you can use this variable to set the application for a given file
  1932. extension. The entries in this list are cons cells where the car identifies
  1933. files and the cdr the corresponding command.
  1934. Possible values for the file identifier are:
  1935. \"string\" A string as a file identifier can be interpreted in different
  1936. ways, depending on its contents:
  1937. - Alphanumeric characters only:
  1938. Match links with this file extension.
  1939. Example: (\"pdf\" . \"evince %s\")
  1940. to open PDFs with evince.
  1941. - Regular expression: Match links where the
  1942. filename matches the regexp. If you want to
  1943. use groups here, use shy groups.
  1944. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1945. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1946. to open *.html and *.xhtml with firefox.
  1947. - Regular expression which contains (non-shy) groups:
  1948. Match links where the whole link, including \"::\", and
  1949. anything after that, matches the regexp.
  1950. In a custom command string, %1, %2, etc. are replaced with
  1951. the parts of the link that were matched by the groups.
  1952. For backwards compatibility, if a command string is given
  1953. that does not use any of the group matches, this case is
  1954. handled identically to the second one (i.e. match against
  1955. file name only).
  1956. In a custom function, you can access the group matches with
  1957. (match-string n link).
  1958. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1959. \"evince -p %1 %s\")
  1960. to open [[file:document.pdf::5]] with evince at page 5.
  1961. `directory' Matches a directory
  1962. `remote' Matches a remote file, accessible through tramp or efs.
  1963. Remote files most likely should be visited through Emacs
  1964. because external applications cannot handle such paths.
  1965. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1966. so all files Emacs knows how to handle. Using this with
  1967. command `emacs' will open most files in Emacs. Beware that this
  1968. will also open html files inside Emacs, unless you add
  1969. (\"html\" . default) to the list as well.
  1970. `system' The system command to open files, like `open' on Windows
  1971. and macOS, and mailcap under GNU/Linux. This is the command
  1972. that will be selected if you call `org-open-at-point' with a
  1973. double prefix argument (`\\[universal-argument] \
  1974. \\[universal-argument] \\[org-open-at-point]').
  1975. t Default for files not matched by any of the other options.
  1976. Possible values for the command are:
  1977. `emacs' The file will be visited by the current Emacs process.
  1978. `default' Use the default application for this file type, which is the
  1979. association for t in the list, most likely in the system-specific
  1980. part. This can be used to overrule an unwanted setting in the
  1981. system-specific variable.
  1982. `system' Use the system command for opening files, like \"open\".
  1983. This command is specified by the entry whose car is `system'.
  1984. Most likely, the system-specific version of this variable
  1985. does define this command, but you can overrule/replace it
  1986. here.
  1987. `mailcap' Use command specified in the mailcaps.
  1988. string A command to be executed by a shell; %s will be replaced
  1989. by the path to the file.
  1990. function A Lisp function, which will be called with two arguments:
  1991. the file path and the original link string, without the
  1992. \"file:\" prefix.
  1993. For more examples, see the system specific constants
  1994. `org-file-apps-defaults-macosx'
  1995. `org-file-apps-defaults-windowsnt'
  1996. `org-file-apps-defaults-gnu'."
  1997. :group 'org-link-follow
  1998. :type '(repeat
  1999. (cons (choice :value ""
  2000. (string :tag "Extension")
  2001. (const :tag "System command to open files" system)
  2002. (const :tag "Default for unrecognized files" t)
  2003. (const :tag "Remote file" remote)
  2004. (const :tag "Links to a directory" directory)
  2005. (const :tag "Any files that have Emacs modes"
  2006. auto-mode))
  2007. (choice :value ""
  2008. (const :tag "Visit with Emacs" emacs)
  2009. (const :tag "Use default" default)
  2010. (const :tag "Use the system command" system)
  2011. (string :tag "Command")
  2012. (function :tag "Function")))))
  2013. (defcustom org-doi-server-url "http://dx.doi.org/"
  2014. "The URL of the DOI server."
  2015. :type 'string
  2016. :version "24.3"
  2017. :group 'org-link-follow)
  2018. (defgroup org-refile nil
  2019. "Options concerning refiling entries in Org mode."
  2020. :tag "Org Refile"
  2021. :group 'org)
  2022. (defcustom org-directory "~/org"
  2023. "Directory with Org files.
  2024. This is just a default location to look for Org files. There is no need
  2025. at all to put your files into this directory. It is used in the
  2026. following situations:
  2027. 1. When a capture template specifies a target file that is not an
  2028. absolute path. The path will then be interpreted relative to
  2029. `org-directory'
  2030. 2. When the value of variable `org-agenda-files' is a single file, any
  2031. relative paths in this file will be taken as relative to
  2032. `org-directory'."
  2033. :group 'org-refile
  2034. :group 'org-capture
  2035. :type 'directory)
  2036. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2037. "Default target for storing notes.
  2038. Used as a fall back file for org-capture.el, for templates that
  2039. do not specify a target file."
  2040. :group 'org-refile
  2041. :group 'org-capture
  2042. :type 'file)
  2043. (defcustom org-reverse-note-order nil
  2044. "Non-nil means store new notes at the beginning of a file or entry.
  2045. When nil, new notes will be filed to the end of a file or entry.
  2046. This can also be a list with cons cells of regular expressions that
  2047. are matched against file names, and values."
  2048. :group 'org-capture
  2049. :group 'org-refile
  2050. :type '(choice
  2051. (const :tag "Reverse always" t)
  2052. (const :tag "Reverse never" nil)
  2053. (repeat :tag "By file name regexp"
  2054. (cons regexp boolean))))
  2055. (defcustom org-log-refile nil
  2056. "Information to record when a task is refiled.
  2057. Possible values are:
  2058. nil Don't add anything
  2059. time Add a time stamp to the task
  2060. note Prompt for a note and add it with template `org-log-note-headings'
  2061. This option can also be set with on a per-file-basis with
  2062. #+STARTUP: nologrefile
  2063. #+STARTUP: logrefile
  2064. #+STARTUP: lognoterefile
  2065. You can have local logging settings for a subtree by setting the LOGGING
  2066. property to one or more of these keywords.
  2067. When bulk-refiling from the agenda, the value `note' is forbidden and
  2068. will temporarily be changed to `time'."
  2069. :group 'org-refile
  2070. :group 'org-progress
  2071. :version "24.1"
  2072. :type '(choice
  2073. (const :tag "No logging" nil)
  2074. (const :tag "Record timestamp" time)
  2075. (const :tag "Record timestamp with note." note)))
  2076. (defcustom org-refile-targets nil
  2077. "Targets for refiling entries with `\\[org-refile]'.
  2078. This is a list of cons cells. Each cell contains:
  2079. - a specification of the files to be considered, either a list of files,
  2080. or a symbol whose function or variable value will be used to retrieve
  2081. a file name or a list of file names. If you use `org-agenda-files' for
  2082. that, all agenda files will be scanned for targets. Nil means consider
  2083. headings in the current buffer.
  2084. - A specification of how to find candidate refile targets. This may be
  2085. any of:
  2086. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2087. This tag has to be present in all target headlines, inheritance will
  2088. not be considered.
  2089. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2090. todo keyword.
  2091. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2092. headlines that are refiling targets.
  2093. - a cons cell (:level . N). Any headline of level N is considered a target.
  2094. Note that, when `org-odd-levels-only' is set, level corresponds to
  2095. order in hierarchy, not to the number of stars.
  2096. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2097. Note that, when `org-odd-levels-only' is set, level corresponds to
  2098. order in hierarchy, not to the number of stars.
  2099. Each element of this list generates a set of possible targets.
  2100. The union of these sets is presented (with completion) to
  2101. the user by `org-refile'.
  2102. You can set the variable `org-refile-target-verify-function' to a function
  2103. to verify each headline found by the simple criteria above.
  2104. When this variable is nil, all top-level headlines in the current buffer
  2105. are used, equivalent to the value `((nil . (:level . 1))'."
  2106. :group 'org-refile
  2107. :type '(repeat
  2108. (cons
  2109. (choice :value org-agenda-files
  2110. (const :tag "All agenda files" org-agenda-files)
  2111. (const :tag "Current buffer" nil)
  2112. (function) (variable) (file))
  2113. (choice :tag "Identify target headline by"
  2114. (cons :tag "Specific tag" (const :value :tag) (string))
  2115. (cons :tag "TODO keyword" (const :value :todo) (string))
  2116. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2117. (cons :tag "Level number" (const :value :level) (integer))
  2118. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2119. (defcustom org-refile-target-verify-function nil
  2120. "Function to verify if the headline at point should be a refile target.
  2121. The function will be called without arguments, with point at the
  2122. beginning of the headline. It should return t and leave point
  2123. where it is if the headline is a valid target for refiling.
  2124. If the target should not be selected, the function must return nil.
  2125. In addition to this, it may move point to a place from where the search
  2126. should be continued. For example, the function may decide that the entire
  2127. subtree of the current entry should be excluded and move point to the end
  2128. of the subtree."
  2129. :group 'org-refile
  2130. :type '(choice
  2131. (const nil)
  2132. (function)))
  2133. (defcustom org-refile-use-cache nil
  2134. "Non-nil means cache refile targets to speed up the process.
  2135. \\<org-mode-map>\
  2136. The cache for a particular file will be updated automatically when
  2137. the buffer has been killed, or when any of the marker used for flagging
  2138. refile targets no longer points at a live buffer.
  2139. If you have added new entries to a buffer that might themselves be targets,
  2140. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2141. if you find that easier, \
  2142. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2143. \\[org-refile]'."
  2144. :group 'org-refile
  2145. :version "24.1"
  2146. :type 'boolean)
  2147. (defcustom org-refile-use-outline-path nil
  2148. "Non-nil means provide refile targets as paths.
  2149. So a level 3 headline will be available as level1/level2/level3.
  2150. When the value is `file', also include the file name (without directory)
  2151. into the path. In this case, you can also stop the completion after
  2152. the file name, to get entries inserted as top level in the file.
  2153. When `full-file-path', include the full file path.
  2154. When `buffer-name', use the buffer name."
  2155. :group 'org-refile
  2156. :type '(choice
  2157. (const :tag "Not" nil)
  2158. (const :tag "Yes" t)
  2159. (const :tag "Start with file name" file)
  2160. (const :tag "Start with full file path" full-file-path)
  2161. (const :tag "Start with buffer name" buffer-name)))
  2162. (defcustom org-outline-path-complete-in-steps t
  2163. "Non-nil means complete the outline path in hierarchical steps.
  2164. When Org uses the refile interface to select an outline path (see
  2165. `org-refile-use-outline-path'), the completion of the path can be
  2166. done in a single go, or it can be done in steps down the headline
  2167. hierarchy. Going in steps is probably the best if you do not use
  2168. a special completion package like `ido' or `icicles'. However,
  2169. when using these packages, going in one step can be very fast,
  2170. while still showing the whole path to the entry."
  2171. :group 'org-refile
  2172. :type 'boolean)
  2173. (defcustom org-refile-allow-creating-parent-nodes nil
  2174. "Non-nil means allow the creation of new nodes as refile targets.
  2175. New nodes are then created by adding \"/new node name\" to the completion
  2176. of an existing node. When the value of this variable is `confirm',
  2177. new node creation must be confirmed by the user (recommended).
  2178. When nil, the completion must match an existing entry.
  2179. Note that, if the new heading is not seen by the criteria
  2180. listed in `org-refile-targets', multiple instances of the same
  2181. heading would be created by trying again to file under the new
  2182. heading."
  2183. :group 'org-refile
  2184. :type '(choice
  2185. (const :tag "Never" nil)
  2186. (const :tag "Always" t)
  2187. (const :tag "Prompt for confirmation" confirm)))
  2188. (defcustom org-refile-active-region-within-subtree nil
  2189. "Non-nil means also refile active region within a subtree.
  2190. By default `org-refile' doesn't allow refiling regions if they
  2191. don't contain a set of subtrees, but it might be convenient to
  2192. do so sometimes: in that case, the first line of the region is
  2193. converted to a headline before refiling."
  2194. :group 'org-refile
  2195. :version "24.1"
  2196. :type 'boolean)
  2197. (defgroup org-todo nil
  2198. "Options concerning TODO items in Org mode."
  2199. :tag "Org TODO"
  2200. :group 'org)
  2201. (defgroup org-progress nil
  2202. "Options concerning Progress logging in Org mode."
  2203. :tag "Org Progress"
  2204. :group 'org-time)
  2205. (defvar org-todo-interpretation-widgets
  2206. '((:tag "Sequence (cycling hits every state)" sequence)
  2207. (:tag "Type (cycling directly to DONE)" type))
  2208. "The available interpretation symbols for customizing `org-todo-keywords'.
  2209. Interested libraries should add to this list.")
  2210. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2211. "List of TODO entry keyword sequences and their interpretation.
  2212. \\<org-mode-map>This is a list of sequences.
  2213. Each sequence starts with a symbol, either `sequence' or `type',
  2214. indicating if the keywords should be interpreted as a sequence of
  2215. action steps, or as different types of TODO items. The first
  2216. keywords are states requiring action - these states will select a headline
  2217. for inclusion into the global TODO list Org produces. If one of the
  2218. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2219. signify that no further action is necessary. If \"|\" is not found,
  2220. the last keyword is treated as the only DONE state of the sequence.
  2221. The command `\\[org-todo]' cycles an entry through these states, and one
  2222. additional state where no keyword is present. For details about this
  2223. cycling, see the manual.
  2224. TODO keywords and interpretation can also be set on a per-file basis with
  2225. the special #+SEQ_TODO and #+TYP_TODO lines.
  2226. Each keyword can optionally specify a character for fast state selection
  2227. \(in combination with the variable `org-use-fast-todo-selection')
  2228. and specifiers for state change logging, using the same syntax that
  2229. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2230. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2231. indicates to record a time stamp each time this state is selected.
  2232. Each keyword may also specify if a timestamp or a note should be
  2233. recorded when entering or leaving the state, by adding additional
  2234. characters in the parenthesis after the keyword. This looks like this:
  2235. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2236. record only the time of the state change. With X and Y being either
  2237. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2238. Y when leaving the state if and only if the *target* state does not
  2239. define X. You may omit any of the fast-selection key or X or /Y,
  2240. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2241. For backward compatibility, this variable may also be just a list
  2242. of keywords. In this case the interpretation (sequence or type) will be
  2243. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2244. :group 'org-todo
  2245. :group 'org-keywords
  2246. :type '(choice
  2247. (repeat :tag "Old syntax, just keywords"
  2248. (string :tag "Keyword"))
  2249. (repeat :tag "New syntax"
  2250. (cons
  2251. (choice
  2252. :tag "Interpretation"
  2253. ;;Quick and dirty way to see
  2254. ;;`org-todo-interpretations'. This takes the
  2255. ;;place of item arguments
  2256. :convert-widget
  2257. (lambda (widget)
  2258. (widget-put widget
  2259. :args (mapcar
  2260. (lambda (x)
  2261. (widget-convert
  2262. (cons 'const x)))
  2263. org-todo-interpretation-widgets))
  2264. widget))
  2265. (repeat
  2266. (string :tag "Keyword"))))))
  2267. (defvar-local org-todo-keywords-1 nil
  2268. "All TODO and DONE keywords active in a buffer.")
  2269. (defvar org-todo-keywords-for-agenda nil)
  2270. (defvar org-done-keywords-for-agenda nil)
  2271. (defvar org-todo-keyword-alist-for-agenda nil)
  2272. (defvar org-tag-alist-for-agenda nil
  2273. "Alist of all tags from all agenda files.")
  2274. (defvar org-tag-groups-alist-for-agenda nil
  2275. "Alist of all groups tags from all current agenda files.")
  2276. (defvar-local org-tag-groups-alist nil)
  2277. (defvar org-agenda-contributing-files nil)
  2278. (defvar-local org-current-tag-alist nil
  2279. "Alist of all tag groups in current buffer.
  2280. This variable takes into consideration `org-tag-alist',
  2281. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2282. (defvar-local org-not-done-keywords nil)
  2283. (defvar-local org-done-keywords nil)
  2284. (defvar-local org-todo-heads nil)
  2285. (defvar-local org-todo-sets nil)
  2286. (defvar-local org-todo-log-states nil)
  2287. (defvar-local org-todo-kwd-alist nil)
  2288. (defvar-local org-todo-key-alist nil)
  2289. (defvar-local org-todo-key-trigger nil)
  2290. (defcustom org-todo-interpretation 'sequence
  2291. "Controls how TODO keywords are interpreted.
  2292. This variable is in principle obsolete and is only used for
  2293. backward compatibility, if the interpretation of todo keywords is
  2294. not given already in `org-todo-keywords'. See that variable for
  2295. more information."
  2296. :group 'org-todo
  2297. :group 'org-keywords
  2298. :type '(choice (const sequence)
  2299. (const type)))
  2300. (defcustom org-use-fast-todo-selection t
  2301. "\\<org-mode-map>\
  2302. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2303. This variable describes if and under what circumstances the cycling
  2304. mechanism for TODO keywords will be replaced by a single-key, direct
  2305. selection scheme.
  2306. When nil, fast selection is never used.
  2307. When the symbol `prefix', it will be used when `org-todo' is called
  2308. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2309. in an Org buffer, and
  2310. `\\[universal-argument] t' in an agenda buffer.
  2311. When t, fast selection is used by default. In this case, the prefix
  2312. argument forces cycling instead.
  2313. In all cases, the special interface is only used if access keys have
  2314. actually been assigned by the user, i.e. if keywords in the configuration
  2315. are followed by a letter in parenthesis, like TODO(t)."
  2316. :group 'org-todo
  2317. :type '(choice
  2318. (const :tag "Never" nil)
  2319. (const :tag "By default" t)
  2320. (const :tag "Only with C-u C-c C-t" prefix)))
  2321. (defcustom org-provide-todo-statistics t
  2322. "Non-nil means update todo statistics after insert and toggle.
  2323. ALL-HEADLINES means update todo statistics by including headlines
  2324. with no TODO keyword as well, counting them as not done.
  2325. A list of TODO keywords means the same, but skip keywords that are
  2326. not in this list.
  2327. When set to a list of two lists, the first list contains keywords
  2328. to consider as TODO keywords, the second list contains keywords
  2329. to consider as DONE keywords.
  2330. When this is set, todo statistics is updated in the parent of the
  2331. current entry each time a todo state is changed."
  2332. :group 'org-todo
  2333. :type '(choice
  2334. (const :tag "Yes, only for TODO entries" t)
  2335. (const :tag "Yes, including all entries" all-headlines)
  2336. (repeat :tag "Yes, for TODOs in this list"
  2337. (string :tag "TODO keyword"))
  2338. (list :tag "Yes, for TODOs and DONEs in these lists"
  2339. (repeat (string :tag "TODO keyword"))
  2340. (repeat (string :tag "DONE keyword")))
  2341. (other :tag "No TODO statistics" nil)))
  2342. (defcustom org-hierarchical-todo-statistics t
  2343. "Non-nil means TODO statistics covers just direct children.
  2344. When nil, all entries in the subtree are considered.
  2345. This has only an effect if `org-provide-todo-statistics' is set.
  2346. To set this to nil for only a single subtree, use a COOKIE_DATA
  2347. property and include the word \"recursive\" into the value."
  2348. :group 'org-todo
  2349. :type 'boolean)
  2350. (defcustom org-after-todo-state-change-hook nil
  2351. "Hook which is run after the state of a TODO item was changed.
  2352. The new state (a string with a TODO keyword, or nil) is available in the
  2353. Lisp variable `org-state'."
  2354. :group 'org-todo
  2355. :type 'hook)
  2356. (defvar org-blocker-hook nil
  2357. "Hook for functions that are allowed to block a state change.
  2358. Functions in this hook should not modify the buffer.
  2359. Each function gets as its single argument a property list,
  2360. see `org-trigger-hook' for more information about this list.
  2361. If any of the functions in this hook returns nil, the state change
  2362. is blocked.")
  2363. (defvar org-trigger-hook nil
  2364. "Hook for functions that are triggered by a state change.
  2365. Each function gets as its single argument a property list with at
  2366. least the following elements:
  2367. (:type type-of-change :position pos-at-entry-start
  2368. :from old-state :to new-state)
  2369. Depending on the type, more properties may be present.
  2370. This mechanism is currently implemented for:
  2371. TODO state changes
  2372. ------------------
  2373. :type todo-state-change
  2374. :from previous state (keyword as a string), or nil, or a symbol
  2375. `todo' or `done', to indicate the general type of state.
  2376. :to new state, like in :from")
  2377. (defcustom org-enforce-todo-dependencies nil
  2378. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2379. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2380. be blocked if any prior sibling is not yet done.
  2381. Finally, if the parent is blocked because of ordered siblings of its own,
  2382. the child will also be blocked."
  2383. :set (lambda (var val)
  2384. (set var val)
  2385. (if val
  2386. (add-hook 'org-blocker-hook
  2387. 'org-block-todo-from-children-or-siblings-or-parent)
  2388. (remove-hook 'org-blocker-hook
  2389. 'org-block-todo-from-children-or-siblings-or-parent)))
  2390. :group 'org-todo
  2391. :type 'boolean)
  2392. (defcustom org-enforce-todo-checkbox-dependencies nil
  2393. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2394. When this is nil, checkboxes have no influence on switching TODO states.
  2395. When non-nil, you first need to check off all check boxes before the TODO
  2396. entry can be switched to DONE.
  2397. This variable needs to be set before org.el is loaded, and you need to
  2398. restart Emacs after a change to make the change effective. The only way
  2399. to change is while Emacs is running is through the customize interface."
  2400. :set (lambda (var val)
  2401. (set var val)
  2402. (if val
  2403. (add-hook 'org-blocker-hook
  2404. 'org-block-todo-from-checkboxes)
  2405. (remove-hook 'org-blocker-hook
  2406. 'org-block-todo-from-checkboxes)))
  2407. :group 'org-todo
  2408. :type 'boolean)
  2409. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2410. "Non-nil means inserting a TODO heading is treated as state change.
  2411. So when the command `\\[org-insert-todo-heading]' is used, state change
  2412. logging will apply if appropriate. When nil, the new TODO item will
  2413. be inserted directly, and no logging will take place."
  2414. :group 'org-todo
  2415. :type 'boolean)
  2416. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2417. "Non-nil means switching TODO states with S-cursor counts as state change.
  2418. This is the default behavior. However, setting this to nil allows a
  2419. convenient way to select a TODO state and bypass any logging associated
  2420. with that."
  2421. :group 'org-todo
  2422. :type 'boolean)
  2423. (defcustom org-todo-state-tags-triggers nil
  2424. "Tag changes that should be triggered by TODO state changes.
  2425. This is a list. Each entry is
  2426. (state-change (tag . flag) .......)
  2427. State-change can be a string with a state, and empty string to indicate the
  2428. state that has no TODO keyword, or it can be one of the symbols `todo'
  2429. or `done', meaning any not-done or done state, respectively."
  2430. :group 'org-todo
  2431. :group 'org-tags
  2432. :type '(repeat
  2433. (cons (choice :tag "When changing to"
  2434. (const :tag "Not-done state" todo)
  2435. (const :tag "Done state" done)
  2436. (string :tag "State"))
  2437. (repeat
  2438. (cons :tag "Tag action"
  2439. (string :tag "Tag")
  2440. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2441. (defcustom org-log-done nil
  2442. "Information to record when a task moves to the DONE state.
  2443. Possible values are:
  2444. nil Don't add anything, just change the keyword
  2445. time Add a time stamp to the task
  2446. note Prompt for a note and add it with template `org-log-note-headings'
  2447. This option can also be set with on a per-file-basis with
  2448. #+STARTUP: nologdone
  2449. #+STARTUP: logdone
  2450. #+STARTUP: lognotedone
  2451. You can have local logging settings for a subtree by setting the LOGGING
  2452. property to one or more of these keywords."
  2453. :group 'org-todo
  2454. :group 'org-progress
  2455. :type '(choice
  2456. (const :tag "No logging" nil)
  2457. (const :tag "Record CLOSED timestamp" time)
  2458. (const :tag "Record CLOSED timestamp with note." note)))
  2459. ;; Normalize old uses of org-log-done.
  2460. (cond
  2461. ((eq org-log-done t) (setq org-log-done 'time))
  2462. ((and (listp org-log-done) (memq 'done org-log-done))
  2463. (setq org-log-done 'note)))
  2464. (defcustom org-log-reschedule nil
  2465. "Information to record when the scheduling date of a tasks is modified.
  2466. Possible values are:
  2467. nil Don't add anything, just change the date
  2468. time Add a time stamp to the task
  2469. note Prompt for a note and add it with template `org-log-note-headings'
  2470. This option can also be set with on a per-file-basis with
  2471. #+STARTUP: nologreschedule
  2472. #+STARTUP: logreschedule
  2473. #+STARTUP: lognotereschedule"
  2474. :group 'org-todo
  2475. :group 'org-progress
  2476. :type '(choice
  2477. (const :tag "No logging" nil)
  2478. (const :tag "Record timestamp" time)
  2479. (const :tag "Record timestamp with note." note)))
  2480. (defcustom org-log-redeadline nil
  2481. "Information to record when the deadline date of a tasks is modified.
  2482. Possible values are:
  2483. nil Don't add anything, just change the date
  2484. time Add a time stamp to the task
  2485. note Prompt for a note and add it with template `org-log-note-headings'
  2486. This option can also be set with on a per-file-basis with
  2487. #+STARTUP: nologredeadline
  2488. #+STARTUP: logredeadline
  2489. #+STARTUP: lognoteredeadline
  2490. You can have local logging settings for a subtree by setting the LOGGING
  2491. property to one or more of these keywords."
  2492. :group 'org-todo
  2493. :group 'org-progress
  2494. :type '(choice
  2495. (const :tag "No logging" nil)
  2496. (const :tag "Record timestamp" time)
  2497. (const :tag "Record timestamp with note." note)))
  2498. (defcustom org-log-note-clock-out nil
  2499. "Non-nil means record a note when clocking out of an item.
  2500. This can also be configured on a per-file basis by adding one of
  2501. the following lines anywhere in the buffer:
  2502. #+STARTUP: lognoteclock-out
  2503. #+STARTUP: nolognoteclock-out"
  2504. :group 'org-todo
  2505. :group 'org-progress
  2506. :type 'boolean)
  2507. (defcustom org-log-done-with-time t
  2508. "Non-nil means the CLOSED time stamp will contain date and time.
  2509. When nil, only the date will be recorded."
  2510. :group 'org-progress
  2511. :type 'boolean)
  2512. (defcustom org-log-note-headings
  2513. '((done . "CLOSING NOTE %t")
  2514. (state . "State %-12s from %-12S %t")
  2515. (note . "Note taken on %t")
  2516. (reschedule . "Rescheduled from %S on %t")
  2517. (delschedule . "Not scheduled, was %S on %t")
  2518. (redeadline . "New deadline from %S on %t")
  2519. (deldeadline . "Removed deadline, was %S on %t")
  2520. (refile . "Refiled on %t")
  2521. (clock-out . ""))
  2522. "Headings for notes added to entries.
  2523. The value is an alist, with the car being a symbol indicating the
  2524. note context, and the cdr is the heading to be used. The heading
  2525. may also be the empty string. The following placeholders can be
  2526. used:
  2527. %t a time stamp.
  2528. %T an active time stamp instead the default inactive one
  2529. %d a short-format time stamp.
  2530. %D an active short-format time stamp.
  2531. %s the new TODO state or time stamp (inactive), in double quotes.
  2532. %S the old TODO state or time stamp (inactive), in double quotes.
  2533. %u the user name.
  2534. %U full user name.
  2535. In fact, it is not a good idea to change the `state' entry,
  2536. because Agenda Log mode depends on the format of these entries."
  2537. :group 'org-todo
  2538. :group 'org-progress
  2539. :type '(list :greedy t
  2540. (cons (const :tag "Heading when closing an item" done) string)
  2541. (cons (const :tag
  2542. "Heading when changing todo state (todo sequence only)"
  2543. state) string)
  2544. (cons (const :tag "Heading when just taking a note" note) string)
  2545. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2546. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2547. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2548. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2549. (cons (const :tag "Heading when refiling" refile) string)
  2550. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2551. (unless (assq 'note org-log-note-headings)
  2552. (push '(note . "%t") org-log-note-headings))
  2553. (defcustom org-log-into-drawer nil
  2554. "Non-nil means insert state change notes and time stamps into a drawer.
  2555. When nil, state changes notes will be inserted after the headline and
  2556. any scheduling and clock lines, but not inside a drawer.
  2557. The value of this variable should be the name of the drawer to use.
  2558. LOGBOOK is proposed as the default drawer for this purpose, you can
  2559. also set this to a string to define the drawer of your choice.
  2560. A value of t is also allowed, representing \"LOGBOOK\".
  2561. A value of t or nil can also be set with on a per-file-basis with
  2562. #+STARTUP: logdrawer
  2563. #+STARTUP: nologdrawer
  2564. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2565. will be ignored.
  2566. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2567. a subtree.
  2568. Do not check directly this variable in a Lisp program. Call
  2569. function `org-log-into-drawer' instead."
  2570. :group 'org-todo
  2571. :group 'org-progress
  2572. :type '(choice
  2573. (const :tag "Not into a drawer" nil)
  2574. (const :tag "LOGBOOK" t)
  2575. (string :tag "Other")))
  2576. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2577. (defun org-log-into-drawer ()
  2578. "Name of the log drawer, as a string, or nil.
  2579. This is the value of `org-log-into-drawer'. However, if the
  2580. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2581. be used instead of the default value."
  2582. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2583. (cond ((equal p "nil") nil)
  2584. ((equal p "t") "LOGBOOK")
  2585. ((stringp p) p)
  2586. (p "LOGBOOK")
  2587. ((stringp org-log-into-drawer) org-log-into-drawer)
  2588. (org-log-into-drawer "LOGBOOK"))))
  2589. (defcustom org-log-state-notes-insert-after-drawers nil
  2590. "Non-nil means insert state change notes after any drawers in entry.
  2591. Only the drawers that *immediately* follow the headline and the
  2592. deadline/scheduled line are skipped.
  2593. When nil, insert notes right after the heading and perhaps the line
  2594. with deadline/scheduling if present.
  2595. This variable will have no effect if `org-log-into-drawer' is
  2596. set."
  2597. :group 'org-todo
  2598. :group 'org-progress
  2599. :type 'boolean)
  2600. (defcustom org-log-states-order-reversed t
  2601. "Non-nil means the latest state note will be directly after heading.
  2602. When nil, the state change notes will be ordered according to time.
  2603. This option can also be set with on a per-file-basis with
  2604. #+STARTUP: logstatesreversed
  2605. #+STARTUP: nologstatesreversed"
  2606. :group 'org-todo
  2607. :group 'org-progress
  2608. :type 'boolean)
  2609. (defcustom org-todo-repeat-to-state nil
  2610. "The TODO state to which a repeater should return the repeating task.
  2611. By default this is the first task of a TODO sequence or the
  2612. previous state of a TYPE_TODO set. But you can specify to use
  2613. the previous state in a TODO sequence or a string.
  2614. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2615. entry, which has precedence over this option."
  2616. :group 'org-todo
  2617. :version "24.1"
  2618. :type '(choice (const :tag "Use the previous TODO state" t)
  2619. (const :tag "Use the head of the TODO sequence" nil)
  2620. (string :tag "Use a specific TODO state")))
  2621. (defcustom org-log-repeat 'time
  2622. "Non-nil means record moving through the DONE state when triggering repeat.
  2623. An auto-repeating task is immediately switched back to TODO when
  2624. marked DONE. If you are not logging state changes (by adding \"@\"
  2625. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2626. record a closing note, there will be no record of the task moving
  2627. through DONE. This variable forces taking a note anyway.
  2628. nil Don't force a record
  2629. time Record a time stamp
  2630. note Prompt for a note and add it with template `org-log-note-headings'
  2631. This option can also be set with on a per-file-basis with
  2632. #+STARTUP: nologrepeat
  2633. #+STARTUP: logrepeat
  2634. #+STARTUP: lognoterepeat
  2635. You can have local logging settings for a subtree by setting the LOGGING
  2636. property to one or more of these keywords."
  2637. :group 'org-todo
  2638. :group 'org-progress
  2639. :type '(choice
  2640. (const :tag "Don't force a record" nil)
  2641. (const :tag "Force recording the DONE state" time)
  2642. (const :tag "Force recording a note with the DONE state" note)))
  2643. (defgroup org-priorities nil
  2644. "Priorities in Org mode."
  2645. :tag "Org Priorities"
  2646. :group 'org-todo)
  2647. (defcustom org-enable-priority-commands t
  2648. "Non-nil means priority commands are active.
  2649. When nil, these commands will be disabled, so that you never accidentally
  2650. set a priority."
  2651. :group 'org-priorities
  2652. :type 'boolean)
  2653. (defcustom org-highest-priority ?A
  2654. "The highest priority of TODO items. A character like ?A, ?B etc.
  2655. Must have a smaller ASCII number than `org-lowest-priority'."
  2656. :group 'org-priorities
  2657. :type 'character)
  2658. (defcustom org-lowest-priority ?C
  2659. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2660. Must have a larger ASCII number than `org-highest-priority'."
  2661. :group 'org-priorities
  2662. :type 'character)
  2663. (defcustom org-default-priority ?B
  2664. "The default priority of TODO items.
  2665. This is the priority an item gets if no explicit priority is given.
  2666. When starting to cycle on an empty priority the first step in the cycle
  2667. depends on `org-priority-start-cycle-with-default'. The resulting first
  2668. step priority must not exceed the range from `org-highest-priority' to
  2669. `org-lowest-priority' which means that `org-default-priority' has to be
  2670. in this range exclusive or inclusive the range boundaries. Else the
  2671. first step refuses to set the default and the second will fall back
  2672. to (depending on the command used) the highest or lowest priority."
  2673. :group 'org-priorities
  2674. :type 'character)
  2675. (defcustom org-priority-start-cycle-with-default t
  2676. "Non-nil means start with default priority when starting to cycle.
  2677. When this is nil, the first step in the cycle will be (depending on the
  2678. command used) one higher or lower than the default priority.
  2679. See also `org-default-priority'."
  2680. :group 'org-priorities
  2681. :type 'boolean)
  2682. (defcustom org-get-priority-function nil
  2683. "Function to extract the priority from a string.
  2684. The string is normally the headline. If this is nil Org computes the
  2685. priority from the priority cookie like [#A] in the headline. It returns
  2686. an integer, increasing by 1000 for each priority level.
  2687. The user can set a different function here, which should take a string
  2688. as an argument and return the numeric priority."
  2689. :group 'org-priorities
  2690. :version "24.1"
  2691. :type '(choice
  2692. (const nil)
  2693. (function)))
  2694. (defgroup org-time nil
  2695. "Options concerning time stamps and deadlines in Org mode."
  2696. :tag "Org Time"
  2697. :group 'org)
  2698. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2699. "Number of minutes to round time stamps to.
  2700. \\<org-mode-map>\
  2701. These are two values, the first applies when first creating a time stamp.
  2702. The second applies when changing it with the commands `S-up' and `S-down'.
  2703. When changing the time stamp, this means that it will change in steps
  2704. of N minutes, as given by the second value.
  2705. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2706. numbers should be factors of 60, so for example 5, 10, 15.
  2707. When this is larger than 1, you can still force an exact time stamp by using
  2708. a double prefix argument to a time stamp command like \
  2709. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2710. and by using a prefix arg to `S-up/down' to specify the exact number
  2711. of minutes to shift."
  2712. :group 'org-time
  2713. :get (lambda (var) ; Make sure both elements are there
  2714. (if (integerp (default-value var))
  2715. (list (default-value var) 5)
  2716. (default-value var)))
  2717. :type '(list
  2718. (integer :tag "when inserting times")
  2719. (integer :tag "when modifying times")))
  2720. ;; Normalize old customizations of this variable.
  2721. (when (integerp org-time-stamp-rounding-minutes)
  2722. (setq org-time-stamp-rounding-minutes
  2723. (list org-time-stamp-rounding-minutes
  2724. org-time-stamp-rounding-minutes)))
  2725. (defcustom org-display-custom-times nil
  2726. "Non-nil means overlay custom formats over all time stamps.
  2727. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2728. To turn this on on a per-file basis, insert anywhere in the file:
  2729. #+STARTUP: customtime"
  2730. :group 'org-time
  2731. :set 'set-default
  2732. :type 'sexp)
  2733. (make-variable-buffer-local 'org-display-custom-times)
  2734. (defcustom org-time-stamp-custom-formats
  2735. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2736. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2737. These are overlaid over the default ISO format if the variable
  2738. `org-display-custom-times' is set. Time like %H:%M should be at the
  2739. end of the second format. The custom formats are also honored by export
  2740. commands, if custom time display is turned on at the time of export."
  2741. :group 'org-time
  2742. :type 'sexp)
  2743. (defun org-time-stamp-format (&optional long inactive)
  2744. "Get the right format for a time string."
  2745. (let ((f (if long (cdr org-time-stamp-formats)
  2746. (car org-time-stamp-formats))))
  2747. (if inactive
  2748. (concat "[" (substring f 1 -1) "]")
  2749. f)))
  2750. (defcustom org-deadline-warning-days 14
  2751. "Number of days before expiration during which a deadline becomes active.
  2752. This variable governs the display in sparse trees and in the agenda.
  2753. When 0 or negative, it means use this number (the absolute value of it)
  2754. even if a deadline has a different individual lead time specified.
  2755. Custom commands can set this variable in the options section."
  2756. :group 'org-time
  2757. :group 'org-agenda-daily/weekly
  2758. :type 'integer)
  2759. (defcustom org-scheduled-delay-days 0
  2760. "Number of days before a scheduled item becomes active.
  2761. This variable governs the display in sparse trees and in the agenda.
  2762. The default value (i.e. 0) means: don't delay scheduled item.
  2763. When negative, it means use this number (the absolute value of it)
  2764. even if a scheduled item has a different individual delay time
  2765. specified.
  2766. Custom commands can set this variable in the options section."
  2767. :group 'org-time
  2768. :group 'org-agenda-daily/weekly
  2769. :version "24.4"
  2770. :package-version '(Org . "8.0")
  2771. :type 'integer)
  2772. (defcustom org-read-date-prefer-future t
  2773. "Non-nil means assume future for incomplete date input from user.
  2774. This affects the following situations:
  2775. 1. The user gives a month but not a year.
  2776. For example, if it is April and you enter \"feb 2\", this will be read
  2777. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2778. 2. The user gives a day, but no month.
  2779. For example, if today is the 15th, and you enter \"3\", Org will read
  2780. this as the third of *next* month. However, if you enter \"17\",
  2781. it will be considered as *this* month.
  2782. If you set this variable to the symbol `time', then also the following
  2783. will work:
  2784. 3. If the user gives a time.
  2785. If the time is before now, it will be interpreted as tomorrow.
  2786. Currently none of this works for ISO week specifications.
  2787. When this option is nil, the current day, month and year will always be
  2788. used as defaults.
  2789. See also `org-agenda-jump-prefer-future'."
  2790. :group 'org-time
  2791. :type '(choice
  2792. (const :tag "Never" nil)
  2793. (const :tag "Check month and day" t)
  2794. (const :tag "Check month, day, and time" time)))
  2795. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2796. "Should the agenda jump command prefer the future for incomplete dates?
  2797. The default is to do the same as configured in `org-read-date-prefer-future'.
  2798. But you can also set a deviating value here.
  2799. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2800. :group 'org-agenda
  2801. :group 'org-time
  2802. :version "24.1"
  2803. :type '(choice
  2804. (const :tag "Use org-read-date-prefer-future"
  2805. org-read-date-prefer-future)
  2806. (const :tag "Never" nil)
  2807. (const :tag "Always" t)))
  2808. (defcustom org-read-date-force-compatible-dates t
  2809. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2810. Depending on the system Emacs is running on, certain dates cannot
  2811. be represented with the type used internally to represent time.
  2812. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2813. correctly. Some systems allow for earlier dates, some for later,
  2814. some for both. One way to find out it to insert any date into an
  2815. Org buffer, putting the cursor on the year and hitting S-up and
  2816. S-down to test the range.
  2817. When this variable is set to t, the date/time prompt will not let
  2818. you specify dates outside the 1970-2037 range, so it is certain that
  2819. these dates will work in whatever version of Emacs you are
  2820. running, and also that you can move a file from one Emacs implementation
  2821. to another. WHenever Org is forcing the year for you, it will display
  2822. a message and beep.
  2823. When this variable is nil, Org will check if the date is
  2824. representable in the specific Emacs implementation you are using.
  2825. If not, it will force a year, usually the current year, and beep
  2826. to remind you. Currently this setting is not recommended because
  2827. the likelihood that you will open your Org files in an Emacs that
  2828. has limited date range is not negligible.
  2829. A workaround for this problem is to use diary sexp dates for time
  2830. stamps outside of this range."
  2831. :group 'org-time
  2832. :version "24.1"
  2833. :type 'boolean)
  2834. (defcustom org-read-date-display-live t
  2835. "Non-nil means display current interpretation of date prompt live.
  2836. This display will be in an overlay, in the minibuffer."
  2837. :group 'org-time
  2838. :type 'boolean)
  2839. (defcustom org-read-date-popup-calendar t
  2840. "Non-nil means pop up a calendar when prompting for a date.
  2841. In the calendar, the date can be selected with mouse-1. However, the
  2842. minibuffer will also be active, and you can simply enter the date as well.
  2843. When nil, only the minibuffer will be available."
  2844. :group 'org-time
  2845. :type 'boolean)
  2846. (defvaralias 'org-popup-calendar-for-date-prompt
  2847. 'org-read-date-popup-calendar)
  2848. (defcustom org-extend-today-until 0
  2849. "The hour when your day really ends. Must be an integer.
  2850. This has influence for the following applications:
  2851. - When switching the agenda to \"today\". It it is still earlier than
  2852. the time given here, the day recognized as TODAY is actually yesterday.
  2853. - When a date is read from the user and it is still before the time given
  2854. here, the current date and time will be assumed to be yesterday, 23:59.
  2855. Also, timestamps inserted in capture templates follow this rule.
  2856. IMPORTANT: This is a feature whose implementation is and likely will
  2857. remain incomplete. Really, it is only here because past midnight seems to
  2858. be the favorite working time of John Wiegley :-)"
  2859. :group 'org-time
  2860. :type 'integer)
  2861. (defcustom org-use-effective-time nil
  2862. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2863. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2864. \"effective time\" of any timestamps between midnight and 8am will be
  2865. 23:59 of the previous day."
  2866. :group 'org-time
  2867. :version "24.1"
  2868. :type 'boolean)
  2869. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2870. "When non-nil, use the last clock out time for `org-todo'.
  2871. Note that this option has precedence over the combined use of
  2872. `org-use-effective-time' and `org-extend-today-until'."
  2873. :group 'org-time
  2874. :version "24.4"
  2875. :package-version '(Org . "8.0")
  2876. :type 'boolean)
  2877. (defcustom org-edit-timestamp-down-means-later nil
  2878. "Non-nil means S-down will increase the time in a time stamp.
  2879. When nil, S-up will increase."
  2880. :group 'org-time
  2881. :type 'boolean)
  2882. (defcustom org-calendar-follow-timestamp-change t
  2883. "Non-nil means make the calendar window follow timestamp changes.
  2884. When a timestamp is modified and the calendar window is visible, it will be
  2885. moved to the new date."
  2886. :group 'org-time
  2887. :type 'boolean)
  2888. (defgroup org-tags nil
  2889. "Options concerning tags in Org mode."
  2890. :tag "Org Tags"
  2891. :group 'org)
  2892. (defcustom org-tag-alist nil
  2893. "Default tags available in Org files.
  2894. The value of this variable is an alist. Associations either:
  2895. (TAG)
  2896. (TAG . SELECT)
  2897. (SPECIAL)
  2898. where TAG is a tag as a string, SELECT is character, used to
  2899. select that tag through the fast tag selection interface, and
  2900. SPECIAL is one of the following keywords: `:startgroup',
  2901. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2902. `:newline'. These keywords are used to define a hierarchy of
  2903. tags. See manual for details.
  2904. When this variable is nil, Org mode bases tag input on what is
  2905. already in the buffer. The value can be overridden locally by
  2906. using a TAGS keyword, e.g.,
  2907. #+TAGS: tag1 tag2
  2908. See also `org-tag-persistent-alist' to sidestep this behavior."
  2909. :group 'org-tags
  2910. :type '(repeat
  2911. (choice
  2912. (cons :tag "Tag with key"
  2913. (string :tag "Tag name")
  2914. (character :tag "Access char"))
  2915. (list :tag "Tag" (string :tag "Tag name"))
  2916. (const :tag "Start radio group" (:startgroup))
  2917. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2918. (const :tag "Group tags delimiter" (:grouptags))
  2919. (const :tag "End radio group" (:endgroup))
  2920. (const :tag "End tag group, non distinct" (:endgrouptag))
  2921. (const :tag "New line" (:newline)))))
  2922. (defcustom org-tag-persistent-alist nil
  2923. "Tags always available in Org files.
  2924. The value of this variable is an alist. Associations either:
  2925. (TAG)
  2926. (TAG . SELECT)
  2927. (SPECIAL)
  2928. where TAG is a tag as a string, SELECT is a character, used to
  2929. select that tag through the fast tag selection interface, and
  2930. SPECIAL is one of the following keywords: `:startgroup',
  2931. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2932. `:newline'. These keywords are used to define a hierarchy of
  2933. tags. See manual for details.
  2934. Unlike to `org-tag-alist', tags defined in this variable do not
  2935. depend on a local TAGS keyword. Instead, to disable these tags
  2936. on a per-file basis, insert anywhere in the file:
  2937. #+STARTUP: noptag"
  2938. :group 'org-tags
  2939. :type '(repeat
  2940. (choice
  2941. (cons :tag "Tag with key"
  2942. (string :tag "Tag name")
  2943. (character :tag "Access char"))
  2944. (list :tag "Tag" (string :tag "Tag name"))
  2945. (const :tag "Start radio group" (:startgroup))
  2946. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2947. (const :tag "Group tags delimiter" (:grouptags))
  2948. (const :tag "End radio group" (:endgroup))
  2949. (const :tag "End tag group, non distinct" (:endgrouptag))
  2950. (const :tag "New line" (:newline)))))
  2951. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2952. "If non-nil, always offer completion for all tags of all agenda files.
  2953. Instead of customizing this variable directly, you might want to
  2954. set it locally for capture buffers, because there no list of
  2955. tags in that file can be created dynamically (there are none).
  2956. (add-hook \\='org-capture-mode-hook
  2957. (lambda ()
  2958. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2959. :group 'org-tags
  2960. :version "24.1"
  2961. :type 'boolean)
  2962. (defvar org-file-tags nil
  2963. "List of tags that can be inherited by all entries in the file.
  2964. The tags will be inherited if the variable `org-use-tag-inheritance'
  2965. says they should be.
  2966. This variable is populated from #+FILETAGS lines.")
  2967. (defcustom org-use-fast-tag-selection 'auto
  2968. "Non-nil means use fast tag selection scheme.
  2969. This is a special interface to select and deselect tags with single keys.
  2970. When nil, fast selection is never used.
  2971. When the symbol `auto', fast selection is used if and only if selection
  2972. characters for tags have been configured, either through the variable
  2973. `org-tag-alist' or through a #+TAGS line in the buffer.
  2974. When t, fast selection is always used and selection keys are assigned
  2975. automatically if necessary."
  2976. :group 'org-tags
  2977. :type '(choice
  2978. (const :tag "Always" t)
  2979. (const :tag "Never" nil)
  2980. (const :tag "When selection characters are configured" auto)))
  2981. (defcustom org-fast-tag-selection-single-key nil
  2982. "Non-nil means fast tag selection exits after first change.
  2983. When nil, you have to press RET to exit it.
  2984. During fast tag selection, you can toggle this flag with `C-c'.
  2985. This variable can also have the value `expert'. In this case, the window
  2986. displaying the tags menu is not even shown, until you press C-c again."
  2987. :group 'org-tags
  2988. :type '(choice
  2989. (const :tag "No" nil)
  2990. (const :tag "Yes" t)
  2991. (const :tag "Expert" expert)))
  2992. (defvar org-fast-tag-selection-include-todo nil
  2993. "Non-nil means fast tags selection interface will also offer TODO states.
  2994. This is an undocumented feature, you should not rely on it.")
  2995. (defcustom org-tags-column -77
  2996. "The column to which tags should be indented in a headline.
  2997. If this number is positive, it specifies the column. If it is negative,
  2998. it means that the tags should be flushright to that column. For example,
  2999. -80 works well for a normal 80 character screen.
  3000. When 0, place tags directly after headline text, with only one space in
  3001. between."
  3002. :group 'org-tags
  3003. :type 'integer)
  3004. (defcustom org-auto-align-tags t
  3005. "Non-nil keeps tags aligned when modifying headlines.
  3006. Some operations (i.e. demoting) change the length of a headline and
  3007. therefore shift the tags around. With this option turned on, after
  3008. each such operation the tags are again aligned to `org-tags-column'."
  3009. :group 'org-tags
  3010. :type 'boolean)
  3011. (defcustom org-use-tag-inheritance t
  3012. "Non-nil means tags in levels apply also for sublevels.
  3013. When nil, only the tags directly given in a specific line apply there.
  3014. This may also be a list of tags that should be inherited, or a regexp that
  3015. matches tags that should be inherited. Additional control is possible
  3016. with the variable `org-tags-exclude-from-inheritance' which gives an
  3017. explicit list of tags to be excluded from inheritance, even if the value of
  3018. `org-use-tag-inheritance' would select it for inheritance.
  3019. If this option is t, a match early-on in a tree can lead to a large
  3020. number of matches in the subtree when constructing the agenda or creating
  3021. a sparse tree. If you only want to see the first match in a tree during
  3022. a search, check out the variable `org-tags-match-list-sublevels'."
  3023. :group 'org-tags
  3024. :type '(choice
  3025. (const :tag "Not" nil)
  3026. (const :tag "Always" t)
  3027. (repeat :tag "Specific tags" (string :tag "Tag"))
  3028. (regexp :tag "Tags matched by regexp")))
  3029. (defcustom org-tags-exclude-from-inheritance nil
  3030. "List of tags that should never be inherited.
  3031. This is a way to exclude a few tags from inheritance. For way to do
  3032. the opposite, to actively allow inheritance for selected tags,
  3033. see the variable `org-use-tag-inheritance'."
  3034. :group 'org-tags
  3035. :type '(repeat (string :tag "Tag")))
  3036. (defun org-tag-inherit-p (tag)
  3037. "Check if TAG is one that should be inherited."
  3038. (cond
  3039. ((member tag org-tags-exclude-from-inheritance) nil)
  3040. ((eq org-use-tag-inheritance t) t)
  3041. ((not org-use-tag-inheritance) nil)
  3042. ((stringp org-use-tag-inheritance)
  3043. (string-match org-use-tag-inheritance tag))
  3044. ((listp org-use-tag-inheritance)
  3045. (member tag org-use-tag-inheritance))
  3046. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3047. (defcustom org-tags-match-list-sublevels t
  3048. "Non-nil means list also sublevels of headlines matching a search.
  3049. This variable applies to tags/property searches, and also to stuck
  3050. projects because this search is based on a tags match as well.
  3051. When set to the symbol `indented', sublevels are indented with
  3052. leading dots.
  3053. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3054. the sublevels of a headline matching a tag search often also match
  3055. the same search. Listing all of them can create very long lists.
  3056. Setting this variable to nil causes subtrees of a match to be skipped.
  3057. This variable is semi-obsolete and probably should always be true. It
  3058. is better to limit inheritance to certain tags using the variables
  3059. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3060. :group 'org-tags
  3061. :type '(choice
  3062. (const :tag "No, don't list them" nil)
  3063. (const :tag "Yes, do list them" t)
  3064. (const :tag "List them, indented with leading dots" indented)))
  3065. (defcustom org-tags-sort-function nil
  3066. "When set, tags are sorted using this function as a comparator."
  3067. :group 'org-tags
  3068. :type '(choice
  3069. (const :tag "No sorting" nil)
  3070. (const :tag "Alphabetical" org-string-collate-lessp)
  3071. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  3072. (function :tag "Custom function" nil)))
  3073. (defvar org-tags-history nil
  3074. "History of minibuffer reads for tags.")
  3075. (defvar org-last-tags-completion-table nil
  3076. "The last used completion table for tags.")
  3077. (defvar org-after-tags-change-hook nil
  3078. "Hook that is run after the tags in a line have changed.")
  3079. (defgroup org-properties nil
  3080. "Options concerning properties in Org mode."
  3081. :tag "Org Properties"
  3082. :group 'org)
  3083. (defcustom org-property-format "%-10s %s"
  3084. "How property key/value pairs should be formatted by `indent-line'.
  3085. When `indent-line' hits a property definition, it will format the line
  3086. according to this format, mainly to make sure that the values are
  3087. lined-up with respect to each other."
  3088. :group 'org-properties
  3089. :type 'string)
  3090. (defcustom org-properties-postprocess-alist nil
  3091. "Alist of properties and functions to adjust inserted values.
  3092. Elements of this alist must be of the form
  3093. ([string] [function])
  3094. where [string] must be a property name and [function] must be a
  3095. lambda expression: this lambda expression must take one argument,
  3096. the value to adjust, and return the new value as a string.
  3097. For example, this element will allow the property \"Remaining\"
  3098. to be updated wrt the relation between the \"Effort\" property
  3099. and the clock summary:
  3100. ((\"Remaining\" (lambda(value)
  3101. (let ((clocksum (org-clock-sum-current-item))
  3102. (effort (org-duration-to-minutes
  3103. (org-entry-get (point) \"Effort\"))))
  3104. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3105. :group 'org-properties
  3106. :version "24.1"
  3107. :type '(alist :key-type (string :tag "Property")
  3108. :value-type (function :tag "Function")))
  3109. (defcustom org-use-property-inheritance nil
  3110. "Non-nil means properties apply also for sublevels.
  3111. This setting is chiefly used during property searches. Turning it on can
  3112. cause significant overhead when doing a search, which is why it is not
  3113. on by default.
  3114. When nil, only the properties directly given in the current entry count.
  3115. When t, every property is inherited. The value may also be a list of
  3116. properties that should have inheritance, or a regular expression matching
  3117. properties that should be inherited.
  3118. However, note that some special properties use inheritance under special
  3119. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3120. and the properties ending in \"_ALL\" when they are used as descriptor
  3121. for valid values of a property.
  3122. Note for programmers:
  3123. When querying an entry with `org-entry-get', you can control if inheritance
  3124. should be used. By default, `org-entry-get' looks only at the local
  3125. properties. You can request inheritance by setting the inherit argument
  3126. to t (to force inheritance) or to `selective' (to respect the setting
  3127. in this variable)."
  3128. :group 'org-properties
  3129. :type '(choice
  3130. (const :tag "Not" nil)
  3131. (const :tag "Always" t)
  3132. (repeat :tag "Specific properties" (string :tag "Property"))
  3133. (regexp :tag "Properties matched by regexp")))
  3134. (defun org-property-inherit-p (property)
  3135. "Return a non-nil value if PROPERTY should be inherited."
  3136. (cond
  3137. ((eq org-use-property-inheritance t) t)
  3138. ((not org-use-property-inheritance) nil)
  3139. ((stringp org-use-property-inheritance)
  3140. (string-match org-use-property-inheritance property))
  3141. ((listp org-use-property-inheritance)
  3142. (member-ignore-case property org-use-property-inheritance))
  3143. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3144. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3145. "The default column format, if no other format has been defined.
  3146. This variable can be set on the per-file basis by inserting a line
  3147. #+COLUMNS: %25ITEM ....."
  3148. :group 'org-properties
  3149. :type 'string)
  3150. (defcustom org-columns-ellipses ".."
  3151. "The ellipses to be used when a field in column view is truncated.
  3152. When this is the empty string, as many characters as possible are shown,
  3153. but then there will be no visual indication that the field has been truncated.
  3154. When this is a string of length N, the last N characters of a truncated
  3155. field are replaced by this string. If the column is narrower than the
  3156. ellipses string, only part of the ellipses string will be shown."
  3157. :group 'org-properties
  3158. :type 'string)
  3159. (defconst org-global-properties-fixed
  3160. '(("VISIBILITY_ALL" . "folded children content all")
  3161. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3162. "List of property/value pairs that can be inherited by any entry.
  3163. These are fixed values, for the preset properties. The user variable
  3164. that can be used to add to this list is `org-global-properties'.
  3165. The entries in this list are cons cells where the car is a property
  3166. name and cdr is a string with the value. If the value represents
  3167. multiple items like an \"_ALL\" property, separate the items by
  3168. spaces.")
  3169. (defcustom org-global-properties nil
  3170. "List of property/value pairs that can be inherited by any entry.
  3171. This list will be combined with the constant `org-global-properties-fixed'.
  3172. The entries in this list are cons cells where the car is a property
  3173. name and cdr is a string with the value.
  3174. You can set buffer-local values for the same purpose in the variable
  3175. `org-file-properties' this by adding lines like
  3176. #+PROPERTY: NAME VALUE"
  3177. :group 'org-properties
  3178. :type '(repeat
  3179. (cons (string :tag "Property")
  3180. (string :tag "Value"))))
  3181. (defvar-local org-file-properties nil
  3182. "List of property/value pairs that can be inherited by any entry.
  3183. Valid for the current buffer.
  3184. This variable is populated from #+PROPERTY lines.")
  3185. (defgroup org-agenda nil
  3186. "Options concerning agenda views in Org mode."
  3187. :tag "Org Agenda"
  3188. :group 'org)
  3189. (defvar-local org-category nil
  3190. "Variable used by Org files to set a category for agenda display.
  3191. Such files should use a file variable to set it, for example
  3192. # -*- mode: org; org-category: \"ELisp\"
  3193. or contain a special line
  3194. #+CATEGORY: ELisp
  3195. If the file does not specify a category, then file's base name
  3196. is used instead.")
  3197. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3198. (defcustom org-agenda-files nil
  3199. "The files to be used for agenda display.
  3200. If an entry is a directory, all files in that directory that are matched
  3201. by `org-agenda-file-regexp' will be part of the file list.
  3202. If the value of the variable is not a list but a single file name, then
  3203. the list of agenda files is actually stored and maintained in that file,
  3204. one agenda file per line. In this file paths can be given relative to
  3205. `org-directory'. Tilde expansion and environment variable substitution
  3206. are also made.
  3207. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3208. and removed with `\\[org-remove-file]'."
  3209. :group 'org-agenda
  3210. :type '(choice
  3211. (repeat :tag "List of files and directories" file)
  3212. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3213. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3214. "Regular expression to match files for `org-agenda-files'.
  3215. If any element in the list in that variable contains a directory instead
  3216. of a normal file, all files in that directory that are matched by this
  3217. regular expression will be included."
  3218. :group 'org-agenda
  3219. :type 'regexp)
  3220. (defcustom org-agenda-text-search-extra-files nil
  3221. "List of extra files to be searched by text search commands.
  3222. These files will be searched in addition to the agenda files by the
  3223. commands `org-search-view' (`\\[org-agenda] s') \
  3224. and `org-occur-in-agenda-files'.
  3225. Note that these files will only be searched for text search commands,
  3226. not for the other agenda views like todo lists, tag searches or the weekly
  3227. agenda. This variable is intended to list notes and possibly archive files
  3228. that should also be searched by these two commands.
  3229. In fact, if the first element in the list is the symbol `agenda-archives',
  3230. then all archive files of all agenda files will be added to the search
  3231. scope."
  3232. :group 'org-agenda
  3233. :type '(set :greedy t
  3234. (const :tag "Agenda Archives" agenda-archives)
  3235. (repeat :inline t (file))))
  3236. (defvaralias 'org-agenda-multi-occur-extra-files
  3237. 'org-agenda-text-search-extra-files)
  3238. (defcustom org-agenda-skip-unavailable-files nil
  3239. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3240. A nil value means to remove them, after a query, from the list."
  3241. :group 'org-agenda
  3242. :type 'boolean)
  3243. (defcustom org-agenda-diary-file 'diary-file
  3244. "File to which to add new entries with the `i' key in agenda and calendar.
  3245. When this is the symbol `diary-file', the functionality in the Emacs
  3246. calendar will be used to add entries to the `diary-file'. But when this
  3247. points to a file, `org-agenda-diary-entry' will be used instead."
  3248. :group 'org-agenda
  3249. :type '(choice
  3250. (const :tag "The standard Emacs diary file" diary-file)
  3251. (file :tag "Special Org file diary entries")))
  3252. (defgroup org-latex nil
  3253. "Options for embedding LaTeX code into Org mode."
  3254. :tag "Org LaTeX"
  3255. :group 'org)
  3256. (defcustom org-format-latex-options
  3257. '(:foreground default :background default :scale 1.0
  3258. :html-foreground "Black" :html-background "Transparent"
  3259. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3260. "Options for creating images from LaTeX fragments.
  3261. This is a property list with the following properties:
  3262. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3263. `default' means use the foreground of the default face.
  3264. `auto' means use the foreground from the text face.
  3265. :background the background color, or \"Transparent\".
  3266. `default' means use the background of the default face.
  3267. `auto' means use the background from the text face.
  3268. :scale a scaling factor for the size of the images, to get more pixels
  3269. :html-foreground, :html-background, :html-scale
  3270. the same numbers for HTML export.
  3271. :matchers a list indicating which matchers should be used to
  3272. find LaTeX fragments. Valid members of this list are:
  3273. \"begin\" find environments
  3274. \"$1\" find single characters surrounded by $.$
  3275. \"$\" find math expressions surrounded by $...$
  3276. \"$$\" find math expressions surrounded by $$....$$
  3277. \"\\(\" find math expressions surrounded by \\(...\\)
  3278. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3279. :group 'org-latex
  3280. :type 'plist)
  3281. (defcustom org-format-latex-signal-error t
  3282. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3283. When nil, just push out a message."
  3284. :group 'org-latex
  3285. :version "24.1"
  3286. :type 'boolean)
  3287. (defcustom org-latex-to-mathml-jar-file nil
  3288. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3289. Use this to specify additional executable file say a jar file.
  3290. When using MathToWeb as the converter, specify the full-path to
  3291. your mathtoweb.jar file."
  3292. :group 'org-latex
  3293. :version "24.1"
  3294. :type '(choice
  3295. (const :tag "None" nil)
  3296. (file :tag "JAR file" :must-match t)))
  3297. (defcustom org-latex-to-mathml-convert-command nil
  3298. "Command to convert LaTeX fragments to MathML.
  3299. Replace format-specifiers in the command as noted below and use
  3300. `shell-command' to convert LaTeX to MathML.
  3301. %j: Executable file in fully expanded form as specified by
  3302. `org-latex-to-mathml-jar-file'.
  3303. %I: Input LaTeX file in fully expanded form.
  3304. %i: The latex fragment to be converted.
  3305. %o: Output MathML file.
  3306. This command is used by `org-create-math-formula'.
  3307. When using MathToWeb as the converter, set this option to
  3308. \"java -jar %j -unicode -force -df %o %I\".
  3309. When using LaTeXML set this option to
  3310. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3311. :group 'org-latex
  3312. :version "24.1"
  3313. :type '(choice
  3314. (const :tag "None" nil)
  3315. (string :tag "\nShell command")))
  3316. (defcustom org-preview-latex-default-process 'dvipng
  3317. "The default process to convert LaTeX fragments to image files.
  3318. All available processes and theirs documents can be found in
  3319. `org-preview-latex-process-alist', which see."
  3320. :group 'org-latex
  3321. :version "26.1"
  3322. :package-version '(Org . "9.0")
  3323. :type 'symbol)
  3324. (defcustom org-preview-latex-process-alist
  3325. '((dvipng
  3326. :programs ("latex" "dvipng")
  3327. :description "dvi > png"
  3328. :message "you need to install the programs: latex and dvipng."
  3329. :image-input-type "dvi"
  3330. :image-output-type "png"
  3331. :image-size-adjust (1.0 . 1.0)
  3332. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3333. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3334. (dvisvgm
  3335. :programs ("latex" "dvisvgm")
  3336. :description "dvi > svg"
  3337. :message "you need to install the programs: latex and dvisvgm."
  3338. :use-xcolor t
  3339. :image-input-type "dvi"
  3340. :image-output-type "svg"
  3341. :image-size-adjust (1.7 . 1.5)
  3342. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3343. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3344. (imagemagick
  3345. :programs ("latex" "convert")
  3346. :description "pdf > png"
  3347. :message "you need to install the programs: latex and imagemagick."
  3348. :use-xcolor t
  3349. :image-input-type "pdf"
  3350. :image-output-type "png"
  3351. :image-size-adjust (1.0 . 1.0)
  3352. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3353. :image-converter
  3354. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3355. "Definitions of external processes for LaTeX previewing.
  3356. Org mode can use some external commands to generate TeX snippet's images for
  3357. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3358. `org-create-formula-image' how to call them.
  3359. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3360. PROPERTIES accepts the following attributes:
  3361. :programs list of strings, required programs.
  3362. :description string, describe the process.
  3363. :message string, message it when required programs cannot be found.
  3364. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3365. :image-output-type string, output file type of image converter (e.g., \"png\").
  3366. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3367. deal with background and foreground color of image.
  3368. Otherwise, dvipng style background and foreground color
  3369. format are generated. You may then refer to them in
  3370. command options with \"%F\" and \"%B\".
  3371. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3372. image size showed in buffer and the cdr element is for
  3373. HTML file. This option is only useful for process
  3374. developers, users should use variable
  3375. `org-format-latex-options' instead.
  3376. :post-clean list of strings, files matched are to be cleaned up once
  3377. the image is generated. When nil, the files with \".dvi\",
  3378. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3379. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3380. be cleaned up.
  3381. :latex-header list of strings, the LaTeX header of the snippet file.
  3382. When nil, the fallback value is used instead, which is
  3383. controlled by `org-format-latex-header',
  3384. `org-latex-default-packages-alist' and
  3385. `org-latex-packages-alist', which see.
  3386. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3387. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3388. replaced with values defined below.
  3389. :image-converter list of image converter commands strings. Each of them is
  3390. given to the shell and supports any of the following
  3391. place-holders defined below.
  3392. Place-holders used by `:image-converter' and `:latex-compiler':
  3393. %f input file name
  3394. %b base name of input file
  3395. %o base directory of input file
  3396. %O absolute output file name
  3397. Place-holders only used by `:image-converter':
  3398. %F foreground of image
  3399. %B background of image
  3400. %D dpi, which is used to adjust image size by some processing commands.
  3401. %S the image size scale ratio, which is used to adjust image size by some
  3402. processing commands."
  3403. :group 'org-latex
  3404. :version "26.1"
  3405. :package-version '(Org . "9.0")
  3406. :type '(alist :tag "LaTeX to image backends"
  3407. :value-type (plist)))
  3408. (defcustom org-preview-latex-image-directory "ltximg/"
  3409. "Path to store latex preview images.
  3410. A relative path here creates many directories relative to the
  3411. processed Org files paths. An absolute path puts all preview
  3412. images at the same place."
  3413. :group 'org-latex
  3414. :version "26.1"
  3415. :package-version '(Org . "9.0")
  3416. :type 'string)
  3417. (defun org-format-latex-mathml-available-p ()
  3418. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3419. (save-match-data
  3420. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3421. org-latex-to-mathml-convert-command)
  3422. (let ((executable (car (split-string
  3423. org-latex-to-mathml-convert-command))))
  3424. (when (executable-find executable)
  3425. (if (string-match
  3426. "%j" org-latex-to-mathml-convert-command)
  3427. (file-readable-p org-latex-to-mathml-jar-file)
  3428. t))))))
  3429. (defcustom org-format-latex-header "\\documentclass{article}
  3430. \\usepackage[usenames]{color}
  3431. \[PACKAGES]
  3432. \[DEFAULT-PACKAGES]
  3433. \\pagestyle{empty} % do not remove
  3434. % The settings below are copied from fullpage.sty
  3435. \\setlength{\\textwidth}{\\paperwidth}
  3436. \\addtolength{\\textwidth}{-3cm}
  3437. \\setlength{\\oddsidemargin}{1.5cm}
  3438. \\addtolength{\\oddsidemargin}{-2.54cm}
  3439. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3440. \\setlength{\\textheight}{\\paperheight}
  3441. \\addtolength{\\textheight}{-\\headheight}
  3442. \\addtolength{\\textheight}{-\\headsep}
  3443. \\addtolength{\\textheight}{-\\footskip}
  3444. \\addtolength{\\textheight}{-3cm}
  3445. \\setlength{\\topmargin}{1.5cm}
  3446. \\addtolength{\\topmargin}{-2.54cm}"
  3447. "The document header used for processing LaTeX fragments.
  3448. It is imperative that this header make sure that no page number
  3449. appears on the page. The package defined in the variables
  3450. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3451. will either replace the placeholder \"[PACKAGES]\" in this
  3452. header, or they will be appended."
  3453. :group 'org-latex
  3454. :type 'string)
  3455. (defun org-set-packages-alist (var val)
  3456. "Set the packages alist and make sure it has 3 elements per entry."
  3457. (set var (mapcar (lambda (x)
  3458. (if (and (consp x) (= (length x) 2))
  3459. (list (car x) (nth 1 x) t)
  3460. x))
  3461. val)))
  3462. (defun org-get-packages-alist (var)
  3463. "Get the packages alist and make sure it has 3 elements per entry."
  3464. (mapcar (lambda (x)
  3465. (if (and (consp x) (= (length x) 2))
  3466. (list (car x) (nth 1 x) t)
  3467. x))
  3468. (default-value var)))
  3469. (defcustom org-latex-default-packages-alist
  3470. '(("AUTO" "inputenc" t ("pdflatex"))
  3471. ("T1" "fontenc" t ("pdflatex"))
  3472. ("" "graphicx" t)
  3473. ("" "grffile" t)
  3474. ("" "longtable" nil)
  3475. ("" "wrapfig" nil)
  3476. ("" "rotating" nil)
  3477. ("normalem" "ulem" t)
  3478. ("" "amsmath" t)
  3479. ("" "textcomp" t)
  3480. ("" "amssymb" t)
  3481. ("" "capt-of" nil)
  3482. ("" "hyperref" nil))
  3483. "Alist of default packages to be inserted in the header.
  3484. Change this only if one of the packages here causes an
  3485. incompatibility with another package you are using.
  3486. The packages in this list are needed by one part or another of
  3487. Org mode to function properly:
  3488. - inputenc, fontenc: for basic font and character selection
  3489. - graphicx: for including images
  3490. - grffile: allow periods and spaces in graphics file names
  3491. - longtable: For multipage tables
  3492. - wrapfig: for figure placement
  3493. - rotating: for sideways figures and tables
  3494. - ulem: for underline and strike-through
  3495. - amsmath: for subscript and superscript and math environments
  3496. - textcomp, amssymb: for various symbols used
  3497. for interpreting the entities in `org-entities'. You can skip
  3498. some of these packages if you don't use any of their symbols.
  3499. - capt-of: for captions outside of floats
  3500. - hyperref: for cross references
  3501. Therefore you should not modify this variable unless you know
  3502. what you are doing. The one reason to change it anyway is that
  3503. you might be loading some other package that conflicts with one
  3504. of the default packages. Each element is either a cell or
  3505. a string.
  3506. A cell is of the format
  3507. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3508. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3509. when compiling LaTeX snippets into images for inclusion into
  3510. non-LaTeX output. COMPILERS is a list of compilers that should
  3511. include the package, see `org-latex-compiler'. If the document
  3512. compiler is not in the list, and the list is non-nil, the package
  3513. will not be inserted in the final document.
  3514. A string will be inserted as-is in the header of the document."
  3515. :group 'org-latex
  3516. :group 'org-export-latex
  3517. :set 'org-set-packages-alist
  3518. :get 'org-get-packages-alist
  3519. :version "26.1"
  3520. :package-version '(Org . "8.3")
  3521. :type '(repeat
  3522. (choice
  3523. (list :tag "options/package pair"
  3524. (string :tag "options")
  3525. (string :tag "package")
  3526. (boolean :tag "Snippet")
  3527. (choice
  3528. (const :tag "For all compilers" nil)
  3529. (repeat :tag "Allowed compiler" string)))
  3530. (string :tag "A line of LaTeX"))))
  3531. (defcustom org-latex-packages-alist nil
  3532. "Alist of packages to be inserted in every LaTeX header.
  3533. These will be inserted after `org-latex-default-packages-alist'.
  3534. Each element is either a cell or a string.
  3535. A cell is of the format:
  3536. (\"options\" \"package\" SNIPPET-FLAG)
  3537. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3538. needed when turning LaTeX snippets into images for inclusion into
  3539. non-LaTeX output.
  3540. A string will be inserted as-is in the header of the document.
  3541. Make sure that you only list packages here which:
  3542. - you want in every file;
  3543. - do not conflict with the setup in `org-format-latex-header';
  3544. - do not conflict with the default packages in
  3545. `org-latex-default-packages-alist'."
  3546. :group 'org-latex
  3547. :group 'org-export-latex
  3548. :set 'org-set-packages-alist
  3549. :get 'org-get-packages-alist
  3550. :type '(repeat
  3551. (choice
  3552. (list :tag "options/package pair"
  3553. (string :tag "options")
  3554. (string :tag "package")
  3555. (boolean :tag "Snippet"))
  3556. (string :tag "A line of LaTeX"))))
  3557. (defgroup org-appearance nil
  3558. "Settings for Org mode appearance."
  3559. :tag "Org Appearance"
  3560. :group 'org)
  3561. (defcustom org-level-color-stars-only nil
  3562. "Non-nil means fontify only the stars in each headline.
  3563. When nil, the entire headline is fontified.
  3564. Changing it requires restart of `font-lock-mode' to become effective
  3565. also in regions already fontified."
  3566. :group 'org-appearance
  3567. :type 'boolean)
  3568. (defcustom org-hide-leading-stars nil
  3569. "Non-nil means hide the first N-1 stars in a headline.
  3570. This works by using the face `org-hide' for these stars. This
  3571. face is white for a light background, and black for a dark
  3572. background. You may have to customize the face `org-hide' to
  3573. make this work.
  3574. Changing it requires restart of `font-lock-mode' to become effective
  3575. also in regions already fontified.
  3576. You may also set this on a per-file basis by adding one of the following
  3577. lines to the buffer:
  3578. #+STARTUP: hidestars
  3579. #+STARTUP: showstars"
  3580. :group 'org-appearance
  3581. :type 'boolean)
  3582. (defcustom org-hidden-keywords nil
  3583. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3584. For example, a value \\='(title) for this list makes the document's title
  3585. appear in the buffer without the initial \"#+TITLE:\" part."
  3586. :group 'org-appearance
  3587. :version "24.1"
  3588. :type '(set (const :tag "#+AUTHOR" author)
  3589. (const :tag "#+DATE" date)
  3590. (const :tag "#+EMAIL" email)
  3591. (const :tag "#+TITLE" title)))
  3592. (defcustom org-custom-properties nil
  3593. "List of properties (as strings) with a special meaning.
  3594. The default use of these custom properties is to let the user
  3595. hide them with `org-toggle-custom-properties-visibility'."
  3596. :group 'org-properties
  3597. :group 'org-appearance
  3598. :version "24.3"
  3599. :type '(repeat (string :tag "Property Name")))
  3600. (defcustom org-fontify-done-headline nil
  3601. "Non-nil means change the face of a headline if it is marked DONE.
  3602. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3603. When this is non-nil, the headline after the keyword is set to the
  3604. `org-headline-done' as an additional indication."
  3605. :group 'org-appearance
  3606. :type 'boolean)
  3607. (defcustom org-fontify-emphasized-text t
  3608. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3609. Changing this variable requires a restart of Emacs to take effect."
  3610. :group 'org-appearance
  3611. :type 'boolean)
  3612. (defcustom org-fontify-whole-heading-line nil
  3613. "Non-nil means fontify the whole line for headings.
  3614. This is useful when setting a background color for the
  3615. org-level-* faces."
  3616. :group 'org-appearance
  3617. :type 'boolean)
  3618. (defcustom org-highlight-latex-and-related nil
  3619. "Non-nil means highlight LaTeX related syntax in the buffer.
  3620. When non nil, the value should be a list containing any of the
  3621. following symbols:
  3622. `latex' Highlight LaTeX snippets and environments.
  3623. `script' Highlight subscript and superscript.
  3624. `entities' Highlight entities."
  3625. :group 'org-appearance
  3626. :version "24.4"
  3627. :package-version '(Org . "8.0")
  3628. :type '(choice
  3629. (const :tag "No highlighting" nil)
  3630. (set :greedy t :tag "Highlight"
  3631. (const :tag "LaTeX snippets and environments" latex)
  3632. (const :tag "Subscript and superscript" script)
  3633. (const :tag "Entities" entities))))
  3634. (defcustom org-hide-emphasis-markers nil
  3635. "Non-nil mean font-lock should hide the emphasis marker characters."
  3636. :group 'org-appearance
  3637. :type 'boolean)
  3638. (defcustom org-hide-macro-markers nil
  3639. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3640. :group 'org-appearance
  3641. :type 'boolean)
  3642. (defcustom org-pretty-entities nil
  3643. "Non-nil means show entities as UTF8 characters.
  3644. When nil, the \\name form remains in the buffer."
  3645. :group 'org-appearance
  3646. :version "24.1"
  3647. :type 'boolean)
  3648. (defcustom org-pretty-entities-include-sub-superscripts t
  3649. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3650. :group 'org-appearance
  3651. :version "24.1"
  3652. :type 'boolean)
  3653. (defvar org-emph-re nil
  3654. "Regular expression for matching emphasis.
  3655. After a match, the match groups contain these elements:
  3656. 0 The match of the full regular expression, including the characters
  3657. before and after the proper match
  3658. 1 The character before the proper match, or empty at beginning of line
  3659. 2 The proper match, including the leading and trailing markers
  3660. 3 The leading marker like * or /, indicating the type of highlighting
  3661. 4 The text between the emphasis markers, not including the markers
  3662. 5 The character after the match, empty at the end of a line")
  3663. (defvar org-verbatim-re nil
  3664. "Regular expression for matching verbatim text.")
  3665. (defvar org-emphasis-regexp-components) ; defined just below
  3666. (defvar org-emphasis-alist) ; defined just below
  3667. (defun org-set-emph-re (var val)
  3668. "Set variable and compute the emphasis regular expression."
  3669. (set var val)
  3670. (when (and (boundp 'org-emphasis-alist)
  3671. (boundp 'org-emphasis-regexp-components)
  3672. org-emphasis-alist org-emphasis-regexp-components)
  3673. (pcase-let*
  3674. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3675. (body (if (<= nl 0) body
  3676. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3677. (template
  3678. (format (concat "\\([%s]\\|^\\)" ;before markers
  3679. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3680. "\\([%s]\\|$\\)") ;after markers
  3681. pre border border body border post)))
  3682. (setq org-emph-re (format template "*/_+"))
  3683. (setq org-verbatim-re (format template "=~")))))
  3684. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3685. ;; set this option proved cumbersome. See this message/thread:
  3686. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3687. (defvar org-emphasis-regexp-components
  3688. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3689. "Components used to build the regular expression for emphasis.
  3690. This is a list with five entries. Terminology: In an emphasis string
  3691. like \" *strong word* \", we call the initial space PREMATCH, the final
  3692. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3693. and \"trong wor\" is the body. The different components in this variable
  3694. specify what is allowed/forbidden in each part:
  3695. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3696. post Chars allowed as postmatch. End of line will be allowed too.
  3697. border The chars *forbidden* as border characters.
  3698. body-regexp A regexp like \".\" to match a body character. Don't use
  3699. non-shy groups here, and don't allow newline here.
  3700. newline The maximum number of newlines allowed in an emphasis exp.
  3701. You need to reload Org or to restart Emacs after setting this.")
  3702. (defcustom org-emphasis-alist
  3703. '(("*" bold)
  3704. ("/" italic)
  3705. ("_" underline)
  3706. ("=" org-verbatim verbatim)
  3707. ("~" org-code verbatim)
  3708. ("+" (:strike-through t)))
  3709. "Alist of characters and faces to emphasize text.
  3710. Text starting and ending with a special character will be emphasized,
  3711. for example *bold*, _underlined_ and /italic/. This variable sets the
  3712. marker characters and the face to be used by font-lock for highlighting
  3713. in Org buffers.
  3714. You need to reload Org or to restart Emacs after customizing this."
  3715. :group 'org-appearance
  3716. :set 'org-set-emph-re
  3717. :version "24.4"
  3718. :package-version '(Org . "8.0")
  3719. :type '(repeat
  3720. (list
  3721. (string :tag "Marker character")
  3722. (choice
  3723. (face :tag "Font-lock-face")
  3724. (plist :tag "Face property list"))
  3725. (option (const verbatim)))))
  3726. (defvar org-protecting-blocks '("src" "example" "export")
  3727. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3728. This is needed for font-lock setup.")
  3729. ;;; Functions and variables from their packages
  3730. ;; Declared here to avoid compiler warnings
  3731. (defvar mark-active)
  3732. ;; Various packages
  3733. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3734. (declare-function calendar-forward-day "cal-move" (arg))
  3735. (declare-function calendar-goto-date "cal-move" (date))
  3736. (declare-function calendar-goto-today "cal-move" ())
  3737. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3738. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3739. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3740. (declare-function cdlatex-tab "ext:cdlatex" ())
  3741. (declare-function dired-get-filename
  3742. "dired"
  3743. (&optional localp no-error-if-not-filep))
  3744. (declare-function iswitchb-read-buffer
  3745. "iswitchb"
  3746. (prompt &optional
  3747. default require-match _predicate start matches-set))
  3748. (declare-function org-agenda-change-all-lines
  3749. "org-agenda"
  3750. (newhead hdmarker &optional fixface just-this))
  3751. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3752. "org-agenda"
  3753. (&optional end))
  3754. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3755. (declare-function org-agenda-format-item
  3756. "org-agenda"
  3757. (extra txt &optional level category tags dotime
  3758. remove-re habitp))
  3759. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3760. (declare-function org-agenda-save-markers-for-cut-and-paste
  3761. "org-agenda"
  3762. (beg end))
  3763. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3764. (declare-function org-agenda-skip "org-agenda" ())
  3765. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3766. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3767. (declare-function org-indent-mode "org-indent" (&optional arg))
  3768. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3769. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3770. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3771. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3772. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3773. (declare-function parse-time-string "parse-time" (string))
  3774. (defvar align-mode-rules-list)
  3775. (defvar calc-embedded-close-formula)
  3776. (defvar calc-embedded-open-formula)
  3777. (defvar calc-embedded-open-mode)
  3778. (defvar font-lock-unfontify-region-function)
  3779. (defvar iswitchb-temp-buflist)
  3780. (defvar org-agenda-tags-todo-honor-ignore-options)
  3781. (defvar remember-data-file)
  3782. (defvar texmathp-why)
  3783. ;;;###autoload
  3784. (defun turn-on-orgtbl ()
  3785. "Unconditionally turn on `orgtbl-mode'."
  3786. (require 'org-table)
  3787. (orgtbl-mode 1))
  3788. (defun org-at-table-p (&optional table-type)
  3789. "Non-nil if the cursor is inside an Org table.
  3790. If TABLE-TYPE is non-nil, also check for table.el-type tables."
  3791. (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
  3792. (or (not (derived-mode-p 'org-mode))
  3793. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3794. (and e (or table-type
  3795. (eq 'org (org-element-property :type e))))))))
  3796. (defun org-at-table.el-p ()
  3797. "Non-nil when point is at a table.el table."
  3798. (and (org-match-line "[ \t]*[|+]")
  3799. (let ((element (org-element-at-point)))
  3800. (and (eq (org-element-type element) 'table)
  3801. (eq (org-element-property :type element) 'table.el)))))
  3802. (defun org-at-table-hline-p ()
  3803. "Non-nil when point is inside a hline in a table.
  3804. Assume point is already in a table."
  3805. (org-match-line org-table-hline-regexp))
  3806. (defun org-table-map-tables (function &optional quietly)
  3807. "Apply FUNCTION to the start of all tables in the buffer."
  3808. (org-with-wide-buffer
  3809. (goto-char (point-min))
  3810. (while (re-search-forward org-table-any-line-regexp nil t)
  3811. (unless quietly
  3812. (message "Mapping tables: %d%%"
  3813. (floor (* 100.0 (point)) (buffer-size))))
  3814. (beginning-of-line 1)
  3815. (when (and (looking-at org-table-line-regexp)
  3816. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3817. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3818. (save-excursion (funcall function))
  3819. (or (looking-at org-table-line-regexp)
  3820. (forward-char 1)))
  3821. (re-search-forward org-table-any-border-regexp nil 1)))
  3822. (unless quietly (message "Mapping tables: done")))
  3823. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3824. (declare-function org-clock-update-mode-line "org-clock" ())
  3825. (declare-function org-resolve-clocks "org-clock"
  3826. (&optional also-non-dangling-p prompt last-valid))
  3827. (defun org-at-TBLFM-p (&optional pos)
  3828. "Non-nil when point (or POS) is in #+TBLFM line."
  3829. (save-excursion
  3830. (goto-char (or pos (point)))
  3831. (beginning-of-line)
  3832. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3833. (eq (org-element-type (org-element-at-point)) 'table))))
  3834. (defvar org-clock-start-time)
  3835. (defvar org-clock-marker (make-marker)
  3836. "Marker recording the last clock-in.")
  3837. (defvar org-clock-hd-marker (make-marker)
  3838. "Marker recording the last clock-in, but the headline position.")
  3839. (defvar org-clock-heading ""
  3840. "The heading of the current clock entry.")
  3841. (defun org-clock-is-active ()
  3842. "Return the buffer where the clock is currently running.
  3843. Return nil if no clock is running."
  3844. (marker-buffer org-clock-marker))
  3845. (defun org-check-running-clock ()
  3846. "Check if the current buffer contains the running clock.
  3847. If yes, offer to stop it and to save the buffer with the changes."
  3848. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3849. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3850. (buffer-name))))
  3851. (org-clock-out)
  3852. (when (y-or-n-p "Save changed buffer?")
  3853. (save-buffer))))
  3854. (defun org-clocktable-try-shift (dir n)
  3855. "Check if this line starts a clock table, if yes, shift the time block."
  3856. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3857. (org-clocktable-shift dir n)))
  3858. ;;;###autoload
  3859. (defun org-clock-persistence-insinuate ()
  3860. "Set up hooks for clock persistence."
  3861. (require 'org-clock)
  3862. (add-hook 'org-mode-hook 'org-clock-load)
  3863. (add-hook 'kill-emacs-hook 'org-clock-save))
  3864. (defgroup org-archive nil
  3865. "Options concerning archiving in Org mode."
  3866. :tag "Org Archive"
  3867. :group 'org-structure)
  3868. (defcustom org-archive-location "%s_archive::"
  3869. "The location where subtrees should be archived.
  3870. The value of this variable is a string, consisting of two parts,
  3871. separated by a double-colon. The first part is a filename and
  3872. the second part is a headline.
  3873. When the filename is omitted, archiving happens in the same file.
  3874. %s in the filename will be replaced by the current file
  3875. name (without the directory part). Archiving to a different file
  3876. is useful to keep archived entries from contributing to the
  3877. Org Agenda.
  3878. The archived entries will be filed as subtrees of the specified
  3879. headline. When the headline is omitted, the subtrees are simply
  3880. filed away at the end of the file, as top-level entries. Also in
  3881. the heading you can use %s to represent the file name, this can be
  3882. useful when using the same archive for a number of different files.
  3883. Here are a few examples:
  3884. \"%s_archive::\"
  3885. If the current file is Projects.org, archive in file
  3886. Projects.org_archive, as top-level trees. This is the default.
  3887. \"::* Archived Tasks\"
  3888. Archive in the current file, under the top-level headline
  3889. \"* Archived Tasks\".
  3890. \"~/org/archive.org::\"
  3891. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3892. \"~/org/archive.org::* From %s\"
  3893. Archive in file ~/org/archive.org (absolute path), under headlines
  3894. \"From FILENAME\" where file name is the current file name.
  3895. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3896. The \"datetree/\" string is special, signifying to archive
  3897. items to the datetree. Items are placed in either the CLOSED
  3898. date of the item, or the current date if there is no CLOSED date.
  3899. The heading will be a subentry to the current date. There doesn't
  3900. need to be a heading, but there always needs to be a slash after
  3901. datetree. For example, to store archived items directly in the
  3902. datetree, use \"~/org/datetree.org::datetree/\".
  3903. \"basement::** Finished Tasks\"
  3904. Archive in file ./basement (relative path), as level 3 trees
  3905. below the level 2 heading \"** Finished Tasks\".
  3906. You may set this option on a per-file basis by adding to the buffer a
  3907. line like
  3908. #+ARCHIVE: basement::** Finished Tasks
  3909. You may also define it locally for a subtree by setting an ARCHIVE property
  3910. in the entry. If such a property is found in an entry, or anywhere up
  3911. the hierarchy, it will be used."
  3912. :group 'org-archive
  3913. :type 'string)
  3914. (defcustom org-agenda-skip-archived-trees t
  3915. "Non-nil means the agenda will skip any items located in archived trees.
  3916. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3917. variable is no longer recommended, you should leave it at the value t.
  3918. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3919. :group 'org-archive
  3920. :group 'org-agenda-skip
  3921. :type 'boolean)
  3922. (defcustom org-columns-skip-archived-trees t
  3923. "Non-nil means ignore archived trees when creating column view."
  3924. :group 'org-archive
  3925. :group 'org-properties
  3926. :type 'boolean)
  3927. (defcustom org-cycle-open-archived-trees nil
  3928. "Non-nil means `org-cycle' will open archived trees.
  3929. An archived tree is a tree marked with the tag ARCHIVE.
  3930. When nil, archived trees will stay folded. You can still open them with
  3931. normal outline commands like `show-all', but not with the cycling commands."
  3932. :group 'org-archive
  3933. :group 'org-cycle
  3934. :type 'boolean)
  3935. (defcustom org-sparse-tree-open-archived-trees nil
  3936. "Non-nil means sparse tree construction shows matches in archived trees.
  3937. When nil, matches in these trees are highlighted, but the trees are kept in
  3938. collapsed state."
  3939. :group 'org-archive
  3940. :group 'org-sparse-trees
  3941. :type 'boolean)
  3942. (defcustom org-sparse-tree-default-date-type nil
  3943. "The default date type when building a sparse tree.
  3944. When this is nil, a date is a scheduled or a deadline timestamp.
  3945. Otherwise, these types are allowed:
  3946. all: all timestamps
  3947. active: only active timestamps (<...>)
  3948. inactive: only inactive timestamps ([...])
  3949. scheduled: only scheduled timestamps
  3950. deadline: only deadline timestamps"
  3951. :type '(choice (const :tag "Scheduled or deadline" nil)
  3952. (const :tag "All timestamps" all)
  3953. (const :tag "Only active timestamps" active)
  3954. (const :tag "Only inactive timestamps" inactive)
  3955. (const :tag "Only scheduled timestamps" scheduled)
  3956. (const :tag "Only deadline timestamps" deadline)
  3957. (const :tag "Only closed timestamps" closed))
  3958. :version "26.1"
  3959. :package-version '(Org . "8.3")
  3960. :group 'org-sparse-trees)
  3961. (defun org-cycle-hide-archived-subtrees (state)
  3962. "Re-hide all archived subtrees after a visibility state change.
  3963. STATE should be one of the symbols listed in the docstring of
  3964. `org-cycle-hook'."
  3965. (when (and (not org-cycle-open-archived-trees)
  3966. (not (memq state '(overview folded))))
  3967. (save-excursion
  3968. (let* ((globalp (memq state '(contents all)))
  3969. (beg (if globalp (point-min) (point)))
  3970. (end (if globalp (point-max) (org-end-of-subtree t))))
  3971. (org-hide-archived-subtrees beg end)
  3972. (goto-char beg)
  3973. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3974. (message "%s" (substitute-command-keys
  3975. "Subtree is archived and stays closed. Use \
  3976. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3977. (defun org-force-cycle-archived ()
  3978. "Cycle subtree even if it is archived."
  3979. (interactive)
  3980. (setq this-command 'org-cycle)
  3981. (let ((org-cycle-open-archived-trees t))
  3982. (call-interactively 'org-cycle)))
  3983. (defun org-hide-archived-subtrees (beg end)
  3984. "Re-hide all archived subtrees after a visibility state change."
  3985. (org-with-wide-buffer
  3986. (let ((case-fold-search nil)
  3987. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3988. (goto-char beg)
  3989. ;; Include headline point is currently on.
  3990. (beginning-of-line)
  3991. (while (and (< (point) end) (re-search-forward re end t))
  3992. (when (member org-archive-tag (org-get-tags nil t))
  3993. (org-flag-subtree t)
  3994. (org-end-of-subtree t))))))
  3995. (defun org-flag-subtree (flag)
  3996. (save-excursion
  3997. (org-back-to-heading t)
  3998. (org-flag-region (line-end-position)
  3999. (progn (org-end-of-subtree t) (point))
  4000. flag
  4001. 'outline)))
  4002. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4003. ;; Declare Column View Code
  4004. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4005. (declare-function org-columns-compute "org-colview" (property))
  4006. ;; Declare ID code
  4007. (declare-function org-id-store-link "org-id")
  4008. (declare-function org-id-locations-load "org-id")
  4009. (declare-function org-id-locations-save "org-id")
  4010. (defvar org-id-track-globally)
  4011. ;;; Variables for pre-computed regular expressions, all buffer local
  4012. (defvar-local org-todo-regexp nil
  4013. "Matches any of the TODO state keywords.
  4014. Since TODO keywords are case-sensitive, `case-fold-search' is
  4015. expected to be bound to nil when matching against this regexp.")
  4016. (defvar-local org-not-done-regexp nil
  4017. "Matches any of the TODO state keywords except the last one.
  4018. Since TODO keywords are case-sensitive, `case-fold-search' is
  4019. expected to be bound to nil when matching against this regexp.")
  4020. (defvar-local org-not-done-heading-regexp nil
  4021. "Matches a TODO headline that is not done.
  4022. Since TODO keywords are case-sensitive, `case-fold-search' is
  4023. expected to be bound to nil when matching against this regexp.")
  4024. (defvar-local org-todo-line-regexp nil
  4025. "Matches a headline and puts TODO state into group 2 if present.
  4026. Since TODO keywords are case-sensitive, `case-fold-search' is
  4027. expected to be bound to nil when matching against this regexp.")
  4028. (defvar-local org-complex-heading-regexp nil
  4029. "Matches a headline and puts everything into groups:
  4030. group 1: Stars
  4031. group 2: The TODO keyword, maybe
  4032. group 3: Priority cookie
  4033. group 4: True headline
  4034. group 5: Tags
  4035. Since TODO keywords are case-sensitive, `case-fold-search' is
  4036. expected to be bound to nil when matching against this regexp.")
  4037. (defvar-local org-complex-heading-regexp-format nil
  4038. "Printf format to make regexp to match an exact headline.
  4039. This regexp will match the headline of any node which has the
  4040. exact headline text that is put into the format, but may have any
  4041. TODO state, priority and tags.")
  4042. (defvar-local org-todo-line-tags-regexp nil
  4043. "Matches a headline and puts TODO state into group 2 if present.
  4044. Also put tags into group 4 if tags are present.")
  4045. (defconst org-plain-time-of-day-regexp
  4046. (concat
  4047. "\\(\\<[012]?[0-9]"
  4048. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4049. "\\(--?"
  4050. "\\(\\<[012]?[0-9]"
  4051. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4052. "\\)?")
  4053. "Regular expression to match a plain time or time range.
  4054. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4055. groups carry important information:
  4056. 0 the full match
  4057. 1 the first time, range or not
  4058. 8 the second time, if it is a range.")
  4059. (defconst org-plain-time-extension-regexp
  4060. (concat
  4061. "\\(\\<[012]?[0-9]"
  4062. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4063. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4064. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4065. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4066. groups carry important information:
  4067. 0 the full match
  4068. 7 hours of duration
  4069. 9 minutes of duration")
  4070. (defconst org-stamp-time-of-day-regexp
  4071. (concat
  4072. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4073. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4074. "\\(--?"
  4075. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4076. "Regular expression to match a timestamp time or time range.
  4077. After a match, the following groups carry important information:
  4078. 0 the full match
  4079. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4080. 2 the first time, range or not
  4081. 4 the second time, if it is a range.")
  4082. (defconst org-startup-options
  4083. '(("fold" org-startup-folded t)
  4084. ("overview" org-startup-folded t)
  4085. ("nofold" org-startup-folded nil)
  4086. ("showall" org-startup-folded nil)
  4087. ("showeverything" org-startup-folded showeverything)
  4088. ("content" org-startup-folded content)
  4089. ("indent" org-startup-indented t)
  4090. ("noindent" org-startup-indented nil)
  4091. ("hidestars" org-hide-leading-stars t)
  4092. ("showstars" org-hide-leading-stars nil)
  4093. ("odd" org-odd-levels-only t)
  4094. ("oddeven" org-odd-levels-only nil)
  4095. ("align" org-startup-align-all-tables t)
  4096. ("noalign" org-startup-align-all-tables nil)
  4097. ("shrink" org-startup-shrink-all-tables t)
  4098. ("inlineimages" org-startup-with-inline-images t)
  4099. ("noinlineimages" org-startup-with-inline-images nil)
  4100. ("latexpreview" org-startup-with-latex-preview t)
  4101. ("nolatexpreview" org-startup-with-latex-preview nil)
  4102. ("customtime" org-display-custom-times t)
  4103. ("logdone" org-log-done time)
  4104. ("lognotedone" org-log-done note)
  4105. ("nologdone" org-log-done nil)
  4106. ("lognoteclock-out" org-log-note-clock-out t)
  4107. ("nolognoteclock-out" org-log-note-clock-out nil)
  4108. ("logrepeat" org-log-repeat state)
  4109. ("lognoterepeat" org-log-repeat note)
  4110. ("logdrawer" org-log-into-drawer t)
  4111. ("nologdrawer" org-log-into-drawer nil)
  4112. ("logstatesreversed" org-log-states-order-reversed t)
  4113. ("nologstatesreversed" org-log-states-order-reversed nil)
  4114. ("nologrepeat" org-log-repeat nil)
  4115. ("logreschedule" org-log-reschedule time)
  4116. ("lognotereschedule" org-log-reschedule note)
  4117. ("nologreschedule" org-log-reschedule nil)
  4118. ("logredeadline" org-log-redeadline time)
  4119. ("lognoteredeadline" org-log-redeadline note)
  4120. ("nologredeadline" org-log-redeadline nil)
  4121. ("logrefile" org-log-refile time)
  4122. ("lognoterefile" org-log-refile note)
  4123. ("nologrefile" org-log-refile nil)
  4124. ("fninline" org-footnote-define-inline t)
  4125. ("nofninline" org-footnote-define-inline nil)
  4126. ("fnlocal" org-footnote-section nil)
  4127. ("fnauto" org-footnote-auto-label t)
  4128. ("fnprompt" org-footnote-auto-label nil)
  4129. ("fnconfirm" org-footnote-auto-label confirm)
  4130. ("fnplain" org-footnote-auto-label plain)
  4131. ("fnadjust" org-footnote-auto-adjust t)
  4132. ("nofnadjust" org-footnote-auto-adjust nil)
  4133. ("constcgs" constants-unit-system cgs)
  4134. ("constSI" constants-unit-system SI)
  4135. ("noptag" org-tag-persistent-alist nil)
  4136. ("hideblocks" org-hide-block-startup t)
  4137. ("nohideblocks" org-hide-block-startup nil)
  4138. ("beamer" org-startup-with-beamer-mode t)
  4139. ("entitiespretty" org-pretty-entities t)
  4140. ("entitiesplain" org-pretty-entities nil))
  4141. "Variable associated with STARTUP options for Org.
  4142. Each element is a list of three items: the startup options (as written
  4143. in the #+STARTUP line), the corresponding variable, and the value to set
  4144. this variable to if the option is found. An optional forth element PUSH
  4145. means to push this value onto the list in the variable.")
  4146. (defcustom org-group-tags t
  4147. "When non-nil (the default), use group tags.
  4148. This can be turned on/off through `org-toggle-tags-groups'."
  4149. :group 'org-tags
  4150. :group 'org-startup
  4151. :type 'boolean)
  4152. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4153. (defun org-toggle-tags-groups ()
  4154. "Toggle support for group tags.
  4155. Support for group tags is controlled by the option
  4156. `org-group-tags', which is non-nil by default."
  4157. (interactive)
  4158. (setq org-group-tags (not org-group-tags))
  4159. (cond ((and (derived-mode-p 'org-agenda-mode)
  4160. org-group-tags)
  4161. (org-agenda-redo))
  4162. ((derived-mode-p 'org-mode)
  4163. (let ((org-inhibit-startup t)) (org-mode))))
  4164. (message "Groups tags support has been turned %s"
  4165. (if org-group-tags "on" "off")))
  4166. (defun org-tag-add-to-alist (alist1 alist2)
  4167. "Append ALIST1 elements to ALIST2 if they are not there yet."
  4168. (cond
  4169. ((null alist2) alist1)
  4170. ((null alist1) alist2)
  4171. (t (let ((alist2-cars (mapcar (lambda (x) (car-safe x)) alist2))
  4172. to-add)
  4173. (dolist (i alist1)
  4174. (unless (member (car-safe i) alist2-cars)
  4175. (push i to-add)))
  4176. (append to-add alist2)))))
  4177. (defun org-set-regexps-and-options (&optional tags-only)
  4178. "Precompute regular expressions used in the current buffer.
  4179. When optional argument TAGS-ONLY is non-nil, only compute tags
  4180. related expressions."
  4181. (when (derived-mode-p 'org-mode)
  4182. (let ((alist (org--setup-collect-keywords
  4183. (org-make-options-regexp
  4184. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4185. (and (not tags-only)
  4186. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4187. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4188. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4189. ;; Startup options. Get this early since it does change
  4190. ;; behavior for other options (e.g., tags).
  4191. (let ((startup (cdr (assq 'startup alist))))
  4192. (dolist (option startup)
  4193. (let ((entry (assoc-string option org-startup-options t)))
  4194. (when entry
  4195. (let ((var (nth 1 entry))
  4196. (val (nth 2 entry)))
  4197. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4198. (unless (listp (symbol-value var))
  4199. (set (make-local-variable var) nil))
  4200. (add-to-list var val)))))))
  4201. (setq-local org-file-tags
  4202. (mapcar #'org-add-prop-inherited
  4203. (cdr (assq 'filetags alist))))
  4204. (setq org-current-tag-alist
  4205. (org-tag-add-to-alist
  4206. org-tag-persistent-alist
  4207. (let ((tags (cdr (assq 'tags alist))))
  4208. (if tags (org-tag-string-to-alist tags)
  4209. org-tag-alist))))
  4210. (setq org-tag-groups-alist
  4211. (org-tag-alist-to-groups org-current-tag-alist))
  4212. (unless tags-only
  4213. ;; File properties.
  4214. (setq-local org-file-properties (cdr (assq 'property alist)))
  4215. ;; Archive location.
  4216. (let ((archive (cdr (assq 'archive alist))))
  4217. (when archive (setq-local org-archive-location archive)))
  4218. ;; Category.
  4219. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4220. (when cat
  4221. (setq-local org-category (intern cat))
  4222. (setq-local org-file-properties
  4223. (org--update-property-plist
  4224. "CATEGORY" cat org-file-properties))))
  4225. ;; Columns.
  4226. (let ((column (cdr (assq 'columns alist))))
  4227. (when column (setq-local org-columns-default-format column)))
  4228. ;; Constants.
  4229. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4230. ;; Link abbreviations.
  4231. (let ((links (cdr (assq 'link alist))))
  4232. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4233. ;; Priorities.
  4234. (let ((priorities (cdr (assq 'priorities alist))))
  4235. (when priorities
  4236. (setq-local org-highest-priority (nth 0 priorities))
  4237. (setq-local org-lowest-priority (nth 1 priorities))
  4238. (setq-local org-default-priority (nth 2 priorities))))
  4239. ;; Scripts.
  4240. (let ((scripts (assq 'scripts alist)))
  4241. (when scripts
  4242. (setq-local org-use-sub-superscripts (cdr scripts))))
  4243. ;; TODO keywords.
  4244. (setq-local org-todo-kwd-alist nil)
  4245. (setq-local org-todo-key-alist nil)
  4246. (setq-local org-todo-key-trigger nil)
  4247. (setq-local org-todo-keywords-1 nil)
  4248. (setq-local org-done-keywords nil)
  4249. (setq-local org-todo-heads nil)
  4250. (setq-local org-todo-sets nil)
  4251. (setq-local org-todo-log-states nil)
  4252. (let ((todo-sequences
  4253. (or (nreverse (cdr (assq 'todo alist)))
  4254. (let ((d (default-value 'org-todo-keywords)))
  4255. (if (not (stringp (car d))) d
  4256. ;; XXX: Backward compatibility code.
  4257. (list (cons org-todo-interpretation d)))))))
  4258. (dolist (sequence todo-sequences)
  4259. (let* ((sequence (or (run-hook-with-args-until-success
  4260. 'org-todo-setup-filter-hook sequence)
  4261. sequence))
  4262. (sequence-type (car sequence))
  4263. (keywords (cdr sequence))
  4264. (sep (member "|" keywords))
  4265. names alist)
  4266. (dolist (k (remove "|" keywords))
  4267. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4268. k)
  4269. (error "Invalid TODO keyword %s" k))
  4270. (let ((name (match-string 1 k))
  4271. (key (match-string 2 k))
  4272. (log (org-extract-log-state-settings k)))
  4273. (push name names)
  4274. (push (cons name (and key (string-to-char key))) alist)
  4275. (when log (push log org-todo-log-states))))
  4276. (let* ((names (nreverse names))
  4277. (done (if sep (org-remove-keyword-keys (cdr sep))
  4278. (last names)))
  4279. (head (car names))
  4280. (tail (list sequence-type head (car done) (org-last done))))
  4281. (add-to-list 'org-todo-heads head 'append)
  4282. (push names org-todo-sets)
  4283. (setq org-done-keywords (append org-done-keywords done nil))
  4284. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4285. (setq org-todo-key-alist
  4286. (append org-todo-key-alist
  4287. (and alist
  4288. (append '((:startgroup))
  4289. (nreverse alist)
  4290. '((:endgroup))))))
  4291. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4292. (setq org-todo-sets (nreverse org-todo-sets)
  4293. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4294. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4295. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4296. ;; Compute the regular expressions and other local variables.
  4297. ;; Using `org-outline-regexp-bol' would complicate them much,
  4298. ;; because of the fixed white space at the end of that string.
  4299. (unless org-done-keywords
  4300. (setq org-done-keywords
  4301. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4302. (setq org-not-done-keywords
  4303. (org-delete-all org-done-keywords
  4304. (copy-sequence org-todo-keywords-1))
  4305. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4306. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4307. org-not-done-heading-regexp
  4308. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4309. org-todo-line-regexp
  4310. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4311. org-complex-heading-regexp
  4312. (concat "^\\(\\*+\\)"
  4313. "\\(?: +" org-todo-regexp "\\)?"
  4314. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4315. "\\(?: +\\(.*?\\)\\)??"
  4316. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4317. "[ \t]*$")
  4318. org-complex-heading-regexp-format
  4319. (concat "^\\(\\*+\\)"
  4320. "\\(?: +" org-todo-regexp "\\)?"
  4321. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4322. "\\(?: +"
  4323. ;; Stats cookies can be stuck to body.
  4324. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4325. "\\(%s\\)"
  4326. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4327. "\\)"
  4328. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4329. "[ \t]*$")
  4330. org-todo-line-tags-regexp
  4331. (concat "^\\(\\*+\\)"
  4332. "\\(?: +" org-todo-regexp "\\)?"
  4333. "\\(?: +\\(.*?\\)\\)??"
  4334. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4335. "[ \t]*$"))
  4336. (org-compute-latex-and-related-regexp)))))
  4337. (defun org--setup-collect-keywords (regexp &optional files alist)
  4338. "Return setup keywords values as an alist.
  4339. REGEXP matches a subset of setup keywords. FILES is a list of
  4340. file names already visited. It is used to avoid circular setup
  4341. files. ALIST, when non-nil, is the alist computed so far.
  4342. Return value contains the following keys: `archive', `category',
  4343. `columns', `constants', `filetags', `link', `priorities',
  4344. `property', `scripts', `startup', `tags' and `todo'."
  4345. (org-with-wide-buffer
  4346. (goto-char (point-min))
  4347. (let ((case-fold-search t))
  4348. (while (re-search-forward regexp nil t)
  4349. (let ((element (org-element-at-point)))
  4350. (when (eq (org-element-type element) 'keyword)
  4351. (let ((key (org-element-property :key element))
  4352. (value (org-element-property :value element)))
  4353. (cond
  4354. ((equal key "ARCHIVE")
  4355. (when (org-string-nw-p value)
  4356. (push (cons 'archive value) alist)))
  4357. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4358. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4359. ((equal key "CONSTANTS")
  4360. (let* ((constants (assq 'constants alist))
  4361. (store (cdr constants)))
  4362. (dolist (pair (split-string value))
  4363. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4364. pair)
  4365. (let* ((name (match-string 1 pair))
  4366. (value (match-string 2 pair))
  4367. (old (assoc name store)))
  4368. (if old (setcdr old value)
  4369. (push (cons name value) store)))))
  4370. (if constants (setcdr constants store)
  4371. (push (cons 'constants store) alist))))
  4372. ((equal key "FILETAGS")
  4373. (when (org-string-nw-p value)
  4374. (let ((old (assq 'filetags alist))
  4375. (new (apply #'nconc
  4376. (mapcar (lambda (x) (org-split-string x ":"))
  4377. (split-string value)))))
  4378. (if old (setcdr old (append new (cdr old)))
  4379. (push (cons 'filetags new) alist)))))
  4380. ((equal key "LINK")
  4381. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4382. (let ((links (assq 'link alist))
  4383. (pair (cons (match-string-no-properties 1 value)
  4384. (match-string-no-properties 2 value))))
  4385. (if links (push pair (cdr links))
  4386. (push (list 'link pair) alist)))))
  4387. ((equal key "OPTIONS")
  4388. (when (and (org-string-nw-p value)
  4389. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4390. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4391. ((equal key "PRIORITIES")
  4392. (push (cons 'priorities
  4393. (let ((prio (split-string value)))
  4394. (if (< (length prio) 3) '(?A ?C ?B)
  4395. (mapcar #'string-to-char prio))))
  4396. alist))
  4397. ((equal key "PROPERTY")
  4398. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4399. (let* ((property (assq 'property alist))
  4400. (value (org--update-property-plist
  4401. (match-string-no-properties 1 value)
  4402. (match-string-no-properties 2 value)
  4403. (cdr property))))
  4404. (if property (setcdr property value)
  4405. (push (cons 'property value) alist)))))
  4406. ((equal key "STARTUP")
  4407. (let ((startup (assq 'startup alist)))
  4408. (if startup
  4409. (setcdr startup
  4410. (append (cdr startup) (split-string value)))
  4411. (push (cons 'startup (split-string value)) alist))))
  4412. ((equal key "TAGS")
  4413. (let ((tag-cell (assq 'tags alist)))
  4414. (if tag-cell
  4415. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4416. (push (cons 'tags value) alist))))
  4417. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4418. (let ((todo (assq 'todo alist))
  4419. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4420. (split-string value))))
  4421. (if todo (push value (cdr todo))
  4422. (push (list 'todo value) alist))))
  4423. ((equal key "SETUPFILE")
  4424. (unless buffer-read-only ; Do not check in Gnus messages.
  4425. (let ((f (and (org-string-nw-p value)
  4426. (expand-file-name
  4427. (org-unbracket-string "\"" "\"" value)))))
  4428. (when (and f (file-readable-p f) (not (member f files)))
  4429. (with-temp-buffer
  4430. (setq default-directory (file-name-directory f))
  4431. (insert-file-contents f)
  4432. (setq alist
  4433. ;; Fake Org mode to benefit from cache
  4434. ;; without recurring needlessly.
  4435. (let ((major-mode 'org-mode))
  4436. (org--setup-collect-keywords
  4437. regexp (cons f files) alist)))))))))))))))
  4438. alist)
  4439. (defun org-tag-string-to-alist (s)
  4440. "Return tag alist associated to string S.
  4441. S is a value for TAGS keyword or produced with
  4442. `org-tag-alist-to-string'. Return value is an alist suitable for
  4443. `org-tag-alist' or `org-tag-persistent-alist'."
  4444. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4445. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  4446. "\\(?:(\\(.\\))\\)?\\'"))
  4447. alist group-flag)
  4448. (dolist (tokens lines (cdr (nreverse alist)))
  4449. (push '(:newline) alist)
  4450. (while tokens
  4451. (let ((token (pop tokens)))
  4452. (pcase token
  4453. ("{"
  4454. (push '(:startgroup) alist)
  4455. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4456. ("}"
  4457. (push '(:endgroup) alist)
  4458. (setq group-flag nil))
  4459. ("["
  4460. (push '(:startgrouptag) alist)
  4461. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4462. ("]"
  4463. (push '(:endgrouptag) alist)
  4464. (setq group-flag nil))
  4465. (":"
  4466. (push '(:grouptags) alist))
  4467. ((guard (string-match tag-re token))
  4468. (let ((tag (match-string 1 token))
  4469. (key (and (match-beginning 2)
  4470. (string-to-char (match-string 2 token)))))
  4471. ;; Push all tags in groups, no matter if they already
  4472. ;; appear somewhere else in the list.
  4473. (when (or group-flag (not (assoc tag alist)))
  4474. (push (cons tag key) alist))))))))))
  4475. (defun org-tag-alist-to-string (alist &optional skip-key)
  4476. "Return tag string associated to ALIST.
  4477. ALIST is an alist, as defined in `org-tag-alist' or
  4478. `org-tag-persistent-alist', or produced with
  4479. `org-tag-string-to-alist'.
  4480. Return value is a string suitable as a value for \"TAGS\"
  4481. keyword.
  4482. When optional argument SKIP-KEY is non-nil, skip selection keys
  4483. next to tags."
  4484. (mapconcat (lambda (token)
  4485. (pcase token
  4486. (`(:startgroup) "{")
  4487. (`(:endgroup) "}")
  4488. (`(:startgrouptag) "[")
  4489. (`(:endgrouptag) "]")
  4490. (`(:grouptags) ":")
  4491. (`(:newline) "\\n")
  4492. ((and
  4493. (guard (not skip-key))
  4494. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4495. (format "%s(%c)" tag key))
  4496. (`(,(and tag (pred stringp)) . ,_) tag)
  4497. (_ (user-error "Invalid tag token: %S" token))))
  4498. alist
  4499. " "))
  4500. (defun org-tag-alist-to-groups (alist)
  4501. "Return group alist from tag ALIST.
  4502. ALIST is an alist, as defined in `org-tag-alist' or
  4503. `org-tag-persistent-alist', or produced with
  4504. `org-tag-string-to-alist'. Return value is an alist following
  4505. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4506. a string, summarizing TAGS, as a list of strings."
  4507. (let (groups group-status current-group)
  4508. (dolist (token alist (nreverse groups))
  4509. (pcase token
  4510. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4511. (`(,(or :endgroup :endgrouptag))
  4512. (when (eq group-status 'append)
  4513. (push (nreverse current-group) groups))
  4514. (setq group-status nil current-group nil))
  4515. (`(:grouptags) (setq group-status 'append))
  4516. ((and `(,tag . ,_) (guard group-status))
  4517. (if (eq group-status 'append) (push tag current-group)
  4518. (setq current-group (list tag))))
  4519. (_ nil)))))
  4520. (defvar org--file-cache (make-hash-table :test #'equal)
  4521. "Hash table to store contents of files referenced via a URL.
  4522. This is the cache of file URLs read using `org-file-contents'.")
  4523. (defun org-reset-file-cache ()
  4524. "Reset the cache of files downloaded by `org-file-contents'."
  4525. (clrhash org--file-cache))
  4526. (defun org-file-url-p (file)
  4527. "Non-nil if FILE is a URL."
  4528. (require 'ffap)
  4529. (string-match-p ffap-url-regexp file))
  4530. (defun org-file-contents (file &optional noerror nocache)
  4531. "Return the contents of FILE, as a string.
  4532. FILE can be a file name or URL.
  4533. If FILE is a URL, download the contents. If the URL contents are
  4534. already cached in the `org--file-cache' hash table, the download step
  4535. is skipped.
  4536. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4537. from file or URL.
  4538. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4539. is available. This option applies only if FILE is a URL."
  4540. (let* ((is-url (org-file-url-p file))
  4541. (cache (and is-url
  4542. (not nocache)
  4543. (gethash file org--file-cache))))
  4544. (cond
  4545. (cache)
  4546. (is-url
  4547. (with-current-buffer (url-retrieve-synchronously file)
  4548. (goto-char (point-min))
  4549. ;; Move point to after the url-retrieve header.
  4550. (search-forward "\n\n" nil :move)
  4551. ;; Search for the success code only in the url-retrieve header.
  4552. (if (save-excursion
  4553. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4554. ;; Update the cache `org--file-cache' and return contents.
  4555. (puthash file
  4556. (buffer-substring-no-properties (point) (point-max))
  4557. org--file-cache)
  4558. (funcall (if noerror #'message #'user-error)
  4559. "Unable to fetch file from %S"
  4560. file))))
  4561. (t
  4562. (with-temp-buffer
  4563. (condition-case nil
  4564. (progn
  4565. (insert-file-contents file)
  4566. (buffer-string))
  4567. (file-error
  4568. (funcall (if noerror #'message #'user-error)
  4569. "Unable to read file %S"
  4570. file))))))))
  4571. (defun org-extract-log-state-settings (x)
  4572. "Extract the log state setting from a TODO keyword string.
  4573. This will extract info from a string like \"WAIT(w@/!)\"."
  4574. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4575. (let ((kw (match-string 1 x))
  4576. (log1 (and (match-end 3) (match-string 3 x)))
  4577. (log2 (and (match-end 4) (match-string 4 x))))
  4578. (and (or log1 log2)
  4579. (list kw
  4580. (and log1 (if (equal log1 "!") 'time 'note))
  4581. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4582. (defun org-remove-keyword-keys (list)
  4583. "Remove a pair of parenthesis at the end of each string in LIST."
  4584. (mapcar (lambda (x)
  4585. (if (string-match "(.*)$" x)
  4586. (substring x 0 (match-beginning 0))
  4587. x))
  4588. list))
  4589. (defun org-assign-fast-keys (alist)
  4590. "Assign fast keys to a keyword-key alist.
  4591. Respect keys that are already there."
  4592. (let (new e (alt ?0))
  4593. (while (setq e (pop alist))
  4594. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4595. (cdr e)) ;; Key already assigned.
  4596. (push e new)
  4597. (let ((clist (string-to-list (downcase (car e))))
  4598. (used (append new alist)))
  4599. (when (= (car clist) ?@)
  4600. (pop clist))
  4601. (while (and clist (rassoc (car clist) used))
  4602. (pop clist))
  4603. (unless clist
  4604. (while (rassoc alt used)
  4605. (cl-incf alt)))
  4606. (push (cons (car e) (or (car clist) alt)) new))))
  4607. (nreverse new)))
  4608. ;;; Some variables used in various places
  4609. (defvar org-window-configuration nil
  4610. "Used in various places to store a window configuration.")
  4611. (defvar org-selected-window nil
  4612. "Used in various places to store a window configuration.")
  4613. (defvar org-finish-function nil
  4614. "Function to be called when `C-c C-c' is used.
  4615. This is for getting out of special buffers like capture.")
  4616. (defvar org-last-state)
  4617. ;; Defined somewhere in this file, but used before definition.
  4618. (defvar org-entities) ;; defined in org-entities.el
  4619. (defvar org-struct-menu)
  4620. (defvar org-org-menu)
  4621. (defvar org-tbl-menu)
  4622. ;;;; Define the Org mode
  4623. ;; We use a before-change function to check if a table might need
  4624. ;; an update.
  4625. (defvar org-table-may-need-update t
  4626. "Indicates that a table might need an update.
  4627. This variable is set by `org-before-change-function'.
  4628. `org-table-align' sets it back to nil.")
  4629. (defun org-before-change-function (_beg _end)
  4630. "Every change indicates that a table might need an update."
  4631. (setq org-table-may-need-update t))
  4632. (defvar org-mode-map)
  4633. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4634. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4635. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4636. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4637. (defvar org-table-buffer-is-an nil)
  4638. (defvar bidi-paragraph-direction)
  4639. (defvar buffer-face-mode-face)
  4640. (require 'outline)
  4641. ;; Other stuff we need.
  4642. (require 'time-date)
  4643. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4644. (require 'easymenu)
  4645. (autoload 'easy-menu-add "easymenu")
  4646. (require 'overlay)
  4647. ;; (require 'org-macs) moved higher up in the file before it is first used
  4648. (require 'org-entities)
  4649. ;; (require 'org-compat) moved higher up in the file before it is first used
  4650. (require 'org-faces)
  4651. (require 'org-list)
  4652. (require 'org-pcomplete)
  4653. (require 'org-src)
  4654. (require 'org-footnote)
  4655. (require 'org-macro)
  4656. ;; babel
  4657. (require 'ob)
  4658. ;;;###autoload
  4659. (define-derived-mode org-mode outline-mode "Org"
  4660. "Outline-based notes management and organizer, alias
  4661. \"Carsten's outline-mode for keeping track of everything.\"
  4662. Org mode develops organizational tasks around a NOTES file which
  4663. contains information about projects as plain text. Org mode is
  4664. implemented on top of Outline mode, which is ideal to keep the content
  4665. of large files well structured. It supports ToDo items, deadlines and
  4666. time stamps, which magically appear in the diary listing of the Emacs
  4667. calendar. Tables are easily created with a built-in table editor.
  4668. Plain text URL-like links connect to websites, emails (VM), Usenet
  4669. messages (Gnus), BBDB entries, and any files related to the project.
  4670. For printing and sharing of notes, an Org file (or a part of it)
  4671. can be exported as a structured ASCII or HTML file.
  4672. The following commands are available:
  4673. \\{org-mode-map}"
  4674. ;; Get rid of Outline menus, they are not needed
  4675. ;; Need to do this here because define-derived-mode sets up
  4676. ;; the keymap so late. Still, it is a waste to call this each time
  4677. ;; we switch another buffer into Org mode.
  4678. (define-key org-mode-map [menu-bar headings] 'undefined)
  4679. (define-key org-mode-map [menu-bar hide] 'undefined)
  4680. (define-key org-mode-map [menu-bar show] 'undefined)
  4681. (org-load-modules-maybe)
  4682. (org-install-agenda-files-menu)
  4683. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4684. (add-to-invisibility-spec '(org-hide-block . t))
  4685. (add-to-invisibility-spec '(org-hide-drawer . t))
  4686. (setq-local outline-regexp org-outline-regexp)
  4687. (setq-local outline-level 'org-outline-level)
  4688. (setq bidi-paragraph-direction 'left-to-right)
  4689. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4690. (unless org-display-table
  4691. (setq org-display-table (make-display-table)))
  4692. (set-display-table-slot
  4693. org-display-table 4
  4694. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4695. org-ellipsis)))
  4696. (setq buffer-display-table org-display-table))
  4697. (org-set-regexps-and-options)
  4698. (org-set-font-lock-defaults)
  4699. (when (and org-tag-faces (not org-tags-special-faces-re))
  4700. ;; tag faces set outside customize.... force initialization.
  4701. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4702. ;; Calc embedded
  4703. (setq-local calc-embedded-open-mode "# ")
  4704. ;; Modify a few syntax entries
  4705. (modify-syntax-entry ?@ "w")
  4706. (modify-syntax-entry ?\" "\"")
  4707. (modify-syntax-entry ?\\ "_")
  4708. (modify-syntax-entry ?~ "_")
  4709. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4710. ;; Activate before-change-function
  4711. (setq-local org-table-may-need-update t)
  4712. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4713. ;; Check for running clock before killing a buffer
  4714. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4715. ;; Initialize macros templates.
  4716. (org-macro-initialize-templates)
  4717. ;; Initialize radio targets.
  4718. (org-update-radio-target-regexp)
  4719. ;; Indentation.
  4720. (setq-local indent-line-function 'org-indent-line)
  4721. (setq-local indent-region-function 'org-indent-region)
  4722. ;; Filling and auto-filling.
  4723. (org-setup-filling)
  4724. ;; Comments.
  4725. (org-setup-comments-handling)
  4726. ;; Initialize cache.
  4727. (org-element-cache-reset)
  4728. ;; Beginning/end of defun
  4729. (setq-local beginning-of-defun-function 'org-backward-element)
  4730. (setq-local end-of-defun-function
  4731. (lambda ()
  4732. (if (not (org-at-heading-p))
  4733. (org-forward-element)
  4734. (org-forward-element)
  4735. (forward-char -1))))
  4736. ;; Next error for sparse trees
  4737. (setq-local next-error-function 'org-occur-next-match)
  4738. ;; Make sure dependence stuff works reliably, even for users who set it
  4739. ;; too late :-(
  4740. (if org-enforce-todo-dependencies
  4741. (add-hook 'org-blocker-hook
  4742. 'org-block-todo-from-children-or-siblings-or-parent)
  4743. (remove-hook 'org-blocker-hook
  4744. 'org-block-todo-from-children-or-siblings-or-parent))
  4745. (if org-enforce-todo-checkbox-dependencies
  4746. (add-hook 'org-blocker-hook
  4747. 'org-block-todo-from-checkboxes)
  4748. (remove-hook 'org-blocker-hook
  4749. 'org-block-todo-from-checkboxes))
  4750. ;; Align options lines
  4751. (setq-local
  4752. align-mode-rules-list
  4753. '((org-in-buffer-settings
  4754. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4755. (modes . '(org-mode)))))
  4756. ;; Imenu
  4757. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4758. ;; Make isearch reveal context
  4759. (setq-local outline-isearch-open-invisible-function
  4760. (lambda (&rest _) (org-show-context 'isearch)))
  4761. ;; Setup the pcomplete hooks
  4762. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4763. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4764. (setq-local pcomplete-default-completion-function 'ignore)
  4765. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4766. (setq-local pcomplete-termination-string "")
  4767. (setq-local buffer-face-mode-face 'org-default)
  4768. ;; If empty file that did not turn on Org mode automatically, make
  4769. ;; it to.
  4770. (when (and org-insert-mode-line-in-empty-file
  4771. (called-interactively-p 'any)
  4772. (= (point-min) (point-max)))
  4773. (insert "# -*- mode: org -*-\n\n"))
  4774. (unless org-inhibit-startup
  4775. (org-unmodified
  4776. (when org-startup-with-beamer-mode (org-beamer-mode))
  4777. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4778. (org-table-map-tables
  4779. (cond ((and org-startup-align-all-tables
  4780. org-startup-shrink-all-tables)
  4781. (lambda () (org-table-align) (org-table-shrink)))
  4782. (org-startup-align-all-tables #'org-table-align)
  4783. (t #'org-table-shrink))
  4784. t))
  4785. (when org-startup-with-inline-images (org-display-inline-images))
  4786. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4787. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4788. (when org-startup-truncated (setq truncate-lines t))
  4789. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4790. (org-refresh-effort-properties)))
  4791. ;; Try to set `org-hide' face correctly.
  4792. (let ((foreground (org-find-invisible-foreground)))
  4793. (when foreground
  4794. (set-face-foreground 'org-hide foreground))))
  4795. ;; Update `customize-package-emacs-version-alist'
  4796. (add-to-list 'customize-package-emacs-version-alist
  4797. '(Org ("8.0" . "24.4")
  4798. ("8.1" . "24.4")
  4799. ("8.2" . "24.4")
  4800. ("8.2.7" . "24.4")
  4801. ("8.3" . "26.1")
  4802. ("9.0" . "26.1")
  4803. ("9.1" . "26.1")
  4804. ("9.2" . "27.1")))
  4805. (defvar org-mode-transpose-word-syntax-table
  4806. (let ((st (make-syntax-table text-mode-syntax-table)))
  4807. (dolist (c org-emphasis-alist st)
  4808. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4809. (when (fboundp 'abbrev-table-put)
  4810. (abbrev-table-put org-mode-abbrev-table
  4811. :parents (list text-mode-abbrev-table)))
  4812. (defun org-find-invisible-foreground ()
  4813. (let ((candidates (remove
  4814. "unspecified-bg"
  4815. (nconc
  4816. (list (face-background 'default)
  4817. (face-background 'org-default))
  4818. (mapcar
  4819. (lambda (alist)
  4820. (when (boundp alist)
  4821. (cdr (assq 'background-color (symbol-value alist)))))
  4822. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4823. (list (face-foreground 'org-hide))))))
  4824. (car (remove nil candidates))))
  4825. (defun org-current-time (&optional rounding-minutes past)
  4826. "Current time, possibly rounded to ROUNDING-MINUTES.
  4827. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4828. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4829. the rounding returns a past time."
  4830. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4831. (car org-time-stamp-rounding-minutes)))
  4832. (time (decode-time)) res)
  4833. (if (< r 1)
  4834. (current-time)
  4835. (setq res
  4836. (apply 'encode-time
  4837. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4838. (nthcdr 2 time))))
  4839. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4840. (seconds-to-time (- (float-time res) (* r 60)))
  4841. res))))
  4842. (defun org-today ()
  4843. "Return today date, considering `org-extend-today-until'."
  4844. (time-to-days
  4845. (time-subtract (current-time)
  4846. (list 0 (* 3600 org-extend-today-until) 0))))
  4847. ;;;; Font-Lock stuff, including the activators
  4848. (defvar org-mouse-map (make-sparse-keymap))
  4849. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4850. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4851. (when org-mouse-1-follows-link
  4852. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4853. (when org-tab-follows-link
  4854. (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
  4855. (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
  4856. (require 'font-lock)
  4857. (defconst org-non-link-chars "]\t\n\r<>")
  4858. (defvar org-link-types-re nil
  4859. "Matches a link that has a url-like prefix like \"http:\"")
  4860. (defvar org-link-re-with-space nil
  4861. "Matches a link with spaces, optional angular brackets around it.")
  4862. (defvar org-link-re-with-space2 nil
  4863. "Matches a link with spaces, optional angular brackets around it.")
  4864. (defvar org-link-re-with-space3 nil
  4865. "Matches a link with spaces, only for internal part in bracket links.")
  4866. (defvar org-angle-link-re nil
  4867. "Matches link with angular brackets, spaces are allowed.")
  4868. (defvar org-plain-link-re nil
  4869. "Matches plain link, without spaces.")
  4870. (defvar org-bracket-link-regexp nil
  4871. "Matches a link in double brackets.")
  4872. (defvar org-bracket-link-analytic-regexp nil
  4873. "Regular expression used to analyze links.
  4874. Here is what the match groups contain after a match:
  4875. 1: http:
  4876. 2: http
  4877. 3: path
  4878. 4: [desc]
  4879. 5: desc")
  4880. (defvar org-bracket-link-analytic-regexp++ nil
  4881. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4882. (defvar org-any-link-re nil
  4883. "Regular expression matching any link.")
  4884. (defconst org-match-sexp-depth 3
  4885. "Number of stacked braces for sub/superscript matching.")
  4886. (defun org-create-multibrace-regexp (left right n)
  4887. "Create a regular expression which will match a balanced sexp.
  4888. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4889. as single character strings.
  4890. The regexp returned will match the entire expression including the
  4891. delimiters. It will also define a single group which contains the
  4892. match except for the outermost delimiters. The maximum depth of
  4893. stacked delimiters is N. Escaping delimiters is not possible."
  4894. (let* ((nothing (concat "[^" left right "]*?"))
  4895. (or "\\|")
  4896. (re nothing)
  4897. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4898. (while (> n 1)
  4899. (setq n (1- n)
  4900. re (concat re or next)
  4901. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4902. (concat left "\\(" re "\\)" right)))
  4903. (defconst org-match-substring-regexp
  4904. (concat
  4905. "\\(\\S-\\)\\([_^]\\)\\("
  4906. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4907. "\\|"
  4908. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4909. "\\|"
  4910. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4911. "The regular expression matching a sub- or superscript.")
  4912. (defconst org-match-substring-with-braces-regexp
  4913. (concat
  4914. "\\(\\S-\\)\\([_^]\\)"
  4915. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4916. "The regular expression matching a sub- or superscript, forcing braces.")
  4917. (defun org-make-link-regexps ()
  4918. "Update the link regular expressions.
  4919. This should be called after the variable `org-link-parameters' has changed."
  4920. (let ((types-re (regexp-opt (org-link-types) t)))
  4921. (setq org-link-types-re
  4922. (concat "\\`" types-re ":")
  4923. org-link-re-with-space
  4924. (concat "<?" types-re ":"
  4925. "\\([^" org-non-link-chars " ]"
  4926. "[^" org-non-link-chars "]*"
  4927. "[^" org-non-link-chars " ]\\)>?")
  4928. org-link-re-with-space2
  4929. (concat "<?" types-re ":"
  4930. "\\([^" org-non-link-chars " ]"
  4931. "[^\t\n\r]*"
  4932. "[^" org-non-link-chars " ]\\)>?")
  4933. org-link-re-with-space3
  4934. (concat "<?" types-re ":"
  4935. "\\([^" org-non-link-chars " ]"
  4936. "[^\t\n\r]*\\)")
  4937. org-angle-link-re
  4938. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  4939. types-re)
  4940. org-plain-link-re
  4941. (concat
  4942. "\\<" types-re ":"
  4943. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  4944. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  4945. org-bracket-link-regexp
  4946. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  4947. org-bracket-link-analytic-regexp
  4948. (concat
  4949. "\\[\\["
  4950. "\\(" types-re ":\\)?"
  4951. "\\([^]]+\\)"
  4952. "\\]"
  4953. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4954. "\\]")
  4955. org-bracket-link-analytic-regexp++
  4956. (concat
  4957. "\\[\\["
  4958. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  4959. "\\([^]]+\\)"
  4960. "\\]"
  4961. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4962. "\\]")
  4963. org-any-link-re
  4964. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  4965. org-angle-link-re "\\)\\|\\("
  4966. org-plain-link-re "\\)"))))
  4967. (org-make-link-regexps)
  4968. (defvar org-emph-face nil)
  4969. (defun org-do-emphasis-faces (limit)
  4970. "Run through the buffer and emphasize strings."
  4971. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4972. (car org-emphasis-regexp-components))))
  4973. (catch :exit
  4974. (while (re-search-forward quick-re limit t)
  4975. (let* ((marker (match-string 2))
  4976. (verbatim? (member marker '("~" "="))))
  4977. (when (save-excursion
  4978. (goto-char (match-beginning 0))
  4979. (and
  4980. ;; Do not match table hlines.
  4981. (not (and (equal marker "+")
  4982. (org-match-line
  4983. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4984. ;; Do not match headline stars. Do not consider
  4985. ;; stars of a headline as closing marker for bold
  4986. ;; markup either.
  4987. (not (and (equal marker "*")
  4988. (save-excursion
  4989. (forward-char)
  4990. (skip-chars-backward "*")
  4991. (looking-at-p org-outline-regexp-bol))))
  4992. ;; Match full emphasis markup regexp.
  4993. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4994. ;; Do not span over paragraph boundaries.
  4995. (not (string-match-p org-element-paragraph-separate
  4996. (match-string 2)))
  4997. ;; Do not span over cells in table rows.
  4998. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4999. (string-match-p "|" (match-string 4))))))
  5000. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  5001. (font-lock-prepend-text-property
  5002. (match-beginning 2) (match-end 2) 'face face)
  5003. (when verbatim?
  5004. (org-remove-flyspell-overlays-in
  5005. (match-beginning 0) (match-end 0)))
  5006. (add-text-properties (match-beginning 2) (match-end 2)
  5007. '(font-lock-multiline t org-emphasis t))
  5008. (when org-hide-emphasis-markers
  5009. (add-text-properties (match-end 4) (match-beginning 5)
  5010. '(invisible org-link))
  5011. (add-text-properties (match-beginning 3) (match-end 3)
  5012. '(invisible org-link)))
  5013. (throw :exit t))))))))
  5014. (defun org-emphasize (&optional char)
  5015. "Insert or change an emphasis, i.e. a font like bold or italic.
  5016. If there is an active region, change that region to a new emphasis.
  5017. If there is no region, just insert the marker characters and position
  5018. the cursor between them.
  5019. CHAR should be the marker character. If it is a space, it means to
  5020. remove the emphasis of the selected region.
  5021. If CHAR is not given (for example in an interactive call) it will be
  5022. prompted for."
  5023. (interactive)
  5024. (let ((erc org-emphasis-regexp-components)
  5025. (string "") beg end move s)
  5026. (if (org-region-active-p)
  5027. (setq beg (region-beginning)
  5028. end (region-end)
  5029. string (buffer-substring beg end))
  5030. (setq move t))
  5031. (unless char
  5032. (message "Emphasis marker or tag: [%s]"
  5033. (mapconcat #'car org-emphasis-alist ""))
  5034. (setq char (read-char-exclusive)))
  5035. (if (equal char ?\s)
  5036. (setq s ""
  5037. move nil)
  5038. (unless (assoc (char-to-string char) org-emphasis-alist)
  5039. (user-error "No such emphasis marker: \"%c\"" char))
  5040. (setq s (char-to-string char)))
  5041. (while (and (> (length string) 1)
  5042. (equal (substring string 0 1) (substring string -1))
  5043. (assoc (substring string 0 1) org-emphasis-alist))
  5044. (setq string (substring string 1 -1)))
  5045. (setq string (concat s string s))
  5046. (when beg (delete-region beg end))
  5047. (unless (or (bolp)
  5048. (string-match (concat "[" (nth 0 erc) "\n]")
  5049. (char-to-string (char-before (point)))))
  5050. (insert " "))
  5051. (unless (or (eobp)
  5052. (string-match (concat "[" (nth 1 erc) "\n]")
  5053. (char-to-string (char-after (point)))))
  5054. (insert " ") (backward-char 1))
  5055. (insert string)
  5056. (and move (backward-char 1))))
  5057. (defconst org-nonsticky-props
  5058. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5059. (defsubst org-rear-nonsticky-at (pos)
  5060. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5061. (defun org-activate-links (limit)
  5062. "Add link properties to links.
  5063. This includes angle, plain, and bracket links."
  5064. (catch :exit
  5065. (while (re-search-forward org-any-link-re limit t)
  5066. (let* ((start (match-beginning 0))
  5067. (end (match-end 0))
  5068. (style (cond ((eq ?< (char-after start)) 'angle)
  5069. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5070. (t 'plain))))
  5071. (when (and (memq style org-highlight-links)
  5072. ;; Do not confuse plain links with tags.
  5073. (not (and (eq style 'plain)
  5074. (let ((face (get-text-property
  5075. (max (1- start) (point-min)) 'face)))
  5076. (if (consp face) (memq 'org-tag face)
  5077. (eq 'org-tag face))))))
  5078. (let* ((link-object (save-excursion
  5079. (goto-char start)
  5080. (save-match-data (org-element-link-parser))))
  5081. (link (org-element-property :raw-link link-object))
  5082. (type (org-element-property :type link-object))
  5083. (path (org-element-property :path link-object))
  5084. (properties ;for link's visible part
  5085. (list
  5086. 'face (pcase (org-link-get-parameter type :face)
  5087. ((and (pred functionp) face) (funcall face path))
  5088. ((and (pred facep) face) face)
  5089. ((and (pred consp) face) face) ;anonymous
  5090. (_ 'org-link))
  5091. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5092. 'highlight)
  5093. 'keymap (or (org-link-get-parameter type :keymap)
  5094. org-mouse-map)
  5095. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5096. ((and (pred stringp) echo) echo)
  5097. ((and (pred functionp) echo) echo)
  5098. (_ (concat "LINK: " link)))
  5099. 'htmlize-link (pcase (org-link-get-parameter type
  5100. :htmlize-link)
  5101. ((and (pred functionp) f) (funcall f))
  5102. (_ `(:uri ,link)))
  5103. 'font-lock-multiline t)))
  5104. (org-remove-flyspell-overlays-in start end)
  5105. (org-rear-nonsticky-at end)
  5106. (if (not (eq 'bracket style))
  5107. (add-text-properties start end properties)
  5108. ;; Handle invisible parts in bracket links.
  5109. (remove-text-properties start end '(invisible nil))
  5110. (let ((hidden
  5111. (append `(invisible
  5112. ,(or (org-link-get-parameter type :display)
  5113. 'org-link))
  5114. properties))
  5115. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5116. (visible-end (or (match-end 4) (match-end 2))))
  5117. (add-text-properties start visible-start hidden)
  5118. (add-text-properties visible-start visible-end properties)
  5119. (add-text-properties visible-end end hidden)
  5120. (org-rear-nonsticky-at visible-start)
  5121. (org-rear-nonsticky-at visible-end)))
  5122. (let ((f (org-link-get-parameter type :activate-func)))
  5123. (when (functionp f)
  5124. (funcall f start end path (eq style 'bracket))))
  5125. (throw :exit t))))) ;signal success
  5126. nil))
  5127. (defun org-activate-code (limit)
  5128. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5129. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5130. (remove-text-properties (match-beginning 0) (match-end 0)
  5131. '(display t invisible t intangible t))
  5132. t))
  5133. (defcustom org-src-fontify-natively t
  5134. "When non-nil, fontify code in code blocks.
  5135. See also the `org-block' face."
  5136. :type 'boolean
  5137. :version "26.1"
  5138. :package-version '(Org . "8.3")
  5139. :group 'org-appearance
  5140. :group 'org-babel)
  5141. (defcustom org-allow-promoting-top-level-subtree nil
  5142. "When non-nil, allow promoting a top level subtree.
  5143. The leading star of the top level headline will be replaced
  5144. by a #."
  5145. :type 'boolean
  5146. :version "24.1"
  5147. :group 'org-appearance)
  5148. (defun org-fontify-meta-lines-and-blocks (limit)
  5149. (condition-case nil
  5150. (org-fontify-meta-lines-and-blocks-1 limit)
  5151. (error (message "Org mode fontification error in %S at %d"
  5152. (current-buffer)
  5153. (line-number-at-pos)))))
  5154. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5155. "Fontify #+ lines and blocks."
  5156. (let ((case-fold-search t))
  5157. (when (re-search-forward
  5158. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5159. limit t)
  5160. (let ((beg (match-beginning 0))
  5161. (block-start (match-end 0))
  5162. (block-end nil)
  5163. (lang (match-string 7))
  5164. (beg1 (line-beginning-position 2))
  5165. (dc1 (downcase (match-string 2)))
  5166. (dc3 (downcase (match-string 3)))
  5167. end end1 quoting block-type)
  5168. (cond
  5169. ((and (match-end 4) (equal dc3 "+begin"))
  5170. ;; Truly a block
  5171. (setq block-type (downcase (match-string 5))
  5172. quoting (member block-type org-protecting-blocks))
  5173. (when (re-search-forward
  5174. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5175. nil t) ;; on purpose, we look further than LIMIT
  5176. (setq end (min (point-max) (match-end 0))
  5177. end1 (min (point-max) (1- (match-beginning 0))))
  5178. (setq block-end (match-beginning 0))
  5179. (when quoting
  5180. (org-remove-flyspell-overlays-in beg1 end1)
  5181. (remove-text-properties beg end
  5182. '(display t invisible t intangible t)))
  5183. (add-text-properties
  5184. beg end '(font-lock-fontified t font-lock-multiline t))
  5185. (add-text-properties beg beg1 '(face org-meta-line))
  5186. (org-remove-flyspell-overlays-in beg beg1)
  5187. (add-text-properties ; For end_src
  5188. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5189. (org-remove-flyspell-overlays-in end1 end)
  5190. (cond
  5191. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5192. (org-src-font-lock-fontify-block lang block-start block-end)
  5193. (add-text-properties beg1 block-end '(src-block t)))
  5194. (quoting
  5195. (add-text-properties beg1 (min (point-max) (1+ end1))
  5196. (list 'face
  5197. (list :inherit
  5198. (let ((face-name
  5199. (intern (format "org-block-%s" lang))))
  5200. (append (and (facep face-name) (list face-name))
  5201. '(org-block))))))) ; end of source block
  5202. ((not org-fontify-quote-and-verse-blocks))
  5203. ((string= block-type "quote")
  5204. (add-face-text-property
  5205. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5206. ((string= block-type "verse")
  5207. (add-face-text-property
  5208. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5209. (add-text-properties beg beg1 '(face org-block-begin-line))
  5210. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5211. '(face org-block-end-line))
  5212. t))
  5213. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5214. (org-remove-flyspell-overlays-in
  5215. (match-beginning 0)
  5216. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5217. (add-text-properties
  5218. beg (match-end 3)
  5219. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5220. '(font-lock-fontified t invisible t)
  5221. '(font-lock-fontified t face org-document-info-keyword)))
  5222. (add-text-properties
  5223. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5224. (if (string-equal dc1 "+title:")
  5225. '(font-lock-fontified t face org-document-title)
  5226. '(font-lock-fontified t face org-document-info))))
  5227. ((string-prefix-p "+caption" dc1)
  5228. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5229. (remove-text-properties (match-beginning 0) (match-end 0)
  5230. '(display t invisible t intangible t))
  5231. ;; Handle short captions.
  5232. (save-excursion
  5233. (beginning-of-line)
  5234. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5235. (add-text-properties (line-beginning-position) (match-end 1)
  5236. '(font-lock-fontified t face org-meta-line))
  5237. (add-text-properties (match-end 0) (line-end-position)
  5238. '(font-lock-fontified t face org-block))
  5239. t)
  5240. ((member dc3 '(" " ""))
  5241. (org-remove-flyspell-overlays-in beg (match-end 0))
  5242. (add-text-properties
  5243. beg (match-end 0)
  5244. '(font-lock-fontified t face font-lock-comment-face)))
  5245. (t ;; just any other in-buffer setting, but not indented
  5246. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5247. (remove-text-properties (match-beginning 0) (match-end 0)
  5248. '(display t invisible t intangible t))
  5249. (add-text-properties beg (match-end 0)
  5250. '(font-lock-fontified t face org-meta-line))
  5251. t))))))
  5252. (defun org-fontify-drawers (limit)
  5253. "Fontify drawers."
  5254. (when (re-search-forward org-drawer-regexp limit t)
  5255. (add-text-properties
  5256. (match-beginning 0) (match-end 0)
  5257. '(font-lock-fontified t face org-special-keyword))
  5258. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5259. t))
  5260. (defun org-fontify-macros (limit)
  5261. "Fontify macros."
  5262. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  5263. (let ((begin (match-beginning 0))
  5264. (opening-end (match-beginning 1)))
  5265. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  5266. (match-string 1))
  5267. (let ((end (match-end 1))
  5268. (closing-start (match-beginning 1)))
  5269. (add-text-properties
  5270. begin end
  5271. '(font-lock-multiline t font-lock-fontified t face org-macro))
  5272. (org-remove-flyspell-overlays-in begin end)
  5273. (when org-hide-macro-markers
  5274. (add-text-properties begin opening-end '(invisible t))
  5275. (add-text-properties closing-start end '(invisible t)))
  5276. t)))))
  5277. (defun org-activate-footnote-links (limit)
  5278. "Add text properties for footnotes."
  5279. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5280. (when fn
  5281. (let* ((beg (nth 1 fn))
  5282. (end (nth 2 fn))
  5283. (label (car fn))
  5284. (referencep (/= (line-beginning-position) beg)))
  5285. (when (and referencep (nth 3 fn))
  5286. (save-excursion
  5287. (goto-char beg)
  5288. (search-forward (or label "fn:"))
  5289. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5290. (add-text-properties beg end
  5291. (list 'mouse-face 'highlight
  5292. 'keymap org-mouse-map
  5293. 'help-echo
  5294. (if referencep "Footnote reference"
  5295. "Footnote definition")
  5296. 'font-lock-fontified t
  5297. 'font-lock-multiline t
  5298. 'face 'org-footnote))))))
  5299. (defun org-activate-dates (limit)
  5300. "Add text properties for dates."
  5301. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5302. (not (equal (char-before (match-beginning 0)) 91)))
  5303. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5304. (add-text-properties (match-beginning 0) (match-end 0)
  5305. (list 'mouse-face 'highlight
  5306. 'keymap org-mouse-map))
  5307. (org-rear-nonsticky-at (match-end 0))
  5308. (when org-display-custom-times
  5309. ;; If it's a date range, activate custom time for second date.
  5310. (when (match-end 3)
  5311. (org-display-custom-time (match-beginning 3) (match-end 3)))
  5312. (org-display-custom-time (match-beginning 1) (match-end 1)))
  5313. t))
  5314. (defvar-local org-target-link-regexp nil
  5315. "Regular expression matching radio targets in plain text.")
  5316. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5317. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5318. border border border))
  5319. "Regular expression matching a link target.")
  5320. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5321. "Regular expression matching a radio target.")
  5322. (defconst org-any-target-regexp
  5323. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5324. "Regular expression matching any target.")
  5325. (defun org-activate-target-links (limit)
  5326. "Add text properties for target matches."
  5327. (when org-target-link-regexp
  5328. (let ((case-fold-search t))
  5329. (when (re-search-forward org-target-link-regexp limit t)
  5330. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5331. (add-text-properties (match-beginning 1) (match-end 1)
  5332. (list 'mouse-face 'highlight
  5333. 'keymap org-mouse-map
  5334. 'help-echo "Radio target link"
  5335. 'org-linked-text t))
  5336. (org-rear-nonsticky-at (match-end 1))
  5337. t))))
  5338. (defun org-update-radio-target-regexp ()
  5339. "Find all radio targets in this file and update the regular expression.
  5340. Also refresh fontification if needed."
  5341. (interactive)
  5342. (let ((old-regexp org-target-link-regexp)
  5343. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5344. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5345. (targets
  5346. (org-with-wide-buffer
  5347. (goto-char (point-min))
  5348. (let (rtn)
  5349. (while (re-search-forward org-radio-target-regexp nil t)
  5350. ;; Make sure point is really within the object.
  5351. (backward-char)
  5352. (let ((obj (org-element-context)))
  5353. (when (eq (org-element-type obj) 'radio-target)
  5354. (cl-pushnew (org-element-property :value obj) rtn
  5355. :test #'equal))))
  5356. rtn))))
  5357. (setq org-target-link-regexp
  5358. (and targets
  5359. (concat before-re
  5360. (mapconcat
  5361. (lambda (x)
  5362. (replace-regexp-in-string
  5363. " +" "\\s-+" (regexp-quote x) t t))
  5364. targets
  5365. "\\|")
  5366. after-re)))
  5367. (unless (equal old-regexp org-target-link-regexp)
  5368. ;; Clean-up cache.
  5369. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5370. ((not org-target-link-regexp) old-regexp)
  5371. (t
  5372. (concat before-re
  5373. (mapconcat
  5374. (lambda (re)
  5375. (substring re (length before-re)
  5376. (- (length after-re))))
  5377. (list old-regexp org-target-link-regexp)
  5378. "\\|")
  5379. after-re)))))
  5380. (org-with-wide-buffer
  5381. (goto-char (point-min))
  5382. (while (re-search-forward regexp nil t)
  5383. (org-element-cache-refresh (match-beginning 1)))))
  5384. ;; Re fontify buffer.
  5385. (when (memq 'radio org-highlight-links)
  5386. (org-restart-font-lock)))))
  5387. (defvar org-latex-and-related-regexp nil
  5388. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5389. (defun org-compute-latex-and-related-regexp ()
  5390. "Compute regular expression for LaTeX, entities and sub/superscript.
  5391. Result depends on variable `org-highlight-latex-and-related'."
  5392. (setq-local
  5393. org-latex-and-related-regexp
  5394. (let* ((re-sub
  5395. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5396. ((eq org-use-sub-superscripts '{})
  5397. (list org-match-substring-with-braces-regexp))
  5398. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5399. (re-latex
  5400. (when (memq 'latex org-highlight-latex-and-related)
  5401. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5402. (delq nil
  5403. (mapcar (lambda (x)
  5404. (and (member (car x) matchers) (nth 1 x)))
  5405. org-latex-regexps)))))
  5406. (re-entities
  5407. (when (memq 'entities org-highlight-latex-and-related)
  5408. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5409. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5410. (defun org-do-latex-and-related (limit)
  5411. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5412. LIMIT bounds the search for syntax to highlight. Stop at first
  5413. highlighted object, if any. Return t if some highlighting was
  5414. done, nil otherwise."
  5415. (when (org-string-nw-p org-latex-and-related-regexp)
  5416. (catch 'found
  5417. (while (re-search-forward org-latex-and-related-regexp limit t)
  5418. (unless
  5419. (cl-some
  5420. (lambda (f)
  5421. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5422. (save-excursion
  5423. (goto-char (1+ (match-beginning 0)))
  5424. (face-at-point nil t)))
  5425. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5426. '(?_ ?^))
  5427. 1
  5428. 0)))
  5429. (font-lock-prepend-text-property
  5430. (+ offset (match-beginning 0)) (match-end 0)
  5431. 'face 'org-latex-and-related)
  5432. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5433. '(font-lock-multiline t)))
  5434. (throw 'found t)))
  5435. nil)))
  5436. (defun org-restart-font-lock ()
  5437. "Restart `font-lock-mode', to force refontification."
  5438. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5439. (font-lock-mode -1)
  5440. (font-lock-mode 1)))
  5441. (defun org-activate-tags (limit)
  5442. (when (re-search-forward org-tag-line-re limit t)
  5443. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5444. (add-text-properties (match-beginning 1) (match-end 1)
  5445. (list 'mouse-face 'highlight
  5446. 'keymap org-mouse-map))
  5447. (org-rear-nonsticky-at (match-end 1))
  5448. t))
  5449. (defun org-outline-level ()
  5450. "Compute the outline level of the heading at point.
  5451. If this is called at a normal headline, the level is the number
  5452. of stars. Use `org-reduced-level' to remove the effect of
  5453. `org-odd-levels'. Unlike to `org-current-level', this function
  5454. takes into consideration inlinetasks."
  5455. (org-with-wide-buffer
  5456. (end-of-line)
  5457. (if (re-search-backward org-outline-regexp-bol nil t)
  5458. (1- (- (match-end 0) (match-beginning 0)))
  5459. 0)))
  5460. (defvar org-font-lock-keywords nil)
  5461. (defsubst org-re-property (property &optional literal allow-null value)
  5462. "Return a regexp matching a PROPERTY line.
  5463. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5464. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5465. non-nil, match properties even without a value.
  5466. Match group 3 is set to the value when it exists. If there is no
  5467. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5468. With optional argument VALUE, match only property lines with
  5469. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5470. unless LITERAL is non-nil."
  5471. (concat
  5472. "^\\(?4:[ \t]*\\)"
  5473. (format "\\(?1::\\(?2:%s\\):\\)"
  5474. (if literal property (regexp-quote property)))
  5475. (cond (value
  5476. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5477. (if literal value (regexp-quote value))))
  5478. (allow-null
  5479. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5480. (t
  5481. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5482. (defconst org-property-re
  5483. (org-re-property "\\S-+" 'literal t)
  5484. "Regular expression matching a property line.
  5485. There are four matching groups:
  5486. 1: :PROPKEY: including the leading and trailing colon,
  5487. 2: PROPKEY without the leading and trailing colon,
  5488. 3: PROPVAL without leading or trailing spaces,
  5489. 4: the indentation of the current line,
  5490. 5: trailing whitespace.")
  5491. (defvar org-font-lock-hook nil
  5492. "Functions to be called for special font lock stuff.")
  5493. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5494. (defvar org-font-lock-set-keywords-hook nil
  5495. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5496. This is called after `org-font-lock-extra-keywords' is defined, but before
  5497. it is installed to be used by font lock. This can be useful if something
  5498. needs to be inserted at a specific position in the font-lock sequence.")
  5499. (defun org-font-lock-hook (limit)
  5500. "Run `org-font-lock-hook' within LIMIT."
  5501. (run-hook-with-args 'org-font-lock-hook limit))
  5502. (defun org-set-font-lock-defaults ()
  5503. "Set font lock defaults for the current buffer."
  5504. (let* ((em org-fontify-emphasized-text)
  5505. (lk org-highlight-links)
  5506. (org-font-lock-extra-keywords
  5507. (list
  5508. ;; Call the hook
  5509. '(org-font-lock-hook)
  5510. ;; Headlines
  5511. `(,(if org-fontify-whole-heading-line
  5512. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5513. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5514. (1 (org-get-level-face 1))
  5515. (2 (org-get-level-face 2))
  5516. (3 (org-get-level-face 3)))
  5517. ;; Table lines
  5518. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5519. (1 'org-table t))
  5520. ;; Table internals
  5521. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5522. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5523. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5524. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5525. ;; Drawers
  5526. '(org-fontify-drawers)
  5527. ;; Properties
  5528. (list org-property-re
  5529. '(1 'org-special-keyword t)
  5530. '(3 'org-property-value t))
  5531. ;; Link related fontification.
  5532. '(org-activate-links)
  5533. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5534. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5535. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5536. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5537. ;; Targets.
  5538. (list org-any-target-regexp '(0 'org-target t))
  5539. ;; Diary sexps.
  5540. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5541. ;; Macro
  5542. '(org-fontify-macros)
  5543. ;; TODO keyword
  5544. (list (format org-heading-keyword-regexp-format
  5545. org-todo-regexp)
  5546. '(2 (org-get-todo-face 2) t))
  5547. ;; DONE
  5548. (if org-fontify-done-headline
  5549. (list (format org-heading-keyword-regexp-format
  5550. (concat
  5551. "\\(?:"
  5552. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5553. "\\)"))
  5554. '(2 'org-headline-done t))
  5555. nil)
  5556. ;; Priorities
  5557. '(org-font-lock-add-priority-faces)
  5558. ;; Tags
  5559. '(org-font-lock-add-tag-faces)
  5560. ;; Tags groups
  5561. (when (and org-group-tags org-tag-groups-alist)
  5562. (list (concat org-outline-regexp-bol ".+\\(:"
  5563. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5564. ":\\).*$")
  5565. '(1 'org-tag-group prepend)))
  5566. ;; Special keywords
  5567. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5568. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5569. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5570. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5571. ;; Emphasis
  5572. (when em '(org-do-emphasis-faces))
  5573. ;; Checkboxes
  5574. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5575. 1 'org-checkbox prepend)
  5576. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5577. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5578. (0 (org-get-checkbox-statistics-face) t)))
  5579. ;; Description list items
  5580. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5581. 1 'org-list-dt prepend)
  5582. ;; ARCHIVEd headings
  5583. (list (concat
  5584. org-outline-regexp-bol
  5585. "\\(.*:" org-archive-tag ":.*\\)")
  5586. '(1 'org-archived prepend))
  5587. ;; Specials
  5588. '(org-do-latex-and-related)
  5589. '(org-fontify-entities)
  5590. '(org-raise-scripts)
  5591. ;; Code
  5592. '(org-activate-code (1 'org-code t))
  5593. ;; COMMENT
  5594. (list (format
  5595. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5596. org-todo-regexp
  5597. org-comment-string)
  5598. '(9 'org-special-keyword t))
  5599. ;; Blocks and meta lines
  5600. '(org-fontify-meta-lines-and-blocks))))
  5601. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5602. (run-hooks 'org-font-lock-set-keywords-hook)
  5603. ;; Now set the full font-lock-keywords
  5604. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5605. (setq-local font-lock-defaults
  5606. '(org-font-lock-keywords t nil nil backward-paragraph))
  5607. (kill-local-variable 'font-lock-keywords)
  5608. nil))
  5609. (defun org-toggle-pretty-entities ()
  5610. "Toggle the composition display of entities as UTF8 characters."
  5611. (interactive)
  5612. (setq-local org-pretty-entities (not org-pretty-entities))
  5613. (org-restart-font-lock)
  5614. (if org-pretty-entities
  5615. (message "Entities are now displayed as UTF8 characters")
  5616. (save-restriction
  5617. (widen)
  5618. (decompose-region (point-min) (point-max))
  5619. (message "Entities are now displayed as plain text"))))
  5620. (defvar-local org-custom-properties-overlays nil
  5621. "List of overlays used for custom properties.")
  5622. (defun org-toggle-custom-properties-visibility ()
  5623. "Display or hide properties in `org-custom-properties'."
  5624. (interactive)
  5625. (if org-custom-properties-overlays
  5626. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5627. (setq org-custom-properties-overlays nil))
  5628. (when org-custom-properties
  5629. (org-with-wide-buffer
  5630. (goto-char (point-min))
  5631. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5632. (while (re-search-forward regexp nil t)
  5633. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5634. (when (and end (< (point) end))
  5635. ;; Hide first custom property in current drawer.
  5636. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5637. (overlay-put o 'invisible t)
  5638. (overlay-put o 'org-custom-property t)
  5639. (push o org-custom-properties-overlays))
  5640. ;; Hide additional custom properties in the same drawer.
  5641. (while (re-search-forward regexp end t)
  5642. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5643. (overlay-put o 'invisible t)
  5644. (overlay-put o 'org-custom-property t)
  5645. (push o org-custom-properties-overlays)))))
  5646. ;; Each entry is limited to a single property drawer.
  5647. (outline-next-heading)))))))
  5648. (defun org-fontify-entities (limit)
  5649. "Find an entity to fontify."
  5650. (let (ee)
  5651. (when org-pretty-entities
  5652. (catch 'match
  5653. ;; "\_ "-family is left out on purpose. Only the first one,
  5654. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5655. ;; confusing when adding a second white space character.
  5656. (while (re-search-forward
  5657. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5658. limit t)
  5659. (when (and (not (org-at-comment-p))
  5660. (setq ee (org-entity-get (match-string 1)))
  5661. (= (length (nth 6 ee)) 1))
  5662. (let* ((end (if (equal (match-string 2) "{}")
  5663. (match-end 2)
  5664. (match-end 1))))
  5665. (add-text-properties
  5666. (match-beginning 0) end
  5667. (list 'font-lock-fontified t))
  5668. (compose-region (match-beginning 0) end
  5669. (nth 6 ee) nil)
  5670. (backward-char 1)
  5671. (throw 'match t))))
  5672. nil))))
  5673. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5674. "Fontify string S like in Org mode."
  5675. (with-temp-buffer
  5676. (insert s)
  5677. (let ((org-odd-levels-only odd-levels))
  5678. (org-mode)
  5679. (org-font-lock-ensure)
  5680. (buffer-string))))
  5681. (defvar org-m nil)
  5682. (defvar org-l nil)
  5683. (defvar org-f nil)
  5684. (defun org-get-level-face (n)
  5685. "Get the right face for match N in font-lock matching of headlines."
  5686. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5687. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5688. (if org-cycle-level-faces
  5689. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5690. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5691. (cond
  5692. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5693. ((eq n 2) org-f)
  5694. (t (unless org-level-color-stars-only org-f))))
  5695. (defun org-face-from-face-or-color (context inherit face-or-color)
  5696. "Create a face list that inherits INHERIT, but sets the foreground color.
  5697. When FACE-OR-COLOR is not a string, just return it."
  5698. (if (stringp face-or-color)
  5699. (list :inherit inherit
  5700. (cdr (assoc context org-faces-easy-properties))
  5701. face-or-color)
  5702. face-or-color))
  5703. (defun org-get-todo-face (kwd)
  5704. "Get the right face for a TODO keyword KWD.
  5705. If KWD is a number, get the corresponding match group."
  5706. (when (numberp kwd) (setq kwd (match-string kwd)))
  5707. (or (org-face-from-face-or-color
  5708. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5709. (and (member kwd org-done-keywords) 'org-done)
  5710. 'org-todo))
  5711. (defun org-get-priority-face (priority)
  5712. "Get the right face for PRIORITY.
  5713. PRIORITY is a character."
  5714. (or (org-face-from-face-or-color
  5715. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5716. 'org-priority))
  5717. (defun org-get-tag-face (tag)
  5718. "Get the right face for TAG.
  5719. If TAG is a number, get the corresponding match group."
  5720. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5721. (or (org-face-from-face-or-color
  5722. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5723. 'org-tag)))
  5724. (defun org-font-lock-add-priority-faces (limit)
  5725. "Add the special priority faces."
  5726. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5727. (add-text-properties
  5728. (match-beginning 1) (match-end 1)
  5729. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5730. 'font-lock-fontified t))))
  5731. (defun org-font-lock-add-tag-faces (limit)
  5732. "Add the special tag faces."
  5733. (when (and org-tag-faces org-tags-special-faces-re)
  5734. (while (re-search-forward org-tags-special-faces-re limit t)
  5735. (add-text-properties (match-beginning 1) (match-end 1)
  5736. (list 'face (org-get-tag-face 1)
  5737. 'font-lock-fontified t))
  5738. (backward-char 1))))
  5739. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5740. "Remove fontification and activation overlays from links."
  5741. (font-lock-default-unfontify-region beg end)
  5742. (let* ((buffer-undo-list t)
  5743. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5744. (inhibit-modification-hooks t)
  5745. deactivate-mark buffer-file-name buffer-file-truename)
  5746. (decompose-region beg end)
  5747. (remove-text-properties beg end
  5748. '(mouse-face t keymap t org-linked-text t
  5749. invisible t intangible t
  5750. org-emphasis t))
  5751. (org-remove-font-lock-display-properties beg end)))
  5752. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5753. ((raise 0.3) (height 0.7))
  5754. ((raise -0.5))
  5755. ((raise 0.5)))
  5756. "Display properties for showing superscripts and subscripts.")
  5757. (defun org-remove-font-lock-display-properties (beg end)
  5758. "Remove specific display properties that have been added by font lock.
  5759. The will remove the raise properties that are used to show superscripts
  5760. and subscripts."
  5761. (let (next prop)
  5762. (while (< beg end)
  5763. (setq next (next-single-property-change beg 'display nil end)
  5764. prop (get-text-property beg 'display))
  5765. (when (member prop org-script-display)
  5766. (put-text-property beg next 'display nil))
  5767. (setq beg next))))
  5768. (defun org-raise-scripts (limit)
  5769. "Add raise properties to sub/superscripts."
  5770. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5771. (re-search-forward
  5772. (if (eq org-use-sub-superscripts t)
  5773. org-match-substring-regexp
  5774. org-match-substring-with-braces-regexp)
  5775. limit t))
  5776. (let* ((pos (point)) table-p comment-p
  5777. (mpos (match-beginning 3))
  5778. (emph-p (get-text-property mpos 'org-emphasis))
  5779. (link-p (get-text-property mpos 'mouse-face))
  5780. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5781. (goto-char (point-at-bol))
  5782. (setq table-p (looking-at-p org-table-dataline-regexp)
  5783. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5784. (goto-char pos)
  5785. ;; Handle a_b^c
  5786. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5787. (unless (or comment-p emph-p link-p keyw-p)
  5788. (put-text-property (match-beginning 3) (match-end 0)
  5789. 'display
  5790. (if (equal (char-after (match-beginning 2)) ?^)
  5791. (nth (if table-p 3 1) org-script-display)
  5792. (nth (if table-p 2 0) org-script-display)))
  5793. (add-text-properties (match-beginning 2) (match-end 2)
  5794. (list 'invisible t))
  5795. (when (and (eq (char-after (match-beginning 3)) ?{)
  5796. (eq (char-before (match-end 3)) ?}))
  5797. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5798. (list 'invisible t))
  5799. (add-text-properties (1- (match-end 3)) (match-end 3)
  5800. (list 'invisible t))))
  5801. t)))
  5802. (defun org-remove-empty-overlays-at (pos)
  5803. "Remove outline overlays that do not contain non-white stuff."
  5804. (dolist (o (overlays-at pos))
  5805. (and (eq 'outline (overlay-get o 'invisible))
  5806. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  5807. (overlay-end o))))
  5808. (delete-overlay o))))
  5809. (defun org-show-empty-lines-in-parent ()
  5810. "Move to the parent and re-show empty lines before visible headlines."
  5811. (save-excursion
  5812. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5813. (org-cycle-show-empty-lines context))))
  5814. (defun org-files-list ()
  5815. "Return `org-agenda-files' list, plus all open Org files.
  5816. This is useful for operations that need to scan all of a user's
  5817. open and agenda-wise Org files."
  5818. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5819. (dolist (buf (buffer-list))
  5820. (with-current-buffer buf
  5821. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5822. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5823. :test #'equal))))
  5824. files))
  5825. (defsubst org-entry-beginning-position ()
  5826. "Return the beginning position of the current entry."
  5827. (save-excursion (org-back-to-heading t) (point)))
  5828. (defsubst org-entry-end-position ()
  5829. "Return the end position of the current entry."
  5830. (save-excursion (outline-next-heading) (point)))
  5831. (defun org-subtree-end-visible-p ()
  5832. "Is the end of the current subtree visible?"
  5833. (pos-visible-in-window-p
  5834. (save-excursion (org-end-of-subtree t) (point))))
  5835. (defun org-first-headline-recenter ()
  5836. "Move cursor to the first headline and recenter the headline."
  5837. (let ((window (get-buffer-window)))
  5838. (when window
  5839. (goto-char (point-min))
  5840. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5841. (set-window-start window (line-beginning-position))))))
  5842. ;;; Visibility (headlines, blocks, drawers)
  5843. ;;;; Headlines visibility
  5844. (defun org-show-entry ()
  5845. "Show the body directly following this heading.
  5846. Show the heading too, if it is currently invisible."
  5847. (interactive)
  5848. (save-excursion
  5849. (ignore-errors
  5850. (org-back-to-heading t)
  5851. (org-flag-region
  5852. (line-end-position 0)
  5853. (save-excursion
  5854. (if (re-search-forward
  5855. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5856. (match-beginning 1)
  5857. (point-max)))
  5858. nil
  5859. 'outline))))
  5860. (defun org-show-children (&optional level)
  5861. "Show all direct subheadings of this heading.
  5862. Prefix arg LEVEL is how many levels below the current level
  5863. should be shown. Default is enough to cause the following
  5864. heading to appear."
  5865. (interactive "p")
  5866. (save-excursion
  5867. (org-back-to-heading t)
  5868. (let* ((current-level (funcall outline-level))
  5869. (max-level (org-get-valid-level
  5870. current-level
  5871. (if level (prefix-numeric-value level) 1)))
  5872. (end (save-excursion (org-end-of-subtree t t)))
  5873. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5874. (past-first-child nil)
  5875. ;; Make sure to skip inlinetasks.
  5876. (re (format regexp-fmt
  5877. current-level
  5878. (cond
  5879. ((not (featurep 'org-inlinetask)) "")
  5880. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5881. 3))
  5882. (t (1- org-inlinetask-min-level))))))
  5883. ;; Display parent heading.
  5884. (org-flag-heading nil)
  5885. (forward-line)
  5886. ;; Display children. First child may be deeper than expected
  5887. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5888. ;; MAX-LEVEL accordingly.
  5889. (while (re-search-forward re end t)
  5890. (unless past-first-child
  5891. (setq re (format regexp-fmt
  5892. current-level
  5893. (max (funcall outline-level) max-level)))
  5894. (setq past-first-child t))
  5895. (org-flag-heading nil)))))
  5896. (defun org-show-subtree ()
  5897. "Show everything after this heading at deeper levels."
  5898. (interactive)
  5899. (org-flag-region
  5900. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5901. ;;;; Blocks visibility
  5902. (defun org-hide-block-toggle-maybe ()
  5903. "Toggle visibility of block at point.
  5904. Unlike to `org-hide-block-toggle', this function does not throw
  5905. an error. Return a non-nil value when toggling is successful."
  5906. (interactive)
  5907. (ignore-errors (org-hide-block-toggle)))
  5908. (defun org-hide-block-toggle (&optional force)
  5909. "Toggle the visibility of the current block.
  5910. When optional argument FORCE is `off', make block visible. If it
  5911. is non-nil, hide it unconditionally. Throw an error when not at
  5912. a block. Return a non-nil value when toggling is successful."
  5913. (interactive)
  5914. (let ((element (org-element-at-point)))
  5915. (unless (memq (org-element-type element)
  5916. '(center-block comment-block dynamic-block example-block
  5917. export-block quote-block special-block
  5918. src-block verse-block))
  5919. (user-error "Not at a block"))
  5920. (let* ((post (org-element-property :post-affiliated element))
  5921. (start (save-excursion
  5922. (goto-char post)
  5923. (line-end-position)))
  5924. (end (save-excursion
  5925. (goto-char (org-element-property :end element))
  5926. (skip-chars-backward " \t\n")
  5927. (line-end-position))))
  5928. ;; Do nothing when not before or at the block opening line or at
  5929. ;; the block closing line.
  5930. (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
  5931. (cond ((eq force 'off)
  5932. (org-flag-region start end nil 'org-hide-block))
  5933. (force
  5934. (org-flag-region start end t 'org-hide-block))
  5935. ((eq (get-char-property start 'invisible) 'org-hide-block)
  5936. (org-flag-region start end nil 'org-hide-block))
  5937. (t
  5938. (org-flag-region start end t 'org-hide-block)))
  5939. ;; When the block is hidden away, make sure point is left in
  5940. ;; a visible part of the buffer.
  5941. (when (invisible-p (max (1- (point)) (point-min)))
  5942. (goto-char post))
  5943. ;; Signal success.
  5944. t))))
  5945. (defun org-hide-block-toggle-all ()
  5946. "Toggle the visibility of all blocks in the current buffer."
  5947. (org-block-map 'org-hide-block-toggle))
  5948. (defun org-hide-block-all ()
  5949. "Fold all blocks in the current buffer."
  5950. (interactive)
  5951. (org-show-all '(blocks))
  5952. (org-block-map 'org-hide-block-toggle-maybe))
  5953. ;;;; Drawers visibility
  5954. (defun org-cycle-hide-drawers (state &optional exceptions)
  5955. "Re-hide all drawers after a visibility state change.
  5956. STATE should be one of the symbols listed in the docstring of
  5957. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  5958. a list of strings specifying which drawers should not be hidden."
  5959. (when (and (derived-mode-p 'org-mode)
  5960. (not (memq state '(overview folded contents))))
  5961. (save-excursion
  5962. (let* ((globalp (eq state 'all))
  5963. (beg (if globalp (point-min) (point)))
  5964. (end (if globalp (point-max)
  5965. (if (eq state 'children)
  5966. (save-excursion (outline-next-heading) (point))
  5967. (org-end-of-subtree t)))))
  5968. (goto-char beg)
  5969. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  5970. (unless (member-ignore-case (match-string 1) exceptions)
  5971. (let ((drawer (org-element-at-point)))
  5972. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5973. (org-flag-drawer t drawer)
  5974. ;; Make sure to skip drawer entirely or we might flag
  5975. ;; it another time when matching its ending line with
  5976. ;; `org-drawer-regexp'.
  5977. (goto-char (org-element-property :end drawer))))))))))
  5978. (defun org-flag-drawer (flag &optional element)
  5979. "When FLAG is non-nil, hide the drawer we are at.
  5980. Otherwise make it visible. When optional argument ELEMENT is
  5981. a parsed drawer, as returned by `org-element-at-point', hide or
  5982. show that drawer instead."
  5983. (let ((drawer (or element
  5984. (and (save-excursion
  5985. (beginning-of-line)
  5986. (looking-at-p org-drawer-regexp))
  5987. (org-element-at-point)))))
  5988. (when (memq (org-element-type drawer) '(drawer property-drawer))
  5989. (let ((post (org-element-property :post-affiliated drawer)))
  5990. (org-flag-region
  5991. (save-excursion (goto-char post) (line-end-position))
  5992. (save-excursion (goto-char (org-element-property :end drawer))
  5993. (skip-chars-backward " \t\n")
  5994. (line-end-position))
  5995. flag 'org-hide-drawer)
  5996. ;; When the drawer is hidden away, make sure point lies in
  5997. ;; a visible part of the buffer.
  5998. (when (invisible-p (max (1- (point)) (point-min)))
  5999. (goto-char post))))))
  6000. ;;;; Visibility cycling
  6001. (defvar-local org-cycle-global-status nil)
  6002. (put 'org-cycle-global-status 'org-state t)
  6003. (defvar-local org-cycle-subtree-status nil)
  6004. (put 'org-cycle-subtree-status 'org-state t)
  6005. (defun org-show-all (&optional types)
  6006. "Show all contents in the visible part of the buffer.
  6007. By default, the function expands headings, blocks and drawers.
  6008. When optional argument TYPE is a list of symbols among `blocks',
  6009. `drawers' and `headings', to only expand one specific type."
  6010. (dolist (type (or types '(blocks drawers headings)))
  6011. (org-flag-region (point-min) (point-max) nil
  6012. (pcase type
  6013. (`blocks 'org-hide-block)
  6014. (`drawers 'org-hide-drawer)
  6015. (`headings 'outline)
  6016. (_ (error "Invalid type: %S" type))))))
  6017. ;;;###autoload
  6018. (defun org-cycle (&optional arg)
  6019. "TAB-action and visibility cycling for Org mode.
  6020. This is the command invoked in Org mode by the `TAB' key. Its main
  6021. purpose is outline visibility cycling, but it also invokes other actions
  6022. in special contexts.
  6023. When this function is called with a `\\[universal-argument]' prefix, rotate \
  6024. the entire
  6025. buffer through 3 states (global cycling)
  6026. 1. OVERVIEW: Show only top-level headlines.
  6027. 2. CONTENTS: Show all headlines of all levels, but no body text.
  6028. 3. SHOW ALL: Show everything.
  6029. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  6030. switch to the startup visibility,
  6031. determined by the variable `org-startup-folded', and by any VISIBILITY
  6032. properties in the buffer.
  6033. With a `\\[universal-argument] \\[universal-argument] \
  6034. \\[universal-argument]' prefix argument, show the entire buffer, including
  6035. any drawers.
  6036. When inside a table, re-align the table and move to the next field.
  6037. When point is at the beginning of a headline, rotate the subtree started
  6038. by this line through 3 different states (local cycling)
  6039. 1. FOLDED: Only the main headline is shown.
  6040. 2. CHILDREN: The main headline and the direct children are shown.
  6041. From this state, you can move to one of the children
  6042. and zoom in further.
  6043. 3. SUBTREE: Show the entire subtree, including body text.
  6044. If there is no subtree, switch directly from CHILDREN to FOLDED.
  6045. When point is at the beginning of an empty headline and the variable
  6046. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  6047. of the headline by demoting and promoting it to likely levels. This
  6048. speeds up creation document structure by pressing `TAB' once or several
  6049. times right after creating a new headline.
  6050. When there is a numeric prefix, go up to a heading with level ARG, do
  6051. a `show-subtree' and return to the previous cursor position. If ARG
  6052. is negative, go up that many levels.
  6053. When point is not at the beginning of a headline, execute the global
  6054. binding for `TAB', which is re-indenting the line. See the option
  6055. `org-cycle-emulate-tab' for details.
  6056. As a special case, if point is at the beginning of the buffer and there is
  6057. no headline in line 1, this function will act as if called with prefix arg
  6058. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  6059. prefix arg, but only
  6060. if the variable `org-cycle-global-at-bob' is t."
  6061. (interactive "P")
  6062. (org-load-modules-maybe)
  6063. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  6064. (and org-cycle-level-after-item/entry-creation
  6065. (or (org-cycle-level)
  6066. (org-cycle-item-indentation))))
  6067. (let* ((limit-level
  6068. (or org-cycle-max-level
  6069. (and (boundp 'org-inlinetask-min-level)
  6070. org-inlinetask-min-level
  6071. (1- org-inlinetask-min-level))))
  6072. (nstars (and limit-level
  6073. (if org-odd-levels-only
  6074. (and limit-level (1- (* limit-level 2)))
  6075. limit-level)))
  6076. (org-outline-regexp
  6077. (if (not (derived-mode-p 'org-mode))
  6078. outline-regexp
  6079. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  6080. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  6081. (not (looking-at org-outline-regexp))))
  6082. (org-cycle-hook
  6083. (if bob-special
  6084. (delq 'org-optimize-window-after-visibility-change
  6085. (copy-sequence org-cycle-hook))
  6086. org-cycle-hook))
  6087. (pos (point)))
  6088. (cond
  6089. ((equal arg '(16))
  6090. (setq last-command 'dummy)
  6091. (org-set-startup-visibility)
  6092. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  6093. ((equal arg '(64))
  6094. (org-show-all)
  6095. (org-unlogged-message "Entire buffer visible, including drawers"))
  6096. ((equal arg '(4)) (org-cycle-internal-global))
  6097. ;; Try hiding block at point.
  6098. ((org-hide-block-toggle-maybe))
  6099. ;; Try cdlatex TAB completion
  6100. ((org-try-cdlatex-tab))
  6101. ;; Table: enter it or move to the next field.
  6102. ((org-at-table-p 'any)
  6103. (if (org-at-table.el-p)
  6104. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6105. Use `\\[org-edit-special]' to edit table.el tables"))
  6106. (if arg (org-table-edit-field t)
  6107. (org-table-justify-field-maybe)
  6108. (call-interactively 'org-table-next-field))))
  6109. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  6110. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6111. (bob-special (org-cycle-internal-global))
  6112. ;; Drawers: delegate to `org-flag-drawer'.
  6113. ((save-excursion
  6114. (beginning-of-line 1)
  6115. (looking-at org-drawer-regexp))
  6116. (org-flag-drawer ; toggle block visibility
  6117. (not (get-char-property (match-end 0) 'invisible))))
  6118. ;; Show-subtree, ARG levels up from here.
  6119. ((integerp arg)
  6120. (save-excursion
  6121. (org-back-to-heading)
  6122. (outline-up-heading (if (< arg 0) (- arg)
  6123. (- (funcall outline-level) arg)))
  6124. (org-show-subtree)))
  6125. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6126. ((and (featurep 'org-inlinetask)
  6127. (org-inlinetask-at-task-p)
  6128. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6129. (org-inlinetask-toggle-visibility))
  6130. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6131. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6132. (save-excursion (move-beginning-of-line 1)
  6133. (looking-at org-outline-regexp)))
  6134. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6135. (org-cycle-internal-local))
  6136. ;; From there: TAB emulation and template completion.
  6137. (buffer-read-only (org-back-to-heading))
  6138. ((run-hook-with-args-until-success
  6139. 'org-tab-after-check-for-cycling-hook))
  6140. ((run-hook-with-args-until-success
  6141. 'org-tab-before-tab-emulation-hook))
  6142. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6143. (or (not (bolp))
  6144. (not (looking-at org-outline-regexp))))
  6145. (call-interactively (global-key-binding "\t")))
  6146. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6147. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6148. (or (and (eq org-cycle-emulate-tab 'white)
  6149. (= (match-end 0) (point-at-eol)))
  6150. (and (eq org-cycle-emulate-tab 'whitestart)
  6151. (>= (match-end 0) pos))))
  6152. t
  6153. (eq org-cycle-emulate-tab t))
  6154. (call-interactively (global-key-binding "\t")))
  6155. (t (save-excursion
  6156. (org-back-to-heading)
  6157. (org-cycle)))))))
  6158. (defun org-cycle-internal-global ()
  6159. "Do the global cycling action."
  6160. ;; Hack to avoid display of messages for .org attachments in Gnus
  6161. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6162. (cond
  6163. ((and (eq last-command this-command)
  6164. (eq org-cycle-global-status 'overview))
  6165. ;; We just created the overview - now do table of contents
  6166. ;; This can be slow in very large buffers, so indicate action
  6167. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6168. (unless ga (org-unlogged-message "CONTENTS..."))
  6169. (org-content)
  6170. (unless ga (org-unlogged-message "CONTENTS...done"))
  6171. (setq org-cycle-global-status 'contents)
  6172. (run-hook-with-args 'org-cycle-hook 'contents))
  6173. ((and (eq last-command this-command)
  6174. (eq org-cycle-global-status 'contents))
  6175. ;; We just showed the table of contents - now show everything
  6176. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6177. (org-show-all '(headings blocks))
  6178. (unless ga (org-unlogged-message "SHOW ALL"))
  6179. (setq org-cycle-global-status 'all)
  6180. (run-hook-with-args 'org-cycle-hook 'all))
  6181. (t
  6182. ;; Default action: go to overview
  6183. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6184. (org-overview)
  6185. (unless ga (org-unlogged-message "OVERVIEW"))
  6186. (setq org-cycle-global-status 'overview)
  6187. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6188. (defvar org-called-with-limited-levels nil
  6189. "Non-nil when `org-with-limited-levels' is currently active.")
  6190. (defun org-cycle-internal-local ()
  6191. "Do the local cycling action."
  6192. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6193. ;; First, determine end of headline (EOH), end of subtree or item
  6194. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6195. (save-excursion
  6196. (if (org-at-item-p)
  6197. (progn
  6198. (beginning-of-line)
  6199. (setq struct (org-list-struct))
  6200. (setq eoh (point-at-eol))
  6201. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6202. (setq has-children (org-list-has-child-p (point) struct)))
  6203. (org-back-to-heading)
  6204. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6205. (setq eos (save-excursion (org-end-of-subtree t t)
  6206. (when (bolp) (backward-char)) (point)))
  6207. (setq has-children
  6208. (or (save-excursion
  6209. (let ((level (funcall outline-level)))
  6210. (outline-next-heading)
  6211. (and (org-at-heading-p t)
  6212. (> (funcall outline-level) level))))
  6213. (save-excursion
  6214. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6215. ;; Determine end invisible part of buffer (EOL)
  6216. (beginning-of-line 2)
  6217. (while (and (not (eobp)) ;This is like `next-line'.
  6218. (get-char-property (1- (point)) 'invisible))
  6219. (goto-char (next-single-char-property-change (point) 'invisible))
  6220. (and (eolp) (beginning-of-line 2)))
  6221. (setq eol (point)))
  6222. ;; Find out what to do next and set `this-command'
  6223. (cond
  6224. ((= eos eoh)
  6225. ;; Nothing is hidden behind this heading
  6226. (unless (org-before-first-heading-p)
  6227. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6228. (org-unlogged-message "EMPTY ENTRY")
  6229. (setq org-cycle-subtree-status nil)
  6230. (save-excursion
  6231. (goto-char eos)
  6232. (outline-next-heading)
  6233. (when (org-invisible-p) (org-flag-heading nil))))
  6234. ((and (or (>= eol eos)
  6235. (not (string-match "\\S-" (buffer-substring eol eos))))
  6236. (or has-children
  6237. (not (setq children-skipped
  6238. org-cycle-skip-children-state-if-no-children))))
  6239. ;; Entire subtree is hidden in one line: children view
  6240. (unless (org-before-first-heading-p)
  6241. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6242. (if (org-at-item-p)
  6243. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6244. (org-show-entry)
  6245. (org-with-limited-levels (org-show-children))
  6246. (org-show-set-visibility 'canonical)
  6247. ;; Fold every list in subtree to top-level items.
  6248. (when (eq org-cycle-include-plain-lists 'integrate)
  6249. (save-excursion
  6250. (org-back-to-heading)
  6251. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6252. (beginning-of-line 1)
  6253. (let* ((struct (org-list-struct))
  6254. (prevs (org-list-prevs-alist struct))
  6255. (end (org-list-get-bottom-point struct)))
  6256. (dolist (e (org-list-get-all-items (point) struct prevs))
  6257. (org-list-set-item-visibility e struct 'folded))
  6258. (goto-char (if (< end eos) end eos)))))))
  6259. (org-unlogged-message "CHILDREN")
  6260. (save-excursion
  6261. (goto-char eos)
  6262. (outline-next-heading)
  6263. (when (org-invisible-p) (org-flag-heading nil)))
  6264. (setq org-cycle-subtree-status 'children)
  6265. (unless (org-before-first-heading-p)
  6266. (run-hook-with-args 'org-cycle-hook 'children)))
  6267. ((or children-skipped
  6268. (and (eq last-command this-command)
  6269. (eq org-cycle-subtree-status 'children)))
  6270. ;; We just showed the children, or no children are there,
  6271. ;; now show everything.
  6272. (unless (org-before-first-heading-p)
  6273. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6274. (org-flag-region eoh eos nil 'outline)
  6275. (org-unlogged-message
  6276. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6277. (setq org-cycle-subtree-status 'subtree)
  6278. (unless (org-before-first-heading-p)
  6279. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6280. (t
  6281. ;; Default action: hide the subtree.
  6282. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6283. (org-flag-region eoh eos t 'outline)
  6284. (org-unlogged-message "FOLDED")
  6285. (setq org-cycle-subtree-status 'folded)
  6286. (unless (org-before-first-heading-p)
  6287. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6288. ;;;###autoload
  6289. (defun org-global-cycle (&optional arg)
  6290. "Cycle the global visibility. For details see `org-cycle'.
  6291. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6292. With a numeric prefix, show all headlines up to that level."
  6293. (interactive "P")
  6294. (let ((org-cycle-include-plain-lists
  6295. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6296. (cond
  6297. ((integerp arg)
  6298. (org-show-all '(headings blocks))
  6299. (outline-hide-sublevels arg)
  6300. (setq org-cycle-global-status 'contents))
  6301. ((equal arg '(4))
  6302. (org-set-startup-visibility)
  6303. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6304. (t
  6305. (org-cycle '(4))))))
  6306. (defun org-set-startup-visibility ()
  6307. "Set the visibility required by startup options and properties."
  6308. (cond
  6309. ((eq org-startup-folded t)
  6310. (org-overview))
  6311. ((eq org-startup-folded 'content)
  6312. (org-content))
  6313. ((or (eq org-startup-folded 'showeverything)
  6314. (eq org-startup-folded nil))
  6315. (org-show-all)))
  6316. (unless (eq org-startup-folded 'showeverything)
  6317. (when org-hide-block-startup (org-hide-block-all))
  6318. (org-set-visibility-according-to-property)
  6319. (org-cycle-hide-archived-subtrees 'all)
  6320. (org-cycle-hide-drawers 'all)
  6321. (org-cycle-show-empty-lines t)))
  6322. (defun org-set-visibility-according-to-property ()
  6323. "Switch subtree visibilities according to :VISIBILITY: property."
  6324. (interactive)
  6325. (org-with-wide-buffer
  6326. (goto-char (point-min))
  6327. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6328. (if (not (org-at-property-p)) (outline-next-heading)
  6329. (let ((state (match-string 3)))
  6330. (save-excursion
  6331. (org-back-to-heading t)
  6332. (outline-hide-subtree)
  6333. (org-reveal)
  6334. (cond
  6335. ((equal state "folded")
  6336. (outline-hide-subtree))
  6337. ((equal state "children")
  6338. (org-show-hidden-entry)
  6339. (org-show-children))
  6340. ((equal state "content")
  6341. (save-excursion
  6342. (save-restriction
  6343. (org-narrow-to-subtree)
  6344. (org-content))))
  6345. ((member state '("all" "showall"))
  6346. (outline-show-subtree)))))))))
  6347. (defun org-overview ()
  6348. "Switch to overview mode, showing only top-level headlines.
  6349. This shows all headlines with a level equal or greater than the level
  6350. of the first headline in the buffer. This is important, because if the
  6351. first headline is not level one, then (hide-sublevels 1) gives confusing
  6352. results."
  6353. (interactive)
  6354. (save-excursion
  6355. (let ((level
  6356. (save-excursion
  6357. (goto-char (point-min))
  6358. (when (re-search-forward org-outline-regexp-bol nil t)
  6359. (goto-char (match-beginning 0))
  6360. (funcall outline-level)))))
  6361. (and level (outline-hide-sublevels level)))))
  6362. (defun org-content (&optional arg)
  6363. "Show all headlines in the buffer, like a table of contents.
  6364. With numerical argument N, show content up to level N."
  6365. (interactive "P")
  6366. (org-overview)
  6367. (save-excursion
  6368. ;; Visit all headings and show their offspring
  6369. (and (integerp arg) (org-overview))
  6370. (goto-char (point-max))
  6371. (catch 'exit
  6372. (while (and (progn (condition-case nil
  6373. (outline-previous-visible-heading 1)
  6374. (error (goto-char (point-min))))
  6375. t)
  6376. (looking-at org-outline-regexp))
  6377. (if (integerp arg)
  6378. (org-show-children (1- arg))
  6379. (outline-show-branches))
  6380. (when (bobp) (throw 'exit nil))))))
  6381. (defun org-optimize-window-after-visibility-change (state)
  6382. "Adjust the window after a change in outline visibility.
  6383. This function is the default value of the hook `org-cycle-hook'."
  6384. (when (get-buffer-window (current-buffer))
  6385. (cond
  6386. ((eq state 'content) nil)
  6387. ((eq state 'all) nil)
  6388. ((eq state 'folded) nil)
  6389. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6390. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6391. (defun org-clean-visibility-after-subtree-move ()
  6392. "Fix visibility issues after moving a subtree."
  6393. ;; First, find a reasonable region to look at:
  6394. ;; Start two siblings above, end three below
  6395. (let* ((beg (save-excursion
  6396. (and (org-get-last-sibling)
  6397. (org-get-last-sibling))
  6398. (point)))
  6399. (end (save-excursion
  6400. (and (org-get-next-sibling)
  6401. (org-get-next-sibling)
  6402. (org-get-next-sibling))
  6403. (if (org-at-heading-p)
  6404. (point-at-eol)
  6405. (point))))
  6406. (level (looking-at "\\*+"))
  6407. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6408. (save-excursion
  6409. (save-restriction
  6410. (narrow-to-region beg end)
  6411. (when re
  6412. ;; Properly fold already folded siblings
  6413. (goto-char (point-min))
  6414. (while (re-search-forward re nil t)
  6415. (when (and (not (org-invisible-p))
  6416. (org-invisible-p (line-end-position)))
  6417. (outline-hide-entry))))
  6418. (org-cycle-hide-drawers 'all)
  6419. (org-cycle-show-empty-lines 'overview)))))
  6420. (defun org-cycle-show-empty-lines (state)
  6421. "Show empty lines above all visible headlines.
  6422. The region to be covered depends on STATE when called through
  6423. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6424. entire buffer covered. Note that an empty line is only shown if there
  6425. are at least `org-cycle-separator-lines' empty lines before the headline."
  6426. (when (/= org-cycle-separator-lines 0)
  6427. (save-excursion
  6428. (let* ((n (abs org-cycle-separator-lines))
  6429. (re (cond
  6430. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6431. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6432. (t (let ((ns (number-to-string (- n 2))))
  6433. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6434. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6435. beg end)
  6436. (cond
  6437. ((memq state '(overview contents t))
  6438. (setq beg (point-min) end (point-max)))
  6439. ((memq state '(children folded))
  6440. (setq beg (point)
  6441. end (progn (org-end-of-subtree t t)
  6442. (line-beginning-position 2)))))
  6443. (when beg
  6444. (goto-char beg)
  6445. (while (re-search-forward re end t)
  6446. (unless (get-char-property (match-end 1) 'invisible)
  6447. (let ((e (match-end 1))
  6448. (b (if (>= org-cycle-separator-lines 0)
  6449. (match-beginning 1)
  6450. (save-excursion
  6451. (goto-char (match-beginning 0))
  6452. (skip-chars-backward " \t\n")
  6453. (line-end-position)))))
  6454. (org-flag-region b e nil 'outline))))))))
  6455. ;; Never hide empty lines at the end of the file.
  6456. (save-excursion
  6457. (goto-char (point-max))
  6458. (outline-previous-heading)
  6459. (outline-end-of-heading)
  6460. (when (and (looking-at "[ \t\n]+")
  6461. (= (match-end 0) (point-max)))
  6462. (org-flag-region (point) (match-end 0) nil 'outline))))
  6463. ;;;; Reveal point location
  6464. (defun org-show-context (&optional key)
  6465. "Make sure point and context are visible.
  6466. Optional argument KEY, when non-nil, is a symbol. See
  6467. `org-show-context-detail' for allowed values and how much is to
  6468. be shown."
  6469. (org-show-set-visibility
  6470. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  6471. ((cdr (assq key org-show-context-detail)))
  6472. (t (cdr (assq 'default org-show-context-detail))))))
  6473. (defun org-show-set-visibility (detail)
  6474. "Set visibility around point according to DETAIL.
  6475. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  6476. `tree', `canonical' or t. See `org-show-context-detail' for more
  6477. information."
  6478. ;; Show current heading and possibly its entry, following headline
  6479. ;; or all children.
  6480. (if (and (org-at-heading-p) (not (eq detail 'local)))
  6481. (org-flag-heading nil)
  6482. (org-show-entry)
  6483. ;; If point is hidden within a drawer or a block, make sure to
  6484. ;; expose it.
  6485. (dolist (o (overlays-at (point)))
  6486. (when (memq (overlay-get o 'invisible)
  6487. '(org-hide-block org-hide-drawer outline))
  6488. (delete-overlay o)))
  6489. (unless (org-before-first-heading-p)
  6490. (org-with-limited-levels
  6491. (cl-case detail
  6492. ((tree canonical t) (org-show-children))
  6493. ((nil minimal ancestors))
  6494. (t (save-excursion
  6495. (outline-next-heading)
  6496. (org-flag-heading nil)))))))
  6497. ;; Show all siblings.
  6498. (when (eq detail 'lineage) (org-show-siblings))
  6499. ;; Show ancestors, possibly with their children.
  6500. (when (memq detail '(ancestors lineage tree canonical t))
  6501. (save-excursion
  6502. (while (org-up-heading-safe)
  6503. (org-flag-heading nil)
  6504. (when (memq detail '(canonical t)) (org-show-entry))
  6505. (when (memq detail '(tree canonical t)) (org-show-children))))))
  6506. (defvar org-reveal-start-hook nil
  6507. "Hook run before revealing a location.")
  6508. (defun org-reveal (&optional siblings)
  6509. "Show current entry, hierarchy above it, and the following headline.
  6510. This can be used to show a consistent set of context around
  6511. locations exposed with `org-show-context'.
  6512. With optional argument SIBLINGS, on each level of the hierarchy all
  6513. siblings are shown. This repairs the tree structure to what it would
  6514. look like when opened with hierarchical calls to `org-cycle'.
  6515. With a \\[universal-argument] \\[universal-argument] prefix, \
  6516. go to the parent and show the entire tree."
  6517. (interactive "P")
  6518. (run-hooks 'org-reveal-start-hook)
  6519. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6520. ((equal siblings '(16))
  6521. (save-excursion
  6522. (when (org-up-heading-safe)
  6523. (org-show-subtree)
  6524. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6525. (t (org-show-set-visibility 'lineage))))
  6526. ;;; Indirect buffer display of subtrees
  6527. (defvar org-indirect-dedicated-frame nil
  6528. "This is the frame being used for indirect tree display.")
  6529. (defvar org-last-indirect-buffer nil)
  6530. (defun org-tree-to-indirect-buffer (&optional arg)
  6531. "Create indirect buffer and narrow it to current subtree.
  6532. With a numerical prefix ARG, go up to this level and then take that tree.
  6533. If ARG is negative, go up that many levels.
  6534. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6535. indirect buffer previously made with this command, to avoid proliferation of
  6536. indirect buffers. However, when you call the command with a \
  6537. `\\[universal-argument]' prefix, or
  6538. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6539. so that you can work with several indirect buffers at the same time. If
  6540. `org-indirect-buffer-display' is `dedicated-frame', the \
  6541. `\\[universal-argument]' prefix also
  6542. requests that a new frame be made for the new buffer, so that the dedicated
  6543. frame is not changed."
  6544. (interactive "P")
  6545. (let ((cbuf (current-buffer))
  6546. (cwin (selected-window))
  6547. (pos (point))
  6548. beg end level heading ibuf)
  6549. (save-excursion
  6550. (org-back-to-heading t)
  6551. (when (numberp arg)
  6552. (setq level (org-outline-level))
  6553. (when (< arg 0) (setq arg (+ level arg)))
  6554. (while (> (setq level (org-outline-level)) arg)
  6555. (org-up-heading-safe)))
  6556. (setq beg (point)
  6557. heading (org-get-heading 'no-tags))
  6558. (org-end-of-subtree t t)
  6559. (when (org-at-heading-p) (backward-char 1))
  6560. (setq end (point)))
  6561. (when (and (buffer-live-p org-last-indirect-buffer)
  6562. (not (eq org-indirect-buffer-display 'new-frame))
  6563. (not arg))
  6564. (kill-buffer org-last-indirect-buffer))
  6565. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6566. org-last-indirect-buffer ibuf)
  6567. (cond
  6568. ((or (eq org-indirect-buffer-display 'new-frame)
  6569. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6570. (select-frame (make-frame))
  6571. (delete-other-windows)
  6572. (pop-to-buffer-same-window ibuf)
  6573. (org-set-frame-title heading))
  6574. ((eq org-indirect-buffer-display 'dedicated-frame)
  6575. (raise-frame
  6576. (select-frame (or (and org-indirect-dedicated-frame
  6577. (frame-live-p org-indirect-dedicated-frame)
  6578. org-indirect-dedicated-frame)
  6579. (setq org-indirect-dedicated-frame (make-frame)))))
  6580. (delete-other-windows)
  6581. (pop-to-buffer-same-window ibuf)
  6582. (org-set-frame-title (concat "Indirect: " heading)))
  6583. ((eq org-indirect-buffer-display 'current-window)
  6584. (pop-to-buffer-same-window ibuf))
  6585. ((eq org-indirect-buffer-display 'other-window)
  6586. (pop-to-buffer ibuf))
  6587. (t (error "Invalid value")))
  6588. (narrow-to-region beg end)
  6589. (org-show-all '(headings blocks))
  6590. (goto-char pos)
  6591. (run-hook-with-args 'org-cycle-hook 'all)
  6592. (and (window-live-p cwin) (select-window cwin))))
  6593. (defun org-get-indirect-buffer (&optional buffer heading)
  6594. (setq buffer (or buffer (current-buffer)))
  6595. (let ((n 1) (base (buffer-name buffer)) bname)
  6596. (while (buffer-live-p
  6597. (get-buffer
  6598. (setq bname
  6599. (concat base "-"
  6600. (if heading (concat heading "-" (number-to-string n))
  6601. (number-to-string n))))))
  6602. (setq n (1+ n)))
  6603. (condition-case nil
  6604. (make-indirect-buffer buffer bname 'clone)
  6605. (error (make-indirect-buffer buffer bname)))))
  6606. (defun org-set-frame-title (title)
  6607. "Set the title of the current frame to the string TITLE."
  6608. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6609. ;;;; Structure editing
  6610. ;;; Inserting headlines
  6611. (defun org--line-empty-p (n)
  6612. "Is the Nth next line empty?
  6613. Counts the current line as N = 1 and the previous line as N = 0;
  6614. see `beginning-of-line'."
  6615. (save-excursion
  6616. (and (not (bobp))
  6617. (or (beginning-of-line n) t)
  6618. (save-match-data
  6619. (looking-at "[ \t]*$")))))
  6620. (defun org-previous-line-empty-p ()
  6621. "Is the previous line a blank line?
  6622. When NEXT is non-nil, check the next line instead."
  6623. (org--line-empty-p 0))
  6624. (defun org-next-line-empty-p ()
  6625. "Is the previous line a blank line?
  6626. When NEXT is non-nil, check the next line instead."
  6627. (org--line-empty-p 2))
  6628. (defun org--blank-before-heading-p (&optional parent)
  6629. "Non-nil when an empty line should precede a new heading here.
  6630. When optional argument PARENT is non-nil, consider parent
  6631. headline instead of current one."
  6632. (pcase (assq 'heading org-blank-before-new-entry)
  6633. (`(heading . auto)
  6634. (save-excursion
  6635. (org-with-limited-levels
  6636. (unless (and (org-before-first-heading-p)
  6637. (not (outline-next-heading)))
  6638. (org-back-to-heading t)
  6639. (when parent (org-up-heading-safe))
  6640. (cond ((not (bobp))
  6641. (org-previous-line-empty-p))
  6642. ((outline-next-heading)
  6643. (org-previous-line-empty-p))
  6644. ;; Ignore trailing spaces on last buffer line.
  6645. ((progn (skip-chars-backward " \t") (bolp))
  6646. (org-previous-line-empty-p))
  6647. (t nil))))))
  6648. (`(heading . ,value) value)
  6649. (_ nil)))
  6650. (defun org-insert-heading (&optional arg invisible-ok top)
  6651. "Insert a new heading or an item with the same depth at point.
  6652. If point is at the beginning of a heading, insert a new heading
  6653. or a new headline above the current one. When at the beginning
  6654. of a regular line of text, turn it into a heading.
  6655. If point is in the middle of a line, split it and create a new
  6656. headline with the text in the current line after point (see
  6657. `org-M-RET-may-split-line' on how to modify this behavior). As
  6658. a special case, on a headline, splitting can only happen on the
  6659. title itself. E.g., this excludes breaking stars or tags.
  6660. With a `\\[universal-argument]' prefix, set \
  6661. `org-insert-heading-respect-content' to
  6662. a non-nil value for the duration of the command. This forces the
  6663. insertion of a heading after the current subtree, independently
  6664. on the location of point.
  6665. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6666. insert the heading at the end of the tree
  6667. above the current heading. For example, if point is within a
  6668. 2nd-level heading, then it will insert a 2nd-level heading at
  6669. the end of the 1st-level parent subtree.
  6670. When INVISIBLE-OK is set, stop at invisible headlines when going
  6671. back. This is important for non-interactive uses of the
  6672. command.
  6673. When optional argument TOP is non-nil, insert a level 1 heading,
  6674. unconditionally."
  6675. (interactive "P")
  6676. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6677. (level (org-current-level))
  6678. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6679. (cond
  6680. ((or org-insert-heading-respect-content
  6681. (member arg '((4) (16)))
  6682. (and (not invisible-ok)
  6683. (invisible-p (max (1- (point)) (point-min)))))
  6684. ;; Position point at the location of insertion.
  6685. (if (not level) ;before first headline
  6686. (org-with-limited-levels (outline-next-heading))
  6687. ;; Make sure we end up on a visible headline if INVISIBLE-OK
  6688. ;; is nil.
  6689. (org-with-limited-levels (org-back-to-heading invisible-ok))
  6690. (cond ((equal arg '(16))
  6691. (org-up-heading-safe)
  6692. (org-end-of-subtree t t))
  6693. (t
  6694. (org-end-of-subtree t t))))
  6695. (unless (bolp) (insert "\n")) ;ensure final newline
  6696. (unless (and blank? (org-previous-line-empty-p))
  6697. (org-N-empty-lines-before-current (if blank? 1 0)))
  6698. (insert stars " \n")
  6699. (forward-char -1))
  6700. ;; At a headline...
  6701. ((org-at-heading-p)
  6702. (cond ((bolp)
  6703. (when blank? (save-excursion (insert "\n")))
  6704. (save-excursion (insert stars " \n"))
  6705. (unless (and blank? (org-previous-line-empty-p))
  6706. (org-N-empty-lines-before-current (if blank? 1 0)))
  6707. (end-of-line))
  6708. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6709. (org-match-line org-complex-heading-regexp)
  6710. (org-pos-in-match-range (point) 4))
  6711. ;; Grab the text that should moved to the new headline.
  6712. ;; Preserve tags.
  6713. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6714. (if (looking-at "[ \t]*$") (replace-match "")
  6715. (org-set-tags nil t))
  6716. (end-of-line)
  6717. (when blank? (insert "\n"))
  6718. (insert "\n" stars " ")
  6719. (when (org-string-nw-p split) (insert split))
  6720. (when (eobp) (save-excursion (insert "\n")))))
  6721. (t
  6722. (end-of-line)
  6723. (when blank? (insert "\n"))
  6724. (insert "\n" stars " ")
  6725. (when (eobp) (save-excursion (insert "\n"))))))
  6726. ;; On regular text, turn line into a headline or split, if
  6727. ;; appropriate.
  6728. ((bolp)
  6729. (insert stars " ")
  6730. (unless (and blank? (org-previous-line-empty-p))
  6731. (org-N-empty-lines-before-current (if blank? 1 0))))
  6732. (t
  6733. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6734. (end-of-line))
  6735. (insert "\n" stars " ")
  6736. (unless (and blank? (org-previous-line-empty-p))
  6737. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6738. (run-hooks 'org-insert-heading-hook))
  6739. (defun org-N-empty-lines-before-current (n)
  6740. "Make the number of empty lines before current exactly N.
  6741. So this will delete or add empty lines."
  6742. (let ((column (current-column)))
  6743. (beginning-of-line)
  6744. (unless (bobp)
  6745. (let ((start (save-excursion
  6746. (skip-chars-backward " \r\t\n")
  6747. (line-end-position))))
  6748. (delete-region start (line-end-position 0))))
  6749. (insert (make-string n ?\n))
  6750. (move-to-column column)))
  6751. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6752. "Return the heading of the current entry, without the stars.
  6753. When NO-TAGS is non-nil, don't include tags.
  6754. When NO-TODO is non-nil, don't include TODO keywords.
  6755. When NO-PRIORITY is non-nil, don't include priority cookie.
  6756. When NO-COMMENT is non-nil, don't include COMMENT string."
  6757. (save-excursion
  6758. (org-back-to-heading t)
  6759. (let ((case-fold-search nil))
  6760. (looking-at org-complex-heading-regexp)
  6761. (let ((todo (and (not no-todo) (match-string 2)))
  6762. (priority (and (not no-priority) (match-string 3)))
  6763. (headline (pcase (match-string 4)
  6764. (`nil "")
  6765. ((and (guard no-comment) h)
  6766. (replace-regexp-in-string
  6767. (eval-when-compile
  6768. (format "\\`%s[ \t]+" org-comment-string))
  6769. "" h))
  6770. (h h)))
  6771. (tags (and (not no-tags) (match-string 5))))
  6772. (mapconcat #'identity
  6773. (delq nil (list todo priority headline tags))
  6774. " ")))))
  6775. (defun org-heading-components ()
  6776. "Return the components of the current heading.
  6777. This is a list with the following elements:
  6778. - the level as an integer
  6779. - the reduced level, different if `org-odd-levels-only' is set.
  6780. - the TODO keyword, or nil
  6781. - the priority character, like ?A, or nil if no priority is given
  6782. - the headline text itself, or the tags string if no headline text
  6783. - the tags string, or nil."
  6784. (save-excursion
  6785. (org-back-to-heading t)
  6786. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6787. (list (length (match-string 1))
  6788. (org-reduced-level (length (match-string 1)))
  6789. (match-string-no-properties 2)
  6790. (and (match-end 3) (aref (match-string 3) 2))
  6791. (match-string-no-properties 4)
  6792. (match-string-no-properties 5)))))
  6793. (defun org-get-entry ()
  6794. "Get the entry text, after heading, entire subtree."
  6795. (save-excursion
  6796. (org-back-to-heading t)
  6797. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6798. (defun org-edit-headline (&optional heading)
  6799. "Edit the current headline.
  6800. Set it to HEADING when provided."
  6801. (interactive)
  6802. (org-with-wide-buffer
  6803. (org-back-to-heading t)
  6804. (let ((case-fold-search nil))
  6805. (when (looking-at org-complex-heading-regexp)
  6806. (let* ((old (match-string-no-properties 4))
  6807. (new (save-match-data
  6808. (org-trim (or heading (read-string "Edit: " old))))))
  6809. (unless (equal old new)
  6810. (if old (replace-match new t t nil 4)
  6811. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6812. (insert " " new))
  6813. (org-set-tags nil t)
  6814. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6815. (defun org-insert-heading-after-current ()
  6816. "Insert a new heading with same level as current, after current subtree."
  6817. (interactive)
  6818. (org-back-to-heading)
  6819. (org-insert-heading)
  6820. (org-move-subtree-down)
  6821. (end-of-line 1))
  6822. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6823. "Insert heading with `org-insert-heading-respect-content' set to t."
  6824. (interactive)
  6825. (org-insert-heading '(4) invisible-ok))
  6826. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6827. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6828. (interactive)
  6829. (org-insert-todo-heading force-state '(4)))
  6830. (defun org-insert-todo-heading (arg &optional force-heading)
  6831. "Insert a new heading with the same level and TODO state as current heading.
  6832. If the heading has no TODO state, or if the state is DONE, use
  6833. the first state (TODO by default). Also with one prefix arg,
  6834. force first state. With two prefix args, force inserting at the
  6835. end of the parent subtree.
  6836. When called at a plain list item, insert a new item with an
  6837. unchecked check box."
  6838. (interactive "P")
  6839. (when (or force-heading (not (org-insert-item 'checkbox)))
  6840. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6841. force-heading))
  6842. (save-excursion
  6843. (org-forward-heading-same-level -1)
  6844. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6845. (let* ((new-mark-x
  6846. (if (or (equal arg '(4))
  6847. (not (match-beginning 2))
  6848. (member (match-string 2) org-done-keywords))
  6849. (car org-todo-keywords-1)
  6850. (match-string 2)))
  6851. (new-mark
  6852. (or
  6853. (run-hook-with-args-until-success
  6854. 'org-todo-get-default-hook new-mark-x nil)
  6855. new-mark-x)))
  6856. (beginning-of-line 1)
  6857. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6858. (if org-treat-insert-todo-heading-as-state-change
  6859. (org-todo new-mark)
  6860. (insert new-mark " "))))
  6861. (when org-provide-todo-statistics
  6862. (org-update-parent-todo-statistics))))
  6863. (defun org-insert-subheading (arg)
  6864. "Insert a new subheading and demote it.
  6865. Works for outline headings and for plain lists alike."
  6866. (interactive "P")
  6867. (org-insert-heading arg)
  6868. (cond
  6869. ((org-at-heading-p) (org-do-demote))
  6870. ((org-at-item-p) (org-indent-item))))
  6871. (defun org-insert-todo-subheading (arg)
  6872. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6873. Works for outline headings and for plain lists alike."
  6874. (interactive "P")
  6875. (org-insert-todo-heading arg)
  6876. (cond
  6877. ((org-at-heading-p) (org-do-demote))
  6878. ((org-at-item-p) (org-indent-item))))
  6879. ;;; Promotion and Demotion
  6880. (defvar org-after-demote-entry-hook nil
  6881. "Hook run after an entry has been demoted.
  6882. The cursor will be at the beginning of the entry.
  6883. When a subtree is being demoted, the hook will be called for each node.")
  6884. (defvar org-after-promote-entry-hook nil
  6885. "Hook run after an entry has been promoted.
  6886. The cursor will be at the beginning of the entry.
  6887. When a subtree is being promoted, the hook will be called for each node.")
  6888. (defun org-promote-subtree ()
  6889. "Promote the entire subtree.
  6890. See also `org-promote'."
  6891. (interactive)
  6892. (save-excursion
  6893. (org-with-limited-levels (org-map-tree 'org-promote)))
  6894. (org-fix-position-after-promote))
  6895. (defun org-demote-subtree ()
  6896. "Demote the entire subtree.
  6897. See `org-demote' and `org-promote'."
  6898. (interactive)
  6899. (save-excursion
  6900. (org-with-limited-levels (org-map-tree 'org-demote)))
  6901. (org-fix-position-after-promote))
  6902. (defun org-do-promote ()
  6903. "Promote the current heading higher up the tree.
  6904. If the region is active in `transient-mark-mode', promote all
  6905. headings in the region."
  6906. (interactive)
  6907. (save-excursion
  6908. (if (org-region-active-p)
  6909. (org-map-region 'org-promote (region-beginning) (region-end))
  6910. (org-promote)))
  6911. (org-fix-position-after-promote))
  6912. (defun org-do-demote ()
  6913. "Demote the current heading lower down the tree.
  6914. If the region is active in `transient-mark-mode', demote all
  6915. headings in the region."
  6916. (interactive)
  6917. (save-excursion
  6918. (if (org-region-active-p)
  6919. (org-map-region 'org-demote (region-beginning) (region-end))
  6920. (org-demote)))
  6921. (org-fix-position-after-promote))
  6922. (defun org-fix-position-after-promote ()
  6923. "Fix cursor position and indentation after demoting/promoting."
  6924. (let ((pos (point)))
  6925. (when (save-excursion
  6926. (beginning-of-line)
  6927. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6928. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6929. (cond ((eobp) (insert " "))
  6930. ((eolp) (insert " "))
  6931. ((equal (char-after) ?\s) (forward-char 1))))))
  6932. (defun org-current-level ()
  6933. "Return the level of the current entry, or nil if before the first headline.
  6934. The level is the number of stars at the beginning of the
  6935. headline. Use `org-reduced-level' to remove the effect of
  6936. `org-odd-levels'. Unlike to `org-outline-level', this function
  6937. ignores inlinetasks."
  6938. (let ((level (org-with-limited-levels (org-outline-level))))
  6939. (and (> level 0) level)))
  6940. (defun org-get-previous-line-level ()
  6941. "Return the outline depth of the last headline before the current line.
  6942. Returns 0 for the first headline in the buffer, and nil if before the
  6943. first headline."
  6944. (and (org-current-level)
  6945. (or (and (/= (line-beginning-position) (point-min))
  6946. (save-excursion (beginning-of-line 0) (org-current-level)))
  6947. 0)))
  6948. (defun org-reduced-level (l)
  6949. "Compute the effective level of a heading.
  6950. This takes into account the setting of `org-odd-levels-only'."
  6951. (cond
  6952. ((zerop l) 0)
  6953. (org-odd-levels-only (1+ (floor (/ l 2))))
  6954. (t l)))
  6955. (defun org-level-increment ()
  6956. "Return the number of stars that will be added or removed at a
  6957. time to headlines when structure editing, based on the value of
  6958. `org-odd-levels-only'."
  6959. (if org-odd-levels-only 2 1))
  6960. (defun org-get-valid-level (level &optional change)
  6961. "Rectify a level change under the influence of `org-odd-levels-only'.
  6962. LEVEL is a current level, CHANGE is by how much the level should
  6963. be modified. Even if CHANGE is nil, LEVEL may be returned
  6964. modified because even level numbers will become the next higher
  6965. odd number. Returns values greater than 0."
  6966. (if org-odd-levels-only
  6967. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6968. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6969. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6970. (max 1 (+ level (or change 0)))))
  6971. (defun org-promote ()
  6972. "Promote the current heading higher up the tree."
  6973. (org-with-wide-buffer
  6974. (org-back-to-heading t)
  6975. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6976. after-change-functions))
  6977. (level (save-match-data (funcall outline-level)))
  6978. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6979. (diff (abs (- level (length up-head) -1))))
  6980. (cond
  6981. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6982. (replace-match "# " nil t))
  6983. ((= level 1)
  6984. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6985. (t (replace-match up-head nil t)))
  6986. (unless (= level 1)
  6987. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  6988. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6989. (run-hooks 'org-after-promote-entry-hook))))
  6990. (defun org-demote ()
  6991. "Demote the current heading lower down the tree."
  6992. (org-with-wide-buffer
  6993. (org-back-to-heading t)
  6994. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6995. after-change-functions))
  6996. (level (save-match-data (funcall outline-level)))
  6997. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6998. (diff (abs (- level (length down-head) -1))))
  6999. (replace-match down-head nil t)
  7000. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7001. (when org-adapt-indentation (org-fixup-indentation diff))
  7002. (run-hooks 'org-after-demote-entry-hook))))
  7003. (defun org-cycle-level ()
  7004. "Cycle the level of an empty headline through possible states.
  7005. This goes first to child, then to parent, level, then up the hierarchy.
  7006. After top level, it switches back to sibling level."
  7007. (interactive)
  7008. (let ((org-adapt-indentation nil))
  7009. (when (org-point-at-end-of-empty-headline)
  7010. (setq this-command 'org-cycle-level) ; Only needed for caching
  7011. (let ((cur-level (org-current-level))
  7012. (prev-level (org-get-previous-line-level)))
  7013. (cond
  7014. ;; If first headline in file, promote to top-level.
  7015. ((= prev-level 0)
  7016. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7017. do (org-do-promote)))
  7018. ;; If same level as prev, demote one.
  7019. ((= prev-level cur-level)
  7020. (org-do-demote))
  7021. ;; If parent is top-level, promote to top level if not already.
  7022. ((= prev-level 1)
  7023. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7024. do (org-do-promote)))
  7025. ;; If top-level, return to prev-level.
  7026. ((= cur-level 1)
  7027. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7028. do (org-do-demote)))
  7029. ;; If less than prev-level, promote one.
  7030. ((< cur-level prev-level)
  7031. (org-do-promote))
  7032. ;; If deeper than prev-level, promote until higher than
  7033. ;; prev-level.
  7034. ((> cur-level prev-level)
  7035. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7036. do (org-do-promote))))
  7037. t))))
  7038. (defun org-map-tree (fun)
  7039. "Call FUN for every heading underneath the current one."
  7040. (org-back-to-heading t)
  7041. (let ((level (funcall outline-level)))
  7042. (save-excursion
  7043. (funcall fun)
  7044. (while (and (progn
  7045. (outline-next-heading)
  7046. (> (funcall outline-level) level))
  7047. (not (eobp)))
  7048. (funcall fun)))))
  7049. (defun org-map-region (fun beg end)
  7050. "Call FUN for every heading between BEG and END."
  7051. (let ((org-ignore-region t))
  7052. (save-excursion
  7053. (setq end (copy-marker end))
  7054. (goto-char beg)
  7055. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7056. (< (point) end))
  7057. (funcall fun))
  7058. (while (and (progn
  7059. (outline-next-heading)
  7060. (< (point) end))
  7061. (not (eobp)))
  7062. (funcall fun)))))
  7063. (defun org-fixup-indentation (diff)
  7064. "Change the indentation in the current entry by DIFF.
  7065. DIFF is an integer. Indentation is done according to the
  7066. following rules:
  7067. - Planning information and property drawers are always indented
  7068. according to the new level of the headline;
  7069. - Footnote definitions and their contents are ignored;
  7070. - Inlinetasks' boundaries are not shifted;
  7071. - Empty lines are ignored;
  7072. - Other lines' indentation are shifted by DIFF columns, unless
  7073. it would introduce a structural change in the document, in
  7074. which case no shifting is done at all.
  7075. Assume point is at a heading or an inlinetask beginning."
  7076. (org-with-wide-buffer
  7077. (narrow-to-region (line-beginning-position)
  7078. (save-excursion
  7079. (if (org-with-limited-levels (org-at-heading-p))
  7080. (org-with-limited-levels (outline-next-heading))
  7081. (org-inlinetask-goto-end))
  7082. (point)))
  7083. (forward-line)
  7084. ;; Indent properly planning info and property drawer.
  7085. (when (looking-at-p org-planning-line-re)
  7086. (org-indent-line)
  7087. (forward-line))
  7088. (when (looking-at org-property-drawer-re)
  7089. (goto-char (match-end 0))
  7090. (forward-line)
  7091. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7092. (catch 'no-shift
  7093. (when (zerop diff) (throw 'no-shift nil))
  7094. ;; If DIFF is negative, first check if a shift is possible at all
  7095. ;; (e.g., it doesn't break structure). This can only happen if
  7096. ;; some contents are not properly indented.
  7097. (let ((case-fold-search t))
  7098. (when (< diff 0)
  7099. (let ((diff (- diff))
  7100. (forbidden-re (concat org-outline-regexp
  7101. "\\|"
  7102. (substring org-footnote-definition-re 1))))
  7103. (save-excursion
  7104. (while (not (eobp))
  7105. (cond
  7106. ((looking-at-p "[ \t]*$") (forward-line))
  7107. ((and (looking-at-p org-footnote-definition-re)
  7108. (let ((e (org-element-at-point)))
  7109. (and (eq (org-element-type e) 'footnote-definition)
  7110. (goto-char (org-element-property :end e))))))
  7111. ((looking-at-p org-outline-regexp) (forward-line))
  7112. ;; Give up if shifting would move before column 0 or
  7113. ;; if it would introduce a headline or a footnote
  7114. ;; definition.
  7115. (t
  7116. (skip-chars-forward " \t")
  7117. (let ((ind (current-column)))
  7118. (when (or (< ind diff)
  7119. (and (= ind diff) (looking-at-p forbidden-re)))
  7120. (throw 'no-shift nil)))
  7121. ;; Ignore contents of example blocks and source
  7122. ;; blocks if their indentation is meant to be
  7123. ;; preserved. Jump to block's closing line.
  7124. (beginning-of-line)
  7125. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7126. (let ((e (org-element-at-point)))
  7127. (and (memq (org-element-type e)
  7128. '(example-block src-block))
  7129. (or org-src-preserve-indentation
  7130. (org-element-property :preserve-indent e))
  7131. (goto-char (org-element-property :end e))
  7132. (progn (skip-chars-backward " \r\t\n")
  7133. (beginning-of-line)
  7134. t))))
  7135. (forward-line))))))))
  7136. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7137. ;; by DIFF. Also skip contents of source or example blocks
  7138. ;; when indentation is meant to be preserved.
  7139. (while (not (eobp))
  7140. (cond
  7141. ((and (looking-at-p org-footnote-definition-re)
  7142. (let ((e (org-element-at-point)))
  7143. (and (eq (org-element-type e) 'footnote-definition)
  7144. (goto-char (org-element-property :end e))))))
  7145. ((looking-at-p org-outline-regexp) (forward-line))
  7146. ((looking-at-p "[ \t]*$") (forward-line))
  7147. (t
  7148. (indent-line-to (+ (org-get-indentation) diff))
  7149. (beginning-of-line)
  7150. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7151. (let ((e (org-element-at-point)))
  7152. (and (memq (org-element-type e)
  7153. '(example-block src-block))
  7154. (or org-src-preserve-indentation
  7155. (org-element-property :preserve-indent e))
  7156. (goto-char (org-element-property :end e))
  7157. (progn (skip-chars-backward " \r\t\n")
  7158. (beginning-of-line)
  7159. t))))
  7160. (forward-line)))))))))
  7161. (defun org-convert-to-odd-levels ()
  7162. "Convert an Org file with all levels allowed to one with odd levels.
  7163. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7164. level 5 etc."
  7165. (interactive)
  7166. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7167. (let ((outline-level 'org-outline-level)
  7168. (org-odd-levels-only nil) n)
  7169. (save-excursion
  7170. (goto-char (point-min))
  7171. (while (re-search-forward "^\\*\\*+ " nil t)
  7172. (setq n (- (length (match-string 0)) 2))
  7173. (while (>= (setq n (1- n)) 0)
  7174. (org-demote))
  7175. (end-of-line 1))))))
  7176. (defun org-convert-to-oddeven-levels ()
  7177. "Convert an Org file with only odd levels to one with odd/even levels.
  7178. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7179. file contains a section with an even level, conversion would
  7180. destroy the structure of the file. An error is signaled in this
  7181. case."
  7182. (interactive)
  7183. (goto-char (point-min))
  7184. ;; First check if there are no even levels
  7185. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7186. (org-show-set-visibility 'canonical)
  7187. (error "Not all levels are odd in this file. Conversion not possible"))
  7188. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7189. (let ((outline-regexp org-outline-regexp)
  7190. (outline-level 'org-outline-level)
  7191. (org-odd-levels-only nil) n)
  7192. (save-excursion
  7193. (goto-char (point-min))
  7194. (while (re-search-forward "^\\*\\*+ " nil t)
  7195. (setq n (/ (1- (length (match-string 0))) 2))
  7196. (while (>= (setq n (1- n)) 0)
  7197. (org-promote))
  7198. (end-of-line 1))))))
  7199. (defun org-tr-level (n)
  7200. "Make N odd if required."
  7201. (if org-odd-levels-only (1+ (/ n 2)) n))
  7202. ;;; Vertical tree motion, cutting and pasting of subtrees
  7203. (defun org-move-subtree-up (&optional arg)
  7204. "Move the current subtree up past ARG headlines of the same level."
  7205. (interactive "p")
  7206. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7207. (defun org-move-subtree-down (&optional arg)
  7208. "Move the current subtree down past ARG headlines of the same level."
  7209. (interactive "p")
  7210. (setq arg (prefix-numeric-value arg))
  7211. (org-preserve-local-variables
  7212. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7213. 'org-get-last-sibling))
  7214. (ins-point (make-marker))
  7215. (cnt (abs arg))
  7216. (col (current-column))
  7217. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7218. ;; Select the tree
  7219. (org-back-to-heading)
  7220. (setq beg0 (point))
  7221. (save-excursion
  7222. (setq ne-beg (org-back-over-empty-lines))
  7223. (setq beg (point)))
  7224. (save-match-data
  7225. (save-excursion (outline-end-of-heading)
  7226. (setq folded (org-invisible-p)))
  7227. (progn (org-end-of-subtree nil t)
  7228. (unless (eobp) (backward-char))))
  7229. (outline-next-heading)
  7230. (setq ne-end (org-back-over-empty-lines))
  7231. (setq end (point))
  7232. (goto-char beg0)
  7233. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7234. ;; include less whitespace
  7235. (save-excursion
  7236. (goto-char beg)
  7237. (forward-line (- ne-beg ne-end))
  7238. (setq beg (point))))
  7239. ;; Find insertion point, with error handling
  7240. (while (> cnt 0)
  7241. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  7242. (goto-char beg0)
  7243. (user-error "Cannot move past superior level or buffer limit"))
  7244. (setq cnt (1- cnt)))
  7245. (when (> arg 0)
  7246. ;; Moving forward - still need to move over subtree
  7247. (org-end-of-subtree t t)
  7248. (save-excursion
  7249. (org-back-over-empty-lines)
  7250. (or (bolp) (newline))))
  7251. (setq ne-ins (org-back-over-empty-lines))
  7252. (move-marker ins-point (point))
  7253. (setq txt (buffer-substring beg end))
  7254. (org-save-markers-in-region beg end)
  7255. (delete-region beg end)
  7256. (org-remove-empty-overlays-at beg)
  7257. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  7258. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  7259. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7260. (let ((bbb (point)))
  7261. (insert-before-markers txt)
  7262. (org-reinstall-markers-in-region bbb)
  7263. (move-marker ins-point bbb))
  7264. (or (bolp) (insert "\n"))
  7265. (setq ins-end (point))
  7266. (goto-char ins-point)
  7267. (org-skip-whitespace)
  7268. (when (and (< arg 0)
  7269. (org-first-sibling-p)
  7270. (> ne-ins ne-beg))
  7271. ;; Move whitespace back to beginning
  7272. (save-excursion
  7273. (goto-char ins-end)
  7274. (let ((kill-whole-line t))
  7275. (kill-line (- ne-ins ne-beg)) (point)))
  7276. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7277. (move-marker ins-point nil)
  7278. (if folded
  7279. (outline-hide-subtree)
  7280. (org-show-entry)
  7281. (org-show-children))
  7282. (org-clean-visibility-after-subtree-move)
  7283. ;; move back to the initial column we were at
  7284. (move-to-column col))))
  7285. (defvar org-subtree-clip ""
  7286. "Clipboard for cut and paste of subtrees.
  7287. This is actually only a copy of the kill, because we use the normal kill
  7288. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7289. (defvar org-subtree-clip-folded nil
  7290. "Was the last copied subtree folded?
  7291. This is used to fold the tree back after pasting.")
  7292. (defun org-cut-subtree (&optional n)
  7293. "Cut the current subtree into the clipboard.
  7294. With prefix arg N, cut this many sequential subtrees.
  7295. This is a short-hand for marking the subtree and then cutting it."
  7296. (interactive "p")
  7297. (org-copy-subtree n 'cut))
  7298. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7299. "Copy the current subtree into the clipboard.
  7300. With prefix arg N, copy this many sequential subtrees.
  7301. This is a short-hand for marking the subtree and then copying it.
  7302. If CUT is non-nil, actually cut the subtree.
  7303. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7304. of some markers in the region, even if CUT is non-nil. This is
  7305. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7306. (interactive "p")
  7307. (org-preserve-local-variables
  7308. (let (beg end folded (beg0 (point)))
  7309. (if (called-interactively-p 'any)
  7310. (org-back-to-heading nil) ; take what looks like a subtree
  7311. (org-back-to-heading t)) ; take what is really there
  7312. (setq beg (point))
  7313. (skip-chars-forward " \t\r\n")
  7314. (save-match-data
  7315. (if nosubtrees
  7316. (outline-next-heading)
  7317. (save-excursion (outline-end-of-heading)
  7318. (setq folded (org-invisible-p)))
  7319. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7320. (org-end-of-subtree t t)))
  7321. ;; Include the end of an inlinetask
  7322. (when (and (featurep 'org-inlinetask)
  7323. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7324. "END[ \t]*$")))
  7325. (end-of-line))
  7326. (setq end (point))
  7327. (goto-char beg0)
  7328. (when (> end beg)
  7329. (setq org-subtree-clip-folded folded)
  7330. (when (or cut force-store-markers)
  7331. (org-save-markers-in-region beg end))
  7332. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7333. (setq org-subtree-clip (current-kill 0))
  7334. (message "%s: Subtree(s) with %d characters"
  7335. (if cut "Cut" "Copied")
  7336. (length org-subtree-clip))))))
  7337. (defun org-paste-subtree (&optional level tree for-yank remove)
  7338. "Paste the clipboard as a subtree, with modification of headline level.
  7339. The entire subtree is promoted or demoted in order to match a new headline
  7340. level.
  7341. If the cursor is at the beginning of a headline, the same level as
  7342. that headline is used to paste the tree.
  7343. If not, the new level is derived from the *visible* headings
  7344. before and after the insertion point, and taken to be the inferior headline
  7345. level of the two. So if the previous visible heading is level 3 and the
  7346. next is level 4 (or vice versa), level 4 will be used for insertion.
  7347. This makes sure that the subtree remains an independent subtree and does
  7348. not swallow low level entries.
  7349. You can also force a different level, either by using a numeric prefix
  7350. argument, or by inserting the heading marker by hand. For example, if the
  7351. cursor is after \"*****\", then the tree will be shifted to level 5.
  7352. If optional TREE is given, use this text instead of the kill ring.
  7353. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7354. move back over whitespace before inserting, and move point to the end of
  7355. the inserted text when done.
  7356. When REMOVE is non-nil, remove the subtree from the clipboard."
  7357. (interactive "P")
  7358. (setq tree (or tree (and kill-ring (current-kill 0))))
  7359. (unless (org-kill-is-subtree-p tree)
  7360. (user-error
  7361. (substitute-command-keys
  7362. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  7363. (org-with-limited-levels
  7364. (let* ((visp (not (org-invisible-p)))
  7365. (txt tree)
  7366. (old-level (if (string-match org-outline-regexp-bol txt)
  7367. (- (match-end 0) (match-beginning 0) 1)
  7368. -1))
  7369. (force-level
  7370. (cond
  7371. (level (prefix-numeric-value level))
  7372. ;; When point is right after the stars in an otherwise
  7373. ;; empty headline, use stars as the forced level.
  7374. ((and (looking-at-p "[ \t]*$")
  7375. (string-match-p "^\\*+ *"
  7376. (buffer-substring (line-beginning-position)
  7377. (point))))
  7378. (org-outline-level))
  7379. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  7380. (previous-level
  7381. (save-excursion
  7382. (org-previous-visible-heading 1)
  7383. (if (org-at-heading-p) (org-outline-level) 1)))
  7384. (next-level
  7385. (save-excursion
  7386. (if (org-at-heading-p) (org-outline-level)
  7387. (org-next-visible-heading 1)
  7388. (if (org-at-heading-p) (org-outline-level) 1))))
  7389. (new-level (or force-level (max previous-level next-level)))
  7390. (shift (if (or (= old-level -1)
  7391. (= new-level -1)
  7392. (= old-level new-level))
  7393. 0
  7394. (- new-level old-level)))
  7395. (delta (if (> shift 0) -1 1))
  7396. (func (if (> shift 0) #'org-demote #'org-promote))
  7397. (org-odd-levels-only nil)
  7398. beg end newend)
  7399. ;; Remove the forced level indicator.
  7400. (when (and force-level (not level))
  7401. (delete-region (line-beginning-position) (point)))
  7402. ;; Paste before the next visible heading or at end of buffer,
  7403. ;; unless point is at the beginning of a headline.
  7404. (unless (and (bolp) (org-at-heading-p))
  7405. (org-next-visible-heading 1)
  7406. (unless (bolp) (insert "\n")))
  7407. (setq beg (point))
  7408. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7409. (insert-before-markers txt)
  7410. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7411. (setq newend (point))
  7412. (org-reinstall-markers-in-region beg)
  7413. (setq end (point))
  7414. (goto-char beg)
  7415. (skip-chars-forward " \t\n\r")
  7416. (setq beg (point))
  7417. (when (and (org-invisible-p) visp)
  7418. (save-excursion (outline-show-heading)))
  7419. ;; Shift if necessary.
  7420. (unless (= shift 0)
  7421. (save-restriction
  7422. (narrow-to-region beg end)
  7423. (while (not (= shift 0))
  7424. (org-map-region func (point-min) (point-max))
  7425. (setq shift (+ delta shift)))
  7426. (goto-char (point-min))
  7427. (setq newend (point-max))))
  7428. (when (or for-yank (called-interactively-p 'interactive))
  7429. (message "Clipboard pasted as level %d subtree" new-level))
  7430. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7431. kill-ring
  7432. (equal org-subtree-clip (current-kill 0))
  7433. org-subtree-clip-folded)
  7434. ;; The tree was folded before it was killed/copied
  7435. (outline-hide-subtree))
  7436. (when for-yank (goto-char newend))
  7437. (when remove (pop kill-ring)))))
  7438. (defun org-kill-is-subtree-p (&optional txt)
  7439. "Check if the current kill is an outline subtree, or a set of trees.
  7440. Returns nil if kill does not start with a headline, or if the first
  7441. headline level is not the largest headline level in the tree.
  7442. So this will actually accept several entries of equal levels as well,
  7443. which is OK for `org-paste-subtree'.
  7444. If optional TXT is given, check this string instead of the current kill."
  7445. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7446. (re (org-get-limited-outline-regexp))
  7447. (^re (concat "^" re))
  7448. (start-level (and kill
  7449. (string-match
  7450. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7451. kill)
  7452. (- (match-end 2) (match-beginning 2) 1)))
  7453. (start (1+ (or (match-beginning 2) -1))))
  7454. (if (not start-level)
  7455. (progn
  7456. nil) ;; does not even start with a heading
  7457. (catch 'exit
  7458. (while (setq start (string-match ^re kill (1+ start)))
  7459. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7460. (throw 'exit nil)))
  7461. t))))
  7462. (defvar org-markers-to-move nil
  7463. "Markers that should be moved with a cut-and-paste operation.
  7464. Those markers are stored together with their positions relative to
  7465. the start of the region.")
  7466. (defun org-save-markers-in-region (beg end)
  7467. "Check markers in region.
  7468. If these markers are between BEG and END, record their position relative
  7469. to BEG, so that after moving the block of text, we can put the markers back
  7470. into place.
  7471. This function gets called just before an entry or tree gets cut from the
  7472. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7473. called immediately, to move the markers with the entries."
  7474. (setq org-markers-to-move nil)
  7475. (when (featurep 'org-clock)
  7476. (org-clock-save-markers-for-cut-and-paste beg end))
  7477. (when (featurep 'org-agenda)
  7478. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7479. (defun org-check-and-save-marker (marker beg end)
  7480. "Check if MARKER is between BEG and END.
  7481. If yes, remember the marker and the distance to BEG."
  7482. (when (and (marker-buffer marker)
  7483. (equal (marker-buffer marker) (current-buffer))
  7484. (>= marker beg) (< marker end))
  7485. (push (cons marker (- marker beg)) org-markers-to-move)))
  7486. (defun org-reinstall-markers-in-region (beg)
  7487. "Move all remembered markers to their position relative to BEG."
  7488. (dolist (x org-markers-to-move)
  7489. (move-marker (car x) (+ beg (cdr x))))
  7490. (setq org-markers-to-move nil))
  7491. (defun org-narrow-to-subtree ()
  7492. "Narrow buffer to the current subtree."
  7493. (interactive)
  7494. (save-excursion
  7495. (save-match-data
  7496. (org-with-limited-levels
  7497. (narrow-to-region
  7498. (progn (org-back-to-heading t) (point))
  7499. (progn (org-end-of-subtree t t)
  7500. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7501. (point)))))))
  7502. (defun org-narrow-to-block ()
  7503. "Narrow buffer to the current block."
  7504. (interactive)
  7505. (let* ((case-fold-search t)
  7506. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7507. "^[ \t]*#\\+end_.*")))
  7508. (if blockp
  7509. (narrow-to-region (car blockp) (cdr blockp))
  7510. (user-error "Not in a block"))))
  7511. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7512. "Clone the task (subtree) at point N times.
  7513. The clones will be inserted as siblings.
  7514. In interactive use, the user will be prompted for the number of
  7515. clones to be produced. If the entry has a timestamp, the user
  7516. will also be prompted for a time shift, which may be a repeater
  7517. as used in time stamps, for example `+3d'. To disable this,
  7518. you can call the function with a universal prefix argument.
  7519. When a valid repeater is given and the entry contains any time
  7520. stamps, the clones will become a sequence in time, with time
  7521. stamps in the subtree shifted for each clone produced. If SHIFT
  7522. is nil or the empty string, time stamps will be left alone. The
  7523. ID property of the original subtree is removed.
  7524. In each clone, all the CLOCK entries will be removed. This
  7525. prevents Org from considering that the clocked times overlap.
  7526. If the original subtree did contain time stamps with a repeater,
  7527. the following will happen:
  7528. - the repeater will be removed in each clone
  7529. - an additional clone will be produced, with the current, unshifted
  7530. date(s) in the entry.
  7531. - the original entry will be placed *after* all the clones, with
  7532. repeater intact.
  7533. - the start days in the repeater in the original entry will be shifted
  7534. to past the last clone.
  7535. In this way you can spell out a number of instances of a repeating task,
  7536. and still retain the repeater to cover future instances of the task.
  7537. As described above, N+1 clones are produced when the original
  7538. subtree has a repeater. Setting N to 0, then, can be used to
  7539. remove the repeater from a subtree and create a shifted clone
  7540. with the original repeater."
  7541. (interactive "nNumber of clones to produce: ")
  7542. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7543. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7544. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7545. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7546. (shift
  7547. (or shift
  7548. (if (and (not (equal current-prefix-arg '(4)))
  7549. (save-excursion
  7550. (goto-char beg)
  7551. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7552. (read-from-minibuffer
  7553. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7554. ""))) ;No time shift
  7555. (doshift
  7556. (and (org-string-nw-p shift)
  7557. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7558. shift)
  7559. (user-error "Invalid shift specification %s" shift)))))
  7560. (goto-char end-of-tree)
  7561. (unless (bolp) (insert "\n"))
  7562. (let* ((end (point))
  7563. (template (buffer-substring beg end))
  7564. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7565. (shift-what (pcase (and doshift (match-string 2 shift))
  7566. (`nil nil)
  7567. ("d" 'day)
  7568. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7569. ("m" 'month)
  7570. ("y" 'year)
  7571. (_ (error "Unsupported time unit"))))
  7572. (nmin 1)
  7573. (nmax n)
  7574. (n-no-remove -1)
  7575. (idprop (org-entry-get nil "ID")))
  7576. (when (and doshift
  7577. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7578. template))
  7579. (delete-region beg end)
  7580. (setq end beg)
  7581. (setq nmin 0)
  7582. (setq nmax (1+ nmax))
  7583. (setq n-no-remove nmax))
  7584. (goto-char end)
  7585. (cl-loop for n from nmin to nmax do
  7586. (insert
  7587. ;; Prepare clone.
  7588. (with-temp-buffer
  7589. (insert template)
  7590. (org-mode)
  7591. (goto-char (point-min))
  7592. (org-show-subtree)
  7593. (and idprop (if org-clone-delete-id
  7594. (org-entry-delete nil "ID")
  7595. (org-id-get-create t)))
  7596. (unless (= n 0)
  7597. (while (re-search-forward org-clock-line-re nil t)
  7598. (delete-region (line-beginning-position)
  7599. (line-beginning-position 2)))
  7600. (goto-char (point-min))
  7601. (while (re-search-forward org-drawer-regexp nil t)
  7602. (org-remove-empty-drawer-at (point))))
  7603. (goto-char (point-min))
  7604. (when doshift
  7605. (while (re-search-forward org-ts-regexp-both nil t)
  7606. (org-timestamp-change (* n shift-n) shift-what))
  7607. (unless (= n n-no-remove)
  7608. (goto-char (point-min))
  7609. (while (re-search-forward org-ts-regexp nil t)
  7610. (save-excursion
  7611. (goto-char (match-beginning 0))
  7612. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7613. (delete-region (match-beginning 1) (match-end 1)))))))
  7614. (buffer-string)))))
  7615. (goto-char beg)))
  7616. ;;; Outline Sorting
  7617. (defun org-sort (&optional with-case)
  7618. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7619. Optional argument WITH-CASE means sort case-sensitively."
  7620. (interactive "P")
  7621. (org-call-with-arg
  7622. (cond ((org-at-table-p) #'org-table-sort-lines)
  7623. ((org-at-item-p) #'org-sort-list)
  7624. (t #'org-sort-entries))
  7625. with-case))
  7626. (defun org-sort-remove-invisible (s)
  7627. "Remove invisible part of links and emphasis markers from string S."
  7628. (remove-text-properties 0 (length s) org-rm-props s)
  7629. (replace-regexp-in-string
  7630. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7631. (replace-regexp-in-string
  7632. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7633. (org-link-display-format s)
  7634. t t) t t))
  7635. (defvar org-priority-regexp) ; defined later in the file
  7636. (defvar org-after-sorting-entries-or-items-hook nil
  7637. "Hook that is run after a bunch of entries or items have been sorted.
  7638. When children are sorted, the cursor is in the parent line when this
  7639. hook gets called. When a region or a plain list is sorted, the cursor
  7640. will be in the first entry of the sorted region/list.")
  7641. (defun org-sort-entries
  7642. (&optional with-case sorting-type getkey-func compare-func property
  7643. interactive?)
  7644. "Sort entries on a certain level of an outline tree.
  7645. If there is an active region, the entries in the region are sorted.
  7646. Else, if the cursor is before the first entry, sort the top-level items.
  7647. Else, the children of the entry at point are sorted.
  7648. Sorting can be alphabetically, numerically, by date/time as given by
  7649. a time stamp, by a property, by priority order, or by a custom function.
  7650. The command prompts for the sorting type unless it has been given to the
  7651. function through the SORTING-TYPE argument, which needs to be a character,
  7652. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7653. the precise meaning of each character:
  7654. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7655. c By creation time, which is assumed to be the first inactive time stamp
  7656. at the beginning of a line.
  7657. d By deadline date/time.
  7658. k By clocking time.
  7659. n Numerically, by converting the beginning of the entry/item to a number.
  7660. o By order of TODO keywords.
  7661. p By priority according to the cookie.
  7662. r By the value of a property.
  7663. s By scheduled date/time.
  7664. t By date/time, either the first active time stamp in the entry, or, if
  7665. none exist, by the first inactive one.
  7666. Capital letters will reverse the sort order.
  7667. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7668. called with point at the beginning of the record. It must return a
  7669. value that is compatible with COMPARE-FUNC, the function used to
  7670. compare entries.
  7671. Comparing entries ignores case by default. However, with an optional argument
  7672. WITH-CASE, the sorting considers case as well.
  7673. Sorting is done against the visible part of the headlines, it ignores hidden
  7674. links.
  7675. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7676. A non-nil value for INTERACTIVE? is used to signal that this
  7677. function is being called interactively."
  7678. (interactive (list current-prefix-arg nil nil nil nil t))
  7679. (let ((case-func (if with-case 'identity 'downcase))
  7680. start beg end stars re re2
  7681. txt what tmp)
  7682. ;; Find beginning and end of region to sort
  7683. (cond
  7684. ((org-region-active-p)
  7685. ;; we will sort the region
  7686. (setq end (region-end)
  7687. what "region")
  7688. (goto-char (region-beginning))
  7689. (unless (org-at-heading-p) (outline-next-heading))
  7690. (setq start (point)))
  7691. ((or (org-at-heading-p)
  7692. (ignore-errors (progn (org-back-to-heading) t)))
  7693. ;; we will sort the children of the current headline
  7694. (org-back-to-heading)
  7695. (setq start (point)
  7696. end (progn (org-end-of-subtree t t)
  7697. (or (bolp) (insert "\n"))
  7698. (when (>= (org-back-over-empty-lines) 1)
  7699. (forward-line 1))
  7700. (point))
  7701. what "children")
  7702. (goto-char start)
  7703. (outline-show-subtree)
  7704. (outline-next-heading))
  7705. (t
  7706. ;; we will sort the top-level entries in this file
  7707. (goto-char (point-min))
  7708. (or (org-at-heading-p) (outline-next-heading))
  7709. (setq start (point))
  7710. (goto-char (point-max))
  7711. (beginning-of-line 1)
  7712. (when (looking-at ".*?\\S-")
  7713. ;; File ends in a non-white line
  7714. (end-of-line 1)
  7715. (insert "\n"))
  7716. (setq end (point-max))
  7717. (setq what "top-level")
  7718. (goto-char start)
  7719. (org-show-all '(headings blocks))))
  7720. (setq beg (point))
  7721. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7722. (looking-at "\\(\\*+\\)")
  7723. (setq stars (match-string 1)
  7724. re (concat "^" (regexp-quote stars) " +")
  7725. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7726. txt (buffer-substring beg end))
  7727. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7728. (when (and (not (equal stars "*")) (string-match re2 txt))
  7729. (user-error "Region to sort contains a level above the first entry"))
  7730. (unless sorting-type
  7731. (message
  7732. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7733. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7734. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7735. what)
  7736. (setq sorting-type (read-char-exclusive)))
  7737. (unless getkey-func
  7738. (and (= (downcase sorting-type) ?f)
  7739. (setq getkey-func
  7740. (or (and interactive?
  7741. (org-read-function
  7742. "Function for extracting keys: "))
  7743. (error "Missing key extractor")))))
  7744. (and (= (downcase sorting-type) ?r)
  7745. (not property)
  7746. (setq property
  7747. (completing-read "Property: "
  7748. (mapcar #'list (org-buffer-property-keys t))
  7749. nil t)))
  7750. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7751. (message "Sorting entries...")
  7752. (save-restriction
  7753. (narrow-to-region start end)
  7754. (let ((restore-clock?
  7755. ;; The clock marker is lost when using `sort-subr'; mark
  7756. ;; the clock with temporary `:org-clock-marker-backup'
  7757. ;; text property.
  7758. (when (and (eq (org-clock-is-active) (current-buffer))
  7759. (<= start (marker-position org-clock-marker))
  7760. (>= end (marker-position org-clock-marker)))
  7761. (org-with-silent-modifications
  7762. (put-text-property (1- org-clock-marker) org-clock-marker
  7763. :org-clock-marker-backup t))
  7764. t))
  7765. (dcst (downcase sorting-type))
  7766. (case-fold-search nil)
  7767. (now (current-time)))
  7768. (org-preserve-local-variables
  7769. (sort-subr
  7770. (/= dcst sorting-type)
  7771. ;; This function moves to the beginning character of the
  7772. ;; "record" to be sorted.
  7773. (lambda nil
  7774. (if (re-search-forward re nil t)
  7775. (goto-char (match-beginning 0))
  7776. (goto-char (point-max))))
  7777. ;; This function moves to the last character of the "record" being
  7778. ;; sorted.
  7779. (lambda nil
  7780. (save-match-data
  7781. (condition-case nil
  7782. (outline-forward-same-level 1)
  7783. (error
  7784. (goto-char (point-max))))))
  7785. ;; This function returns the value that gets sorted against.
  7786. (lambda ()
  7787. (cond
  7788. ((= dcst ?n)
  7789. (string-to-number
  7790. (org-sort-remove-invisible (org-get-heading t t t t))))
  7791. ((= dcst ?a)
  7792. (funcall case-func
  7793. (org-sort-remove-invisible (org-get-heading t t t t))))
  7794. ((= dcst ?k)
  7795. (or (get-text-property (point) :org-clock-minutes) 0))
  7796. ((= dcst ?t)
  7797. (let ((end (save-excursion (outline-next-heading) (point))))
  7798. (if (or (re-search-forward org-ts-regexp end t)
  7799. (re-search-forward org-ts-regexp-both end t))
  7800. (org-time-string-to-seconds (match-string 0))
  7801. (float-time now))))
  7802. ((= dcst ?c)
  7803. (let ((end (save-excursion (outline-next-heading) (point))))
  7804. (if (re-search-forward
  7805. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7806. end t)
  7807. (org-time-string-to-seconds (match-string 0))
  7808. (float-time now))))
  7809. ((= dcst ?s)
  7810. (let ((end (save-excursion (outline-next-heading) (point))))
  7811. (if (re-search-forward org-scheduled-time-regexp end t)
  7812. (org-time-string-to-seconds (match-string 1))
  7813. (float-time now))))
  7814. ((= dcst ?d)
  7815. (let ((end (save-excursion (outline-next-heading) (point))))
  7816. (if (re-search-forward org-deadline-time-regexp end t)
  7817. (org-time-string-to-seconds (match-string 1))
  7818. (float-time now))))
  7819. ((= dcst ?p)
  7820. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7821. (string-to-char (match-string 2))
  7822. org-default-priority))
  7823. ((= dcst ?r)
  7824. (or (org-entry-get nil property) ""))
  7825. ((= dcst ?o)
  7826. (when (looking-at org-complex-heading-regexp)
  7827. (let* ((m (match-string 2))
  7828. (s (if (member m org-done-keywords) '- '+)))
  7829. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7830. ((= dcst ?f)
  7831. (if getkey-func
  7832. (progn
  7833. (setq tmp (funcall getkey-func))
  7834. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7835. tmp)
  7836. (error "Invalid key function `%s'" getkey-func)))
  7837. (t (error "Invalid sorting type `%c'" sorting-type))))
  7838. nil
  7839. (cond
  7840. ((= dcst ?a) 'org-string-collate-lessp)
  7841. ((= dcst ?f)
  7842. (or compare-func
  7843. (and interactive?
  7844. (org-read-function
  7845. (concat "Function for comparing keys "
  7846. "(empty for default `sort-subr' predicate): ")
  7847. 'allow-empty))))
  7848. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7849. (when restore-clock?
  7850. (move-marker org-clock-marker
  7851. (1+ (next-single-property-change
  7852. start :org-clock-marker-backup)))
  7853. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7854. '(:org-clock-marker-backup t)))))
  7855. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7856. (message "Sorting entries...done")))
  7857. (defun org-contextualize-keys (alist contexts)
  7858. "Return valid elements in ALIST depending on CONTEXTS.
  7859. `org-agenda-custom-commands' or `org-capture-templates' are the
  7860. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7861. or `org-capture-templates-contexts' are the associated contexts
  7862. definitions."
  7863. (let ((contexts
  7864. ;; normalize contexts
  7865. (mapcar
  7866. (lambda(c) (cond ((listp (cadr c))
  7867. (list (car c) (car c) (nth 1 c)))
  7868. ((string= "" (cadr c))
  7869. (list (car c) (car c) (nth 2 c)))
  7870. (t c)))
  7871. contexts))
  7872. (a alist) r s)
  7873. ;; loop over all commands or templates
  7874. (dolist (c a)
  7875. (let (vrules repl)
  7876. (cond
  7877. ((not (assoc (car c) contexts))
  7878. (push c r))
  7879. ((and (assoc (car c) contexts)
  7880. (setq vrules (org-contextualize-validate-key
  7881. (car c) contexts)))
  7882. (mapc (lambda (vr)
  7883. (unless (equal (car vr) (cadr vr))
  7884. (setq repl vr)))
  7885. vrules)
  7886. (if (not repl) (push c r)
  7887. (push (cadr repl) s)
  7888. (push
  7889. (cons (car c)
  7890. (cdr (or (assoc (cadr repl) alist)
  7891. (error "Undefined key `%s' as contextual replacement for `%s'"
  7892. (cadr repl) (car c)))))
  7893. r))))))
  7894. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7895. (delq
  7896. nil
  7897. (delete-dups
  7898. (mapcar (lambda (x)
  7899. (let ((tpl (car x)))
  7900. (unless (delq
  7901. nil
  7902. (mapcar (lambda (y)
  7903. (equal y tpl))
  7904. s))
  7905. x)))
  7906. (reverse r))))))
  7907. (defun org-contextualize-validate-key (key contexts)
  7908. "Check CONTEXTS for agenda or capture KEY."
  7909. (let (res)
  7910. (dolist (r contexts)
  7911. (dolist (rr (car (last r)))
  7912. (when
  7913. (and (equal key (car r))
  7914. (if (functionp rr) (funcall rr)
  7915. (or (and (eq (car rr) 'in-file)
  7916. (buffer-file-name)
  7917. (string-match (cdr rr) (buffer-file-name)))
  7918. (and (eq (car rr) 'in-mode)
  7919. (string-match (cdr rr) (symbol-name major-mode)))
  7920. (and (eq (car rr) 'in-buffer)
  7921. (string-match (cdr rr) (buffer-name)))
  7922. (when (and (eq (car rr) 'not-in-file)
  7923. (buffer-file-name))
  7924. (not (string-match (cdr rr) (buffer-file-name))))
  7925. (when (eq (car rr) 'not-in-mode)
  7926. (not (string-match (cdr rr) (symbol-name major-mode))))
  7927. (when (eq (car rr) 'not-in-buffer)
  7928. (not (string-match (cdr rr) (buffer-name)))))))
  7929. (push r res))))
  7930. (delete-dups (delq nil res))))
  7931. ;; Defined to provide a value for defcustom, since there is no
  7932. ;; string-collate-greaterp in Emacs.
  7933. (defun org-string-collate-greaterp (s1 s2)
  7934. "Return non-nil if S1 is greater than S2 in collation order."
  7935. (not (org-string-collate-lessp s1 s2)))
  7936. ;;;###autoload
  7937. (defun org-run-like-in-org-mode (cmd)
  7938. "Run a command, pretending that the current buffer is in Org mode.
  7939. This will temporarily bind local variables that are typically bound in
  7940. Org mode to the values they have in Org mode, and then interactively
  7941. call CMD."
  7942. (org-load-modules-maybe)
  7943. (let (binds)
  7944. (dolist (var (org-get-local-variables))
  7945. (when (or (not (boundp (car var)))
  7946. (eq (symbol-value (car var))
  7947. (default-value (car var))))
  7948. (push (list (car var) `(quote ,(cadr var))) binds)))
  7949. (eval `(let ,binds
  7950. (call-interactively (quote ,cmd))))))
  7951. (defun org-get-category (&optional pos force-refresh)
  7952. "Get the category applying to position POS."
  7953. (save-match-data
  7954. (when force-refresh (org-refresh-category-properties))
  7955. (let ((pos (or pos (point))))
  7956. (or (get-text-property pos 'org-category)
  7957. (progn (org-refresh-category-properties)
  7958. (get-text-property pos 'org-category))))))
  7959. ;;; Refresh properties
  7960. (defun org-refresh-properties (dprop tprop)
  7961. "Refresh buffer text properties.
  7962. DPROP is the drawer property and TPROP is either the
  7963. corresponding text property to set, or an alist with each element
  7964. being a text property (as a symbol) and a function to apply to
  7965. the value of the drawer property."
  7966. (let* ((case-fold-search t)
  7967. (inhibit-read-only t)
  7968. (inherit? (org-property-inherit-p dprop))
  7969. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7970. (global (and inherit? (org--property-global-value dprop nil))))
  7971. (org-with-silent-modifications
  7972. (org-with-point-at 1
  7973. ;; Set global values (e.g., values defined through
  7974. ;; "#+PROPERTY:" keywords) to the whole buffer.
  7975. (when global (put-text-property (point-min) (point-max) tprop global))
  7976. ;; Set local values.
  7977. (while (re-search-forward property-re nil t)
  7978. (when (org-at-property-p)
  7979. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7980. (outline-next-heading))))))
  7981. (defun org-refresh-property (tprop p &optional inherit)
  7982. "Refresh the buffer text property TPROP from the drawer property P.
  7983. The refresh happens only for the current headline, or the whole
  7984. sub-tree if optional argument INHERIT is non-nil."
  7985. (unless (org-before-first-heading-p)
  7986. (save-excursion
  7987. (org-back-to-heading t)
  7988. (let ((start (point))
  7989. (end (save-excursion
  7990. (if inherit (org-end-of-subtree t t)
  7991. (or (outline-next-heading) (point-max))))))
  7992. (if (symbolp tprop)
  7993. ;; TPROP is a text property symbol.
  7994. (put-text-property start end tprop p)
  7995. ;; TPROP is an alist with (property . function) elements.
  7996. (pcase-dolist (`(,prop . ,f) tprop)
  7997. (put-text-property start end prop (funcall f p))))))))
  7998. (defun org-refresh-category-properties ()
  7999. "Refresh category text properties in the buffer."
  8000. (let ((case-fold-search t)
  8001. (inhibit-read-only t)
  8002. (default-category
  8003. (cond ((null org-category)
  8004. (if buffer-file-name
  8005. (file-name-sans-extension
  8006. (file-name-nondirectory buffer-file-name))
  8007. "???"))
  8008. ((symbolp org-category) (symbol-name org-category))
  8009. (t org-category))))
  8010. (org-with-silent-modifications
  8011. (org-with-wide-buffer
  8012. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8013. ;; This is the default category for the buffer. If none is
  8014. ;; found, fall-back to `org-category' or buffer file name.
  8015. (put-text-property
  8016. (point-min) (point-max)
  8017. 'org-category
  8018. (catch 'buffer-category
  8019. (goto-char (point-max))
  8020. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8021. (let ((element (org-element-at-point)))
  8022. (when (eq (org-element-type element) 'keyword)
  8023. (throw 'buffer-category
  8024. (org-element-property :value element)))))
  8025. default-category))
  8026. ;; Set sub-tree specific categories.
  8027. (goto-char (point-min))
  8028. (let ((regexp (org-re-property "CATEGORY")))
  8029. (while (re-search-forward regexp nil t)
  8030. (let ((value (match-string-no-properties 3)))
  8031. (when (org-at-property-p)
  8032. (put-text-property
  8033. (save-excursion (org-back-to-heading t) (point))
  8034. (save-excursion (org-end-of-subtree t t) (point))
  8035. 'org-category
  8036. value)))))))))
  8037. (defun org-refresh-stats-properties ()
  8038. "Refresh stats text properties in the buffer."
  8039. (org-with-silent-modifications
  8040. (org-with-point-at 1
  8041. (let ((regexp (concat org-outline-regexp-bol
  8042. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8043. (while (re-search-forward regexp nil t)
  8044. (let* ((numerator (string-to-number (match-string 1)))
  8045. (denominator (and (match-end 2)
  8046. (string-to-number (match-string 2))))
  8047. (stats (cond ((not denominator) numerator) ;percent
  8048. ((= denominator 0) 0)
  8049. (t (/ (* numerator 100) denominator)))))
  8050. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8051. 'org-stats stats)))))))
  8052. (defun org-refresh-effort-properties ()
  8053. "Refresh effort properties"
  8054. (org-refresh-properties
  8055. org-effort-property
  8056. '((effort . identity)
  8057. (effort-minutes . org-duration-to-minutes))))
  8058. ;;;; Link Stuff
  8059. ;;; Link abbreviations
  8060. (defun org-link-expand-abbrev (link)
  8061. "Apply replacements as defined in `org-link-abbrev-alist'."
  8062. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8063. (let* ((key (match-string 1 link))
  8064. (as (or (assoc key org-link-abbrev-alist-local)
  8065. (assoc key org-link-abbrev-alist)))
  8066. (tag (and (match-end 2) (match-string 3 link)))
  8067. rpl)
  8068. (if (not as)
  8069. link
  8070. (setq rpl (cdr as))
  8071. (cond
  8072. ((symbolp rpl) (funcall rpl tag))
  8073. ((string-match "%(\\([^)]+\\))" rpl)
  8074. (replace-match
  8075. (save-match-data
  8076. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8077. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8078. ((string-match "%h" rpl)
  8079. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8080. (t (concat rpl tag)))))
  8081. link))
  8082. ;;; Storing and inserting links
  8083. (defvar org-insert-link-history nil
  8084. "Minibuffer history for links inserted with `org-insert-link'.")
  8085. (defvar org-stored-links nil
  8086. "Contains the links stored with `org-store-link'.")
  8087. (defvar org-store-link-plist nil
  8088. "Plist with info about the most recently link created with `org-store-link'.")
  8089. (defun org-store-link-functions ()
  8090. "Return a list of functions that are called to create and store a link.
  8091. The functions defined in the :store property of
  8092. `org-link-parameters'.
  8093. Each function will be called in turn until one returns a non-nil
  8094. value. Each function should check if it is responsible for
  8095. creating this link (for example by looking at the major mode).
  8096. If not, it must exit and return nil. If yes, it should return
  8097. a non-nil value after calling `org-store-link-props' with a list
  8098. of properties and values. Special properties are:
  8099. :type The link prefix, like \"http\". This must be given.
  8100. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8101. This is obligatory as well.
  8102. :description Optional default description for the second pair
  8103. of brackets in an Org mode link. The user can still change
  8104. this when inserting this link into an Org mode buffer.
  8105. In addition to these, any additional properties can be specified
  8106. and then used in capture templates."
  8107. (cl-loop for link in org-link-parameters
  8108. with store-func
  8109. do (setq store-func (org-link-get-parameter (car link) :store))
  8110. if store-func
  8111. collect store-func))
  8112. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8113. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8114. ;;;###autoload
  8115. (defun org-store-link (arg &optional interactive?)
  8116. "Store an org-link to the current location.
  8117. \\<org-mode-map>
  8118. This link is added to `org-stored-links' and can later be inserted
  8119. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8120. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8121. A single
  8122. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8123. `org-gnus-prefer-web-links' for links to Usenet articles.
  8124. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8125. skipping storing functions that are not
  8126. part of Org core.
  8127. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8128. prefix ARG forces storing a link for each line in the
  8129. active region.
  8130. Assume the function is called interactively if INTERACTIVE? is
  8131. non-nil."
  8132. (interactive "P\np")
  8133. (org-load-modules-maybe)
  8134. (if (and (equal arg '(64)) (org-region-active-p))
  8135. (save-excursion
  8136. (let ((end (region-end)))
  8137. (goto-char (region-beginning))
  8138. (set-mark (point))
  8139. (while (< (point-at-eol) end)
  8140. (move-end-of-line 1) (activate-mark)
  8141. (let (current-prefix-arg)
  8142. (call-interactively 'org-store-link))
  8143. (move-beginning-of-line 2)
  8144. (set-mark (point)))))
  8145. (setq org-store-link-plist nil)
  8146. (let (link cpltxt desc description search txt custom-id agenda-link)
  8147. (cond
  8148. ;; Store a link using an external link type, if any function is
  8149. ;; available. If more than one can generate a link from current
  8150. ;; location, ask which one to use.
  8151. ((and (not (equal arg '(16)))
  8152. (let ((results-alist nil))
  8153. (dolist (f (org-store-link-functions))
  8154. (when (funcall f)
  8155. ;; XXX: return value is not link's plist, so we
  8156. ;; store the new value before it is modified. It
  8157. ;; would be cleaner to ask store link functions to
  8158. ;; return the plist instead.
  8159. (push (cons f (copy-sequence org-store-link-plist))
  8160. results-alist)))
  8161. (pcase results-alist
  8162. (`nil nil)
  8163. (`((,_ . ,_)) t) ;single choice: nothing to do
  8164. (`((,name . ,_) . ,_)
  8165. ;; Reinstate link plist associated to the chosen
  8166. ;; function.
  8167. (apply #'org-store-link-props
  8168. (cdr (assoc-string
  8169. (completing-read
  8170. "Which function for creating the link? "
  8171. (mapcar #'car results-alist)
  8172. nil t (symbol-name name))
  8173. results-alist)))
  8174. t))))
  8175. (setq link (plist-get org-store-link-plist :link))
  8176. (setq desc (or (plist-get org-store-link-plist :description)
  8177. link)))
  8178. ;; Store a link from a source code buffer.
  8179. ((org-src-edit-buffer-p)
  8180. (let ((coderef-format (org-src-coderef-format)))
  8181. (cond ((org-match-line (org-src-coderef-regexp coderef-format))
  8182. (setq link (format "(%s)" (match-string-no-properties 3))))
  8183. (interactive?
  8184. (let ((label (read-string "Code line label: ")))
  8185. (end-of-line)
  8186. (setq link (format coderef-format label))
  8187. (let ((gc (- 79 (length link))))
  8188. (if (< (current-column) gc)
  8189. (org-move-to-column gc t)
  8190. (insert " ")))
  8191. (insert link)
  8192. (setq link (concat "(" label ")"))
  8193. (setq desc nil)))
  8194. (t (setq link nil)))))
  8195. ;; We are in the agenda, link to referenced location
  8196. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8197. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8198. (get-text-property (point) 'org-marker))))
  8199. (when m
  8200. (org-with-point-at m
  8201. (setq agenda-link (org-store-link nil interactive?))))))
  8202. ((eq major-mode 'calendar-mode)
  8203. (let ((cd (calendar-cursor-to-date)))
  8204. (setq link
  8205. (format-time-string
  8206. (car org-time-stamp-formats)
  8207. (apply 'encode-time
  8208. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8209. nil nil nil))))
  8210. (org-store-link-props :type "calendar" :date cd)))
  8211. ((eq major-mode 'help-mode)
  8212. (setq link (concat "help:" (save-excursion
  8213. (goto-char (point-min))
  8214. (looking-at "^[^ ]+")
  8215. (match-string 0))))
  8216. (org-store-link-props :type "help"))
  8217. ((eq major-mode 'w3-mode)
  8218. (setq cpltxt (if (and (buffer-name)
  8219. (not (string-match "Untitled" (buffer-name))))
  8220. (buffer-name)
  8221. (url-view-url t))
  8222. link (url-view-url t))
  8223. (org-store-link-props :type "w3" :url (url-view-url t)))
  8224. ((eq major-mode 'image-mode)
  8225. (setq cpltxt (concat "file:"
  8226. (abbreviate-file-name buffer-file-name))
  8227. link cpltxt)
  8228. (org-store-link-props :type "image" :file buffer-file-name))
  8229. ;; In dired, store a link to the file of the current line
  8230. ((derived-mode-p 'dired-mode)
  8231. (let ((file (dired-get-filename nil t)))
  8232. (setq file (if file
  8233. (abbreviate-file-name
  8234. (expand-file-name (dired-get-filename nil t)))
  8235. ;; otherwise, no file so use current directory.
  8236. default-directory))
  8237. (setq cpltxt (concat "file:" file)
  8238. link cpltxt)))
  8239. ((setq search (run-hook-with-args-until-success
  8240. 'org-create-file-search-functions))
  8241. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8242. "::" search))
  8243. (setq cpltxt (or description link)))
  8244. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8245. (org-with-limited-levels
  8246. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8247. (cond
  8248. ;; Store a link using the target at point
  8249. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8250. (setq cpltxt
  8251. (concat "file:"
  8252. (abbreviate-file-name
  8253. (buffer-file-name (buffer-base-buffer)))
  8254. "::" (match-string 1))
  8255. link cpltxt))
  8256. ((and (featurep 'org-id)
  8257. (or (eq org-id-link-to-org-use-id t)
  8258. (and interactive?
  8259. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8260. (and (eq org-id-link-to-org-use-id
  8261. 'create-if-interactive-and-no-custom-id)
  8262. (not custom-id))))
  8263. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8264. ;; Store a link using the ID at point
  8265. (setq link (condition-case nil
  8266. (prog1 (org-id-store-link)
  8267. (setq desc (or (plist-get org-store-link-plist
  8268. :description)
  8269. "")))
  8270. (error
  8271. ;; Probably before first headline, link only to file
  8272. (concat "file:"
  8273. (abbreviate-file-name
  8274. (buffer-file-name (buffer-base-buffer))))))))
  8275. (t
  8276. ;; Just link to current headline
  8277. (setq cpltxt (concat "file:"
  8278. (abbreviate-file-name
  8279. (buffer-file-name (buffer-base-buffer)))))
  8280. ;; Add a context search string
  8281. (when (org-xor org-context-in-file-links
  8282. (equal arg '(4)))
  8283. (let* ((element (org-element-at-point))
  8284. (name (org-element-property :name element)))
  8285. (setq txt (cond
  8286. ((org-at-heading-p) nil)
  8287. (name)
  8288. ((org-region-active-p)
  8289. (buffer-substring (region-beginning) (region-end)))))
  8290. (when (or (null txt) (string-match "\\S-" txt))
  8291. (setq cpltxt
  8292. (concat cpltxt "::"
  8293. (condition-case nil
  8294. (org-make-org-heading-search-string txt)
  8295. (error "")))
  8296. desc (or name
  8297. (nth 4 (ignore-errors (org-heading-components)))
  8298. "NONE")))))
  8299. (when (string-match "::\\'" cpltxt)
  8300. (setq cpltxt (substring cpltxt 0 -2)))
  8301. (setq link cpltxt)))))
  8302. ((buffer-file-name (buffer-base-buffer))
  8303. ;; Just link to this file here.
  8304. (setq cpltxt (concat "file:"
  8305. (abbreviate-file-name
  8306. (buffer-file-name (buffer-base-buffer)))))
  8307. ;; Add a context string.
  8308. (when (org-xor org-context-in-file-links
  8309. (equal arg '(4)))
  8310. (setq txt (if (org-region-active-p)
  8311. (buffer-substring (region-beginning) (region-end))
  8312. (buffer-substring (point-at-bol) (point-at-eol))))
  8313. ;; Only use search option if there is some text.
  8314. (when (string-match "\\S-" txt)
  8315. (setq cpltxt
  8316. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8317. desc "NONE")))
  8318. (setq link cpltxt))
  8319. (interactive?
  8320. (user-error "No method for storing a link from this buffer"))
  8321. (t (setq link nil)))
  8322. ;; We're done setting link and desc, clean up
  8323. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8324. (setq link (or link cpltxt)
  8325. desc (or desc cpltxt))
  8326. (cond ((not desc))
  8327. ((equal desc "NONE") (setq desc nil))
  8328. (t (setq desc
  8329. (replace-regexp-in-string
  8330. org-bracket-link-analytic-regexp
  8331. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8332. desc))))
  8333. ;; Return the link
  8334. (if (not (and interactive? link))
  8335. (or agenda-link (and link (org-make-link-string link desc)))
  8336. (push (list link desc) org-stored-links)
  8337. (message "Stored: %s" (or desc link))
  8338. (when custom-id
  8339. (setq link (concat "file:" (abbreviate-file-name
  8340. (buffer-file-name)) "::#" custom-id))
  8341. (push (list link desc) org-stored-links))
  8342. (car org-stored-links)))))
  8343. (defun org-store-link-props (&rest plist)
  8344. "Store link properties.
  8345. The properties are pre-processed by extracting names, addresses
  8346. and dates."
  8347. (let ((x (plist-get plist :from)))
  8348. (when x
  8349. (let ((adr (mail-extract-address-components x)))
  8350. (setq plist (plist-put plist :fromname (car adr)))
  8351. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8352. (let ((x (plist-get plist :to)))
  8353. (when x
  8354. (let ((adr (mail-extract-address-components x)))
  8355. (setq plist (plist-put plist :toname (car adr)))
  8356. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8357. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8358. (when x
  8359. (setq plist (plist-put plist :date-timestamp
  8360. (format-time-string
  8361. (org-time-stamp-format t) x)))
  8362. (setq plist (plist-put plist :date-timestamp-inactive
  8363. (format-time-string
  8364. (org-time-stamp-format t t) x)))))
  8365. (let ((from (plist-get plist :from))
  8366. (to (plist-get plist :to)))
  8367. (when (and from to org-from-is-user-regexp)
  8368. (setq plist
  8369. (plist-put plist :fromto
  8370. (if (string-match org-from-is-user-regexp from)
  8371. (concat "to %t")
  8372. (concat "from %f"))))))
  8373. (setq org-store-link-plist plist))
  8374. (defun org-add-link-props (&rest plist)
  8375. "Add these properties to the link property list."
  8376. (let (key value)
  8377. (while plist
  8378. (setq key (pop plist) value (pop plist))
  8379. (setq org-store-link-plist
  8380. (plist-put org-store-link-plist key value)))))
  8381. (defun org-email-link-description (&optional fmt)
  8382. "Return the description part of an email link.
  8383. This takes information from `org-store-link-plist' and formats it
  8384. according to FMT (default from `org-email-link-description-format')."
  8385. (setq fmt (or fmt org-email-link-description-format))
  8386. (let* ((p org-store-link-plist)
  8387. (to (plist-get p :toaddress))
  8388. (from (plist-get p :fromaddress))
  8389. (table
  8390. (list
  8391. (cons "%c" (plist-get p :fromto))
  8392. (cons "%F" (plist-get p :from))
  8393. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8394. (cons "%T" (plist-get p :to))
  8395. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8396. (cons "%s" (plist-get p :subject))
  8397. (cons "%d" (plist-get p :date))
  8398. (cons "%m" (plist-get p :message-id)))))
  8399. (when (string-match "%c" fmt)
  8400. ;; Check if the user wrote this message
  8401. (if (and org-from-is-user-regexp from to
  8402. (save-match-data (string-match org-from-is-user-regexp from)))
  8403. (setq fmt (replace-match "to %t" t t fmt))
  8404. (setq fmt (replace-match "from %f" t t fmt))))
  8405. (org-replace-escapes fmt table)))
  8406. (defun org-make-org-heading-search-string (&optional string)
  8407. "Make search string for the current headline or STRING."
  8408. (let ((s (or string
  8409. (and (derived-mode-p 'org-mode)
  8410. (save-excursion
  8411. (org-back-to-heading t)
  8412. (org-element-property :raw-value (org-element-at-point))))))
  8413. (lines org-context-in-file-links))
  8414. (unless string (setq s (concat "*" s))) ;Add * for headlines
  8415. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8416. (when (and string (integerp lines) (> lines 0))
  8417. (let ((slines (org-split-string s "\n")))
  8418. (when (< lines (length slines))
  8419. (setq s (mapconcat
  8420. 'identity
  8421. (reverse (nthcdr (- (length slines) lines)
  8422. (reverse slines))) "\n")))))
  8423. (mapconcat #'identity (split-string s) " ")))
  8424. (defconst org-link-escape-chars
  8425. ;;%20 %5B %5D %25
  8426. '(?\s ?\[ ?\] ?%)
  8427. "List of characters that should be escaped in a link when stored to Org.
  8428. This is the list that is used for internal purposes.")
  8429. (defun org-make-link-string (link &optional description)
  8430. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8431. (unless (org-string-nw-p link) (error "Empty link"))
  8432. (let ((uri (cond ((string-match org-link-types-re link)
  8433. (concat (match-string 1 link)
  8434. (org-link-escape (substring link (match-end 1)))))
  8435. ((or (file-name-absolute-p link)
  8436. (string-match-p "\\`\\.\\.?/" link))
  8437. (org-link-escape link))
  8438. ;; For readability, do not encode space characters
  8439. ;; in fuzzy links.
  8440. (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
  8441. (description
  8442. (and (org-string-nw-p description)
  8443. ;; Remove brackets from description, as they are fatal.
  8444. (replace-regexp-in-string
  8445. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8446. (org-trim description)))))
  8447. (format "[[%s]%s]"
  8448. uri
  8449. (if description (format "[%s]" description) ""))))
  8450. (defun org-link-escape (text &optional table merge)
  8451. "Return percent escaped representation of TEXT.
  8452. TEXT is a string with the text to escape.
  8453. Optional argument TABLE is a list with characters that should be
  8454. escaped. When nil, `org-link-escape-chars' is used.
  8455. If optional argument MERGE is set, merge TABLE into
  8456. `org-link-escape-chars'."
  8457. (let ((characters-to-encode
  8458. (cond ((null table) org-link-escape-chars)
  8459. (merge (append org-link-escape-chars table))
  8460. (t table))))
  8461. (mapconcat
  8462. (lambda (c)
  8463. (if (or (memq c characters-to-encode)
  8464. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8465. (mapconcat (lambda (e) (format "%%%.2X" e))
  8466. (or (encode-coding-char c 'utf-8)
  8467. (error "Unable to percent escape character: %c" c))
  8468. "")
  8469. (char-to-string c)))
  8470. text "")))
  8471. (defun org-link-unescape (str)
  8472. "Unhex hexified Unicode parts in string STR.
  8473. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  8474. reciprocal of `org-link-escape', which see."
  8475. (if (org-string-nw-p str)
  8476. (replace-regexp-in-string
  8477. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  8478. str))
  8479. (defun org-link-unescape-compound (hex)
  8480. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  8481. Note: this function also decodes single byte encodings like
  8482. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  8483. (save-match-data
  8484. (let* ((bytes (cdr (split-string hex "%")))
  8485. (ret "")
  8486. (eat 0)
  8487. (sum 0))
  8488. (while bytes
  8489. (let* ((val (string-to-number (pop bytes) 16))
  8490. (shift-xor
  8491. (if (= 0 eat)
  8492. (cond
  8493. ((>= val 252) (cons 6 252))
  8494. ((>= val 248) (cons 5 248))
  8495. ((>= val 240) (cons 4 240))
  8496. ((>= val 224) (cons 3 224))
  8497. ((>= val 192) (cons 2 192))
  8498. (t (cons 0 0)))
  8499. (cons 6 128))))
  8500. (when (>= val 192) (setq eat (car shift-xor)))
  8501. (setq val (logxor val (cdr shift-xor)))
  8502. (setq sum (+ (lsh sum (car shift-xor)) val))
  8503. (when (> eat 0) (setq eat (- eat 1)))
  8504. (cond
  8505. ((= 0 eat) ;multi byte
  8506. (setq ret (concat ret (char-to-string sum)))
  8507. (setq sum 0))
  8508. ((not bytes) ; single byte(s)
  8509. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  8510. ret)))
  8511. (defun org-link-unescape-single-byte-sequence (hex)
  8512. "Unhexify hex-encoded single byte character sequences."
  8513. (mapconcat (lambda (byte)
  8514. (char-to-string (string-to-number byte 16)))
  8515. (cdr (split-string hex "%")) ""))
  8516. (defun org-fixup-message-id-for-http (s)
  8517. "Replace special characters in a message id, so it can be used in an http query."
  8518. (when (string-match "%" s)
  8519. (setq s (mapconcat (lambda (c)
  8520. (if (eq c ?%)
  8521. "%25"
  8522. (char-to-string c)))
  8523. s "")))
  8524. (while (string-match "<" s)
  8525. (setq s (replace-match "%3C" t t s)))
  8526. (while (string-match ">" s)
  8527. (setq s (replace-match "%3E" t t s)))
  8528. (while (string-match "@" s)
  8529. (setq s (replace-match "%40" t t s)))
  8530. s)
  8531. (defun org-link-prettify (link)
  8532. "Return a human-readable representation of LINK.
  8533. The car of LINK must be a raw link.
  8534. The cdr of LINK must be either a link description or nil."
  8535. (let ((desc (or (cadr link) "<no description>")))
  8536. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  8537. "<" (car link) ">")))
  8538. ;;;###autoload
  8539. (defun org-insert-link-global ()
  8540. "Insert a link like Org mode does.
  8541. This command can be called in any mode to insert a link in Org syntax."
  8542. (interactive)
  8543. (org-load-modules-maybe)
  8544. (org-run-like-in-org-mode 'org-insert-link))
  8545. (defun org-insert-all-links (arg &optional pre post)
  8546. "Insert all links in `org-stored-links'.
  8547. When a universal prefix, do not delete the links from `org-stored-links'.
  8548. When `ARG' is a number, insert the last N link(s).
  8549. `PRE' and `POST' are optional arguments to define a string to
  8550. prepend or to append."
  8551. (interactive "P")
  8552. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  8553. (links (copy-sequence org-stored-links))
  8554. (pr (or pre "- "))
  8555. (po (or post "\n"))
  8556. (cnt 1) l)
  8557. (if (null org-stored-links)
  8558. (message "No link to insert")
  8559. (while (and (or (listp arg) (>= arg cnt))
  8560. (setq l (if (listp arg)
  8561. (pop links)
  8562. (pop org-stored-links))))
  8563. (setq cnt (1+ cnt))
  8564. (insert pr)
  8565. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  8566. (insert po)))))
  8567. (defun org-insert-last-stored-link (arg)
  8568. "Insert the last link stored in `org-stored-links'."
  8569. (interactive "p")
  8570. (org-insert-all-links arg "" "\n"))
  8571. (defun org-link-fontify-links-to-this-file ()
  8572. "Fontify links to the current file in `org-stored-links'."
  8573. (let ((f (buffer-file-name)) a b)
  8574. (setq a (mapcar (lambda(l)
  8575. (let ((ll (car l)))
  8576. (when (and (string-match "^file:\\(.+\\)::" ll)
  8577. (equal f (expand-file-name (match-string 1 ll))))
  8578. ll)))
  8579. org-stored-links))
  8580. (when (featurep 'org-id)
  8581. (setq b (mapcar (lambda(l)
  8582. (let ((ll (car l)))
  8583. (when (and (string-match "^id:\\(.+\\)$" ll)
  8584. (equal f (expand-file-name
  8585. (or (org-id-find-id-file
  8586. (match-string 1 ll)) ""))))
  8587. ll)))
  8588. org-stored-links)))
  8589. (mapcar (lambda(l)
  8590. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  8591. (delq nil (append a b)))))
  8592. (defvar org--links-history nil)
  8593. (defun org-insert-link (&optional complete-file link-location default-description)
  8594. "Insert a link. At the prompt, enter the link.
  8595. Completion can be used to insert any of the link protocol prefixes in use.
  8596. The history can be used to select a link previously stored with
  8597. `org-store-link'. When the empty string is entered (i.e. if you just
  8598. press `RET' at the prompt), the link defaults to the most recently
  8599. stored link. As `SPC' triggers completion in the minibuffer, you need to
  8600. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  8601. You will also be prompted for a description, and if one is given, it will
  8602. be displayed in the buffer instead of the link.
  8603. If there is already a link at point, this command will allow you to edit
  8604. link and description parts.
  8605. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  8606. file name can be
  8607. selected using completion. The path to the file will be relative to the
  8608. current directory if the file is in the current directory or a subdirectory.
  8609. Otherwise, the link will be the absolute path as completed in the minibuffer
  8610. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  8611. option `org-link-file-path-type'.
  8612. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  8613. absolute path even if the file is in
  8614. the current directory or below.
  8615. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8616. prefix negates `org-keep-stored-link-after-insertion'.
  8617. If the LINK-LOCATION parameter is non-nil, this value will be used as
  8618. the link location instead of reading one interactively.
  8619. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  8620. be used as the default description. Otherwise, if
  8621. `org-make-link-description-function' is non-nil, this function
  8622. will be called with the link target, and the result will be the
  8623. default link description. When called non-interactivily, don't
  8624. allow to edit the default description."
  8625. (interactive "P")
  8626. (let* ((wcf (current-window-configuration))
  8627. (origbuf (current-buffer))
  8628. (region (when (org-region-active-p)
  8629. (buffer-substring (region-beginning) (region-end))))
  8630. (remove (and region (list (region-beginning) (region-end))))
  8631. (desc region)
  8632. (link link-location)
  8633. (abbrevs org-link-abbrev-alist-local)
  8634. entry all-prefixes auto-desc)
  8635. (cond
  8636. (link-location) ; specified by arg, just use it.
  8637. ((org-in-regexp org-bracket-link-regexp 1)
  8638. ;; We do have a link at point, and we are going to edit it.
  8639. (setq remove (list (match-beginning 0) (match-end 0)))
  8640. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  8641. (setq link (read-string "Link: "
  8642. (org-link-unescape
  8643. (match-string-no-properties 1)))))
  8644. ((or (org-in-regexp org-angle-link-re)
  8645. (org-in-regexp org-plain-link-re))
  8646. ;; Convert to bracket link
  8647. (setq remove (list (match-beginning 0) (match-end 0))
  8648. link (read-string "Link: "
  8649. (org-unbracket-string "<" ">" (match-string 0)))))
  8650. ((member complete-file '((4) (16)))
  8651. ;; Completing read for file names.
  8652. (setq link (org-file-complete-link complete-file)))
  8653. (t
  8654. ;; Read link, with completion for stored links.
  8655. (org-link-fontify-links-to-this-file)
  8656. (org-switch-to-buffer-other-window "*Org Links*")
  8657. (with-current-buffer "*Org Links*"
  8658. (erase-buffer)
  8659. (insert "Insert a link.
  8660. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  8661. (when org-stored-links
  8662. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  8663. (insert (mapconcat 'org-link-prettify
  8664. (reverse org-stored-links) "\n")))
  8665. (goto-char (point-min)))
  8666. (let ((cw (selected-window)))
  8667. (select-window (get-buffer-window "*Org Links*" 'visible))
  8668. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  8669. (unless (pos-visible-in-window-p (point-max))
  8670. (org-fit-window-to-buffer))
  8671. (and (window-live-p cw) (select-window cw)))
  8672. (setq all-prefixes (append (mapcar 'car abbrevs)
  8673. (mapcar 'car org-link-abbrev-alist)
  8674. (org-link-types)))
  8675. (unwind-protect
  8676. ;; Fake a link history, containing the stored links.
  8677. (let ((org--links-history
  8678. (append (mapcar #'car org-stored-links)
  8679. org-insert-link-history)))
  8680. (setq link
  8681. (org-completing-read
  8682. "Link: "
  8683. (append
  8684. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  8685. (mapcar #'car org-stored-links))
  8686. nil nil nil
  8687. 'org--links-history
  8688. (caar org-stored-links)))
  8689. (unless (org-string-nw-p link) (user-error "No link selected"))
  8690. (dolist (l org-stored-links)
  8691. (when (equal link (cadr l))
  8692. (setq link (car l))
  8693. (setq auto-desc t)))
  8694. (when (or (member link all-prefixes)
  8695. (and (equal ":" (substring link -1))
  8696. (member (substring link 0 -1) all-prefixes)
  8697. (setq link (substring link 0 -1))))
  8698. (setq link (with-current-buffer origbuf
  8699. (org-link-try-special-completion link)))))
  8700. (set-window-configuration wcf)
  8701. (kill-buffer "*Org Links*"))
  8702. (setq entry (assoc link org-stored-links))
  8703. (or entry (push link org-insert-link-history))
  8704. (setq desc (or desc (nth 1 entry)))))
  8705. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  8706. (not org-keep-stored-link-after-insertion))
  8707. (setq org-stored-links (delq (assoc link org-stored-links)
  8708. org-stored-links)))
  8709. (when (and (string-match org-plain-link-re link)
  8710. (not (string-match org-ts-regexp link)))
  8711. ;; URL-like link, normalize the use of angular brackets.
  8712. (setq link (org-unbracket-string "<" ">" link)))
  8713. ;; Check if we are linking to the current file with a search
  8714. ;; option If yes, simplify the link by using only the search
  8715. ;; option.
  8716. (when (and buffer-file-name
  8717. (let ((case-fold-search nil))
  8718. (string-match "\\`file:\\(.+?\\)::" link)))
  8719. (let ((path (match-string-no-properties 1 link))
  8720. (search (substring-no-properties link (match-end 0))))
  8721. (save-match-data
  8722. (when (equal (file-truename buffer-file-name) (file-truename path))
  8723. ;; We are linking to this same file, with a search option
  8724. (setq link search)))))
  8725. ;; Check if we can/should use a relative path. If yes, simplify
  8726. ;; the link.
  8727. (let ((case-fold-search nil))
  8728. (when (string-match "\\`\\(file\\|docview\\):" link)
  8729. (let* ((type (match-string-no-properties 0 link))
  8730. (path-start (match-end 0))
  8731. (search (and (string-match "::\\(.*\\)\\'" link)
  8732. (match-string 1 link)))
  8733. (path
  8734. (if search
  8735. (substring-no-properties
  8736. link path-start (match-beginning 0))
  8737. (substring-no-properties link (match-end 0))))
  8738. (origpath path))
  8739. (cond
  8740. ((or (eq org-link-file-path-type 'absolute)
  8741. (equal complete-file '(16)))
  8742. (setq path (abbreviate-file-name (expand-file-name path))))
  8743. ((eq org-link-file-path-type 'noabbrev)
  8744. (setq path (expand-file-name path)))
  8745. ((eq org-link-file-path-type 'relative)
  8746. (setq path (file-relative-name path)))
  8747. (t
  8748. (save-match-data
  8749. (if (string-match (concat "^" (regexp-quote
  8750. (expand-file-name
  8751. (file-name-as-directory
  8752. default-directory))))
  8753. (expand-file-name path))
  8754. ;; We are linking a file with relative path name.
  8755. (setq path (substring (expand-file-name path)
  8756. (match-end 0)))
  8757. (setq path (abbreviate-file-name (expand-file-name path)))))))
  8758. (setq link (concat type path (and search (concat "::" search))))
  8759. (when (equal desc origpath)
  8760. (setq desc path)))))
  8761. (unless auto-desc
  8762. (let ((initial-input
  8763. (cond
  8764. (default-description)
  8765. ((not org-make-link-description-function) desc)
  8766. (t (condition-case nil
  8767. (funcall org-make-link-description-function link desc)
  8768. (error
  8769. (message "Can't get link description from `%s'"
  8770. (symbol-name org-make-link-description-function))
  8771. (sit-for 2)
  8772. nil))))))
  8773. (setq desc (if (called-interactively-p 'any)
  8774. (read-string "Description: " initial-input)
  8775. initial-input))))
  8776. (unless (string-match "\\S-" desc) (setq desc nil))
  8777. (when remove (apply 'delete-region remove))
  8778. (insert (org-make-link-string link desc))
  8779. ;; Redisplay so as the new link has proper invisible characters.
  8780. (sit-for 0)))
  8781. (defun org-link-try-special-completion (type)
  8782. "If there is completion support for link type TYPE, offer it."
  8783. (let ((fun (org-link-get-parameter type :complete)))
  8784. (if (functionp fun)
  8785. (funcall fun)
  8786. (read-string "Link (no completion support): " (concat type ":")))))
  8787. (defun org-file-complete-link (&optional arg)
  8788. "Create a file link using completion."
  8789. (let ((file (read-file-name "File: "))
  8790. (pwd (file-name-as-directory (expand-file-name ".")))
  8791. (pwd1 (file-name-as-directory (abbreviate-file-name
  8792. (expand-file-name ".")))))
  8793. (cond ((equal arg '(16))
  8794. (concat "file:"
  8795. (abbreviate-file-name (expand-file-name file))))
  8796. ((string-match
  8797. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  8798. (concat "file:" (match-string 1 file)))
  8799. ((string-match
  8800. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  8801. (expand-file-name file))
  8802. (concat "file:"
  8803. (match-string 1 (expand-file-name file))))
  8804. (t (concat "file:" file)))))
  8805. ;;; Opening/following a link
  8806. (defvar org-link-search-failed nil)
  8807. (defvar org-open-link-functions nil
  8808. "Hook for functions finding a plain text link.
  8809. These functions must take a single argument, the link content.
  8810. They will be called for links that look like [[link text][description]]
  8811. when LINK TEXT does not have a protocol like \"http:\" and does not look
  8812. like a filename (e.g. \"./blue.png\").
  8813. These functions will be called *before* Org attempts to resolve the
  8814. link by doing text searches in the current buffer - so if you want a
  8815. link \"[[target]]\" to still find \"<<target>>\", your function should
  8816. handle this as a special case.
  8817. When the function does handle the link, it must return a non-nil value.
  8818. If it decides that it is not responsible for this link, it must return
  8819. nil to indicate that that Org can continue with other options like
  8820. exact and fuzzy text search.")
  8821. (defun org-next-link (&optional search-backward)
  8822. "Move forward to the next link.
  8823. If the link is in hidden text, expose it."
  8824. (interactive "P")
  8825. (when (and org-link-search-failed (eq this-command last-command))
  8826. (goto-char (point-min))
  8827. (message "Link search wrapped back to beginning of buffer"))
  8828. (setq org-link-search-failed nil)
  8829. (let* ((pos (point))
  8830. (ct (org-context))
  8831. (a (assq :link ct))
  8832. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  8833. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  8834. ((looking-at org-any-link-re)
  8835. ;; Don't stay stuck at link without an org-link face
  8836. (forward-char (if search-backward -1 1))))
  8837. (if (funcall srch-fun org-any-link-re nil t)
  8838. (progn
  8839. (goto-char (match-beginning 0))
  8840. (when (org-invisible-p) (org-show-context)))
  8841. (goto-char pos)
  8842. (setq org-link-search-failed t)
  8843. (message "No further link found"))))
  8844. (defun org-previous-link ()
  8845. "Move backward to the previous link.
  8846. If the link is in hidden text, expose it."
  8847. (interactive)
  8848. (funcall 'org-next-link t))
  8849. (defun org-translate-link (s)
  8850. "Translate a link string if a translation function has been defined."
  8851. (with-temp-buffer
  8852. (insert (org-trim s))
  8853. (org-trim (org-element-interpret-data (org-element-context)))))
  8854. (defun org-translate-link-from-planner (type path)
  8855. "Translate a link from Emacs Planner syntax so that Org can follow it.
  8856. This is still an experimental function, your mileage may vary."
  8857. (cond
  8858. ((member type '("http" "https" "news" "ftp"))
  8859. ;; standard Internet links are the same.
  8860. nil)
  8861. ((and (equal type "irc") (string-match "^//" path))
  8862. ;; Planner has two / at the beginning of an irc link, we have 1.
  8863. ;; We should have zero, actually....
  8864. (setq path (substring path 1)))
  8865. ((and (equal type "lisp") (string-match "^/" path))
  8866. ;; Planner has a slash, we do not.
  8867. (setq type "elisp" path (substring path 1)))
  8868. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  8869. ;; A typical message link. Planner has the id after the final slash,
  8870. ;; we separate it with a hash mark
  8871. (setq path (concat (match-string 1 path) "#"
  8872. (org-unbracket-string "<" ">" (match-string 2 path))))))
  8873. (cons type path))
  8874. (defun org-find-file-at-mouse (ev)
  8875. "Open file link or URL at mouse."
  8876. (interactive "e")
  8877. (mouse-set-point ev)
  8878. (org-open-at-point 'in-emacs))
  8879. (defun org-open-at-mouse (ev)
  8880. "Open file link or URL at mouse.
  8881. See the docstring of `org-open-file' for details."
  8882. (interactive "e")
  8883. (mouse-set-point ev)
  8884. (when (eq major-mode 'org-agenda-mode)
  8885. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  8886. (org-open-at-point))
  8887. (defvar org-window-config-before-follow-link nil
  8888. "The window configuration before following a link.
  8889. This is saved in case the need arises to restore it.")
  8890. ;;;###autoload
  8891. (defun org-open-at-point-global ()
  8892. "Follow a link or time-stamp like Org mode does.
  8893. This command can be called in any mode to follow an external link
  8894. or a time-stamp that has Org mode syntax. Its behavior is
  8895. undefined when called on internal links (e.g., fuzzy links).
  8896. Raise an error when there is nothing to follow. "
  8897. (interactive)
  8898. (cond ((org-in-regexp org-any-link-re)
  8899. (org-open-link-from-string (match-string-no-properties 0)))
  8900. ((or (org-in-regexp org-ts-regexp-both nil t)
  8901. (org-in-regexp org-tsr-regexp-both nil t))
  8902. (org-follow-timestamp-link))
  8903. (t (user-error "No link found"))))
  8904. ;;;###autoload
  8905. (defun org-open-link-from-string (s &optional arg reference-buffer)
  8906. "Open a link in the string S, as if it was in Org mode."
  8907. (interactive "sLink: \nP")
  8908. (let ((reference-buffer (or reference-buffer (current-buffer))))
  8909. (with-temp-buffer
  8910. (let ((org-inhibit-startup (not reference-buffer)))
  8911. (org-mode)
  8912. (insert s)
  8913. (goto-char (point-min))
  8914. (when reference-buffer
  8915. (setq org-link-abbrev-alist-local
  8916. (with-current-buffer reference-buffer
  8917. org-link-abbrev-alist-local)))
  8918. (org-open-at-point arg reference-buffer)))))
  8919. (defvar org-open-at-point-functions nil
  8920. "Hook that is run when following a link at point.
  8921. Functions in this hook must return t if they identify and follow
  8922. a link at point. If they don't find anything interesting at point,
  8923. they must return nil.")
  8924. (defvar org-link-search-inhibit-query nil)
  8925. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  8926. (defun org--open-doi-link (path)
  8927. "Open a \"doi\" type link.
  8928. PATH is a the path to search for, as a string."
  8929. (browse-url (url-encode-url (concat org-doi-server-url path))))
  8930. (defun org--open-elisp-link (path)
  8931. "Open a \"elisp\" type link.
  8932. PATH is the sexp to evaluate, as a string."
  8933. (let ((cmd path))
  8934. (if (or (and (org-string-nw-p
  8935. org-confirm-elisp-link-not-regexp)
  8936. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  8937. (not org-confirm-elisp-link-function)
  8938. (funcall org-confirm-elisp-link-function
  8939. (format "Execute \"%s\" as elisp? "
  8940. (org-add-props cmd nil 'face 'org-warning))))
  8941. (message "%s => %s" cmd
  8942. (if (eq (string-to-char cmd) ?\()
  8943. (eval (read cmd))
  8944. (call-interactively (read cmd))))
  8945. (user-error "Abort"))))
  8946. (defun org--open-help-link (path)
  8947. "Open a \"help\" type link.
  8948. PATH is a symbol name, as a string."
  8949. (pcase (intern path)
  8950. ((and (pred fboundp) variable) (describe-function variable))
  8951. ((and (pred boundp) function) (describe-variable function))
  8952. (name (user-error "Unknown function or variable: %s" name))))
  8953. (defun org--open-shell-link (path)
  8954. "Open a \"shell\" type link.
  8955. PATH is the command to execute, as a string."
  8956. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  8957. (cmd path))
  8958. (if (or (and (org-string-nw-p
  8959. org-confirm-shell-link-not-regexp)
  8960. (string-match
  8961. org-confirm-shell-link-not-regexp cmd))
  8962. (not org-confirm-shell-link-function)
  8963. (funcall org-confirm-shell-link-function
  8964. (format "Execute \"%s\" in shell? "
  8965. (org-add-props cmd nil
  8966. 'face 'org-warning))))
  8967. (progn
  8968. (message "Executing %s" cmd)
  8969. (shell-command cmd buf)
  8970. (when (featurep 'midnight)
  8971. (setq clean-buffer-list-kill-buffer-names
  8972. (cons (buffer-name buf)
  8973. clean-buffer-list-kill-buffer-names))))
  8974. (user-error "Abort"))))
  8975. (defun org-open-at-point (&optional arg reference-buffer)
  8976. "Open link, timestamp, footnote or tags at point.
  8977. When point is on a link, follow it. Normally, files will be
  8978. opened by an appropriate application. If the optional prefix
  8979. argument ARG is non-nil, Emacs will visit the file. With
  8980. a double prefix argument, try to open outside of Emacs, in the
  8981. application the system uses for this file type.
  8982. When point is on a timestamp, open the agenda at the day
  8983. specified.
  8984. When point is a footnote definition, move to the first reference
  8985. found. If it is on a reference, move to the associated
  8986. definition.
  8987. When point is on a headline, display a list of every link in the
  8988. entry, so it is possible to pick one, or all, of them. If point
  8989. is on a tag, call `org-tags-view' instead.
  8990. When optional argument REFERENCE-BUFFER is non-nil, it should
  8991. specify a buffer from where the link search should happen. This
  8992. is used internally by `org-open-link-from-string'.
  8993. On top of syntactically correct links, this function will also
  8994. try to open links and time-stamps in comments, example
  8995. blocks... i.e., whenever point is on something looking like
  8996. a timestamp or a link."
  8997. (interactive "P")
  8998. ;; On a code block, open block's results.
  8999. (unless (call-interactively 'org-babel-open-src-block-result)
  9000. (org-load-modules-maybe)
  9001. (setq org-window-config-before-follow-link (current-window-configuration))
  9002. (org-remove-occur-highlights nil nil t)
  9003. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9004. (let* ((context
  9005. ;; Only consider supported types, even if they are not
  9006. ;; the closest one.
  9007. (org-element-lineage
  9008. (org-element-context)
  9009. '(clock footnote-definition footnote-reference headline
  9010. inlinetask link timestamp)
  9011. t))
  9012. (type (org-element-type context))
  9013. (value (org-element-property :value context)))
  9014. (cond
  9015. ;; On a headline or an inlinetask, but not on a timestamp,
  9016. ;; a link, a footnote reference.
  9017. ((memq type '(headline inlinetask))
  9018. (org-match-line org-complex-heading-regexp)
  9019. (if (and (match-beginning 5)
  9020. (>= (point) (match-beginning 5))
  9021. (< (point) (match-end 5)))
  9022. ;; On tags.
  9023. (org-tags-view arg (substring (match-string 5) 0 -1))
  9024. ;; Not on tags.
  9025. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  9026. (`(nil . ,_)
  9027. (require 'org-attach)
  9028. (org-attach-reveal 'if-exists))
  9029. (`(,links . ,links-end)
  9030. (dolist (link (if (stringp links) (list links) links))
  9031. (search-forward link nil links-end)
  9032. (goto-char (match-beginning 0))
  9033. (org-open-at-point))))))
  9034. ;; On a footnote reference or at definition's label.
  9035. ((or (eq type 'footnote-reference)
  9036. (and (eq type 'footnote-definition)
  9037. (save-excursion
  9038. ;; Do not validate action when point is on the
  9039. ;; spaces right after the footnote label, in
  9040. ;; order to be on par with behavior on links.
  9041. (skip-chars-forward " \t")
  9042. (let ((begin
  9043. (org-element-property :contents-begin context)))
  9044. (if begin (< (point) begin)
  9045. (= (org-element-property :post-affiliated context)
  9046. (line-beginning-position)))))))
  9047. (org-footnote-action))
  9048. ;; No valid context. Ignore catch-all types like `headline'.
  9049. ;; If point is on something looking like a link or
  9050. ;; a time-stamp, try opening it. It may be useful in
  9051. ;; comments, example blocks...
  9052. ((memq type '(footnote-definition headline inlinetask nil))
  9053. (call-interactively #'org-open-at-point-global))
  9054. ;; On a clock line, make sure point is on the timestamp
  9055. ;; before opening it.
  9056. ((and (eq type 'clock)
  9057. value
  9058. (>= (point) (org-element-property :begin value))
  9059. (<= (point) (org-element-property :end value)))
  9060. (org-follow-timestamp-link))
  9061. ;; Do nothing on white spaces after an object.
  9062. ((>= (point)
  9063. (save-excursion
  9064. (goto-char (org-element-property :end context))
  9065. (skip-chars-backward " \t")
  9066. (point)))
  9067. (user-error "No link found"))
  9068. ((eq type 'timestamp) (org-follow-timestamp-link))
  9069. ((eq type 'link)
  9070. (let ((type (org-element-property :type context))
  9071. (path (org-link-unescape (org-element-property :path context))))
  9072. ;; Switch back to REFERENCE-BUFFER needed when called in
  9073. ;; a temporary buffer through `org-open-link-from-string'.
  9074. (with-current-buffer (or reference-buffer (current-buffer))
  9075. (cond
  9076. ((equal type "file")
  9077. (if (string-match "[*?{]" (file-name-nondirectory path))
  9078. (dired path)
  9079. ;; Look into `org-link-parameters' in order to find
  9080. ;; a DEDICATED-FUNCTION to open file. The function
  9081. ;; will be applied on raw link instead of parsed
  9082. ;; link due to the limitation in `org-add-link-type'
  9083. ;; ("open" function called with a single argument).
  9084. ;; If no such function is found, fallback to
  9085. ;; `org-open-file'.
  9086. (let* ((option (org-element-property :search-option context))
  9087. (app (org-element-property :application context))
  9088. (dedicated-function
  9089. (org-link-get-parameter
  9090. (if app (concat type "+" app) type)
  9091. :follow)))
  9092. (if dedicated-function
  9093. (funcall dedicated-function
  9094. (concat path
  9095. (and option (concat "::" option))))
  9096. (apply #'org-open-file
  9097. path
  9098. (cond (arg)
  9099. ((equal app "emacs") 'emacs)
  9100. ((equal app "sys") 'system))
  9101. (cond ((not option) nil)
  9102. ((string-match-p "\\`[0-9]+\\'" option)
  9103. (list (string-to-number option)))
  9104. (t (list nil
  9105. (org-link-unescape option)))))))))
  9106. ((functionp (org-link-get-parameter type :follow))
  9107. (funcall (org-link-get-parameter type :follow) path))
  9108. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9109. (unless (run-hook-with-args-until-success
  9110. 'org-open-link-functions path)
  9111. (if (not arg) (org-mark-ring-push)
  9112. (switch-to-buffer-other-window
  9113. (org-get-buffer-for-internal-link (current-buffer))))
  9114. (let ((destination
  9115. (org-with-wide-buffer
  9116. (if (equal type "radio")
  9117. (org-search-radio-target
  9118. (org-element-property :path context))
  9119. (org-link-search
  9120. (if (member type '("custom-id" "coderef"))
  9121. (org-element-property :raw-link context)
  9122. path)
  9123. ;; Prevent fuzzy links from matching
  9124. ;; themselves.
  9125. (and (equal type "fuzzy")
  9126. (+ 2 (org-element-property :begin context)))))
  9127. (point))))
  9128. (unless (and (<= (point-min) destination)
  9129. (>= (point-max) destination))
  9130. (widen))
  9131. (goto-char destination))))
  9132. (t (browse-url-at-point))))))
  9133. (t (user-error "No link found")))))
  9134. (run-hook-with-args 'org-follow-link-hook)))
  9135. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9136. "Offer links in the current entry and return the selected link.
  9137. If there is only one link, return it.
  9138. If NTH is an integer, return the NTH link found.
  9139. If ZERO is a string, check also this string for a link, and if
  9140. there is one, return it."
  9141. (with-current-buffer buffer
  9142. (org-with-wide-buffer
  9143. (goto-char marker)
  9144. (let ((cnt ?0)
  9145. have-zero end links link c)
  9146. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9147. (push (match-string 0 zero) links)
  9148. (setq cnt (1- cnt) have-zero t))
  9149. (save-excursion
  9150. (org-back-to-heading t)
  9151. (setq end (save-excursion (outline-next-heading) (point)))
  9152. (while (re-search-forward org-any-link-re end t)
  9153. (push (match-string 0) links))
  9154. (setq links (org-uniquify (reverse links))))
  9155. (cond
  9156. ((null links)
  9157. (message "No links"))
  9158. ((equal (length links) 1)
  9159. (setq link (car links)))
  9160. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9161. (setq link (nth (if have-zero nth (1- nth)) links)))
  9162. (t ; we have to select a link
  9163. (save-excursion
  9164. (save-window-excursion
  9165. (delete-other-windows)
  9166. (with-output-to-temp-buffer "*Select Link*"
  9167. (dolist (l links)
  9168. (cond
  9169. ((not (string-match org-bracket-link-regexp l))
  9170. (princ (format "[%c] %s\n" (cl-incf cnt)
  9171. (org-unbracket-string "<" ">" l))))
  9172. ((match-end 3)
  9173. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9174. (match-string 3 l) (match-string 1 l))))
  9175. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9176. (match-string 1 l)))))))
  9177. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9178. (message "Select link to open, RET to open all:")
  9179. (setq c (read-char-exclusive))
  9180. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9181. (when (equal c ?q) (user-error "Abort"))
  9182. (if (equal c ?\C-m)
  9183. (setq link links)
  9184. (setq nth (- c ?0))
  9185. (when have-zero (setq nth (1+ nth)))
  9186. (unless (and (integerp nth) (>= (length links) nth))
  9187. (user-error "Invalid link selection"))
  9188. (setq link (nth (1- nth) links)))))
  9189. (cons link end)))))
  9190. ;; TODO: These functions are deprecated since `org-open-at-point'
  9191. ;; hard-codes behavior for "file+emacs" and "file+sys" types.
  9192. (defun org-open-file-with-system (path)
  9193. "Open file at PATH using the system way of opening it."
  9194. (org-open-file path 'system))
  9195. (defun org-open-file-with-emacs (path)
  9196. "Open file at PATH in Emacs."
  9197. (org-open-file path 'emacs))
  9198. ;;; File search
  9199. (defvar org-create-file-search-functions nil
  9200. "List of functions to construct the right search string for a file link.
  9201. These functions are called in turn with point at the location to
  9202. which the link should point.
  9203. A function in the hook should first test if it would like to
  9204. handle this file type, for example by checking the `major-mode'
  9205. or the file extension. If it decides not to handle this file, it
  9206. should just return nil to give other functions a chance. If it
  9207. does handle the file, it must return the search string to be used
  9208. when following the link. The search string will be part of the
  9209. file link, given after a double colon, and `org-open-at-point'
  9210. will automatically search for it. If special measures must be
  9211. taken to make the search successful, another function should be
  9212. added to the companion hook `org-execute-file-search-functions',
  9213. which see.
  9214. A function in this hook may also use `setq' to set the variable
  9215. `description' to provide a suggestion for the descriptive text to
  9216. be used for this link when it gets inserted into an Org buffer
  9217. with \\[org-insert-link].")
  9218. (defvar org-execute-file-search-functions nil
  9219. "List of functions to execute a file search triggered by a link.
  9220. Functions added to this hook must accept a single argument, the
  9221. search string that was part of the file link, the part after the
  9222. double colon. The function must first check if it would like to
  9223. handle this search, for example by checking the `major-mode' or
  9224. the file extension. If it decides not to handle this search, it
  9225. should just return nil to give other functions a chance. If it
  9226. does handle the search, it must return a non-nil value to keep
  9227. other functions from trying.
  9228. Each function can access the current prefix argument through the
  9229. variable `current-prefix-arg'. Note that a single prefix is used
  9230. to force opening a link in Emacs, so it may be good to only use a
  9231. numeric or double prefix to guide the search function.
  9232. In case this is needed, a function in this hook can also restore
  9233. the window configuration before `org-open-at-point' was called using:
  9234. (set-window-configuration org-window-config-before-follow-link)")
  9235. (defun org-search-radio-target (target)
  9236. "Search a radio target matching TARGET in current buffer.
  9237. White spaces are not significant."
  9238. (let ((re (format "<<<%s>>>"
  9239. (mapconcat #'regexp-quote
  9240. (split-string target)
  9241. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9242. (origin (point)))
  9243. (goto-char (point-min))
  9244. (catch :radio-match
  9245. (while (re-search-forward re nil t)
  9246. (backward-char)
  9247. (let ((object (org-element-context)))
  9248. (when (eq (org-element-type object) 'radio-target)
  9249. (goto-char (org-element-property :begin object))
  9250. (org-show-context 'link-search)
  9251. (throw :radio-match nil))))
  9252. (goto-char origin)
  9253. (user-error "No match for radio target: %s" target))))
  9254. (defun org-link-search (s &optional avoid-pos stealth)
  9255. "Search for a search string S.
  9256. If S starts with \"#\", it triggers a custom ID search.
  9257. If S is enclosed within parenthesis, it initiates a coderef
  9258. search.
  9259. If S is surrounded by forward slashes, it is interpreted as
  9260. a regular expression. In Org mode files, this will create an
  9261. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9262. to list matches. If the current buffer is in `dired-mode', grep
  9263. will be used to search in all files.
  9264. When AVOID-POS is given, ignore matches near that position.
  9265. When optional argument STEALTH is non-nil, do not modify
  9266. visibility around point, thus ignoring `org-show-context-detail'
  9267. variable.
  9268. Search is case-insensitive and ignores white spaces. Return type
  9269. of matched result, which is either `dedicated' or `fuzzy'."
  9270. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9271. (let* ((case-fold-search t)
  9272. (origin (point))
  9273. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9274. (starred (eq (string-to-char normalized) ?*))
  9275. (words (split-string (if starred (substring s 1) s)))
  9276. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9277. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9278. type)
  9279. (cond
  9280. ;; Check if there are any special search functions.
  9281. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9282. ((eq (string-to-char s) ?#)
  9283. ;; Look for a custom ID S if S starts with "#".
  9284. (let* ((id (substring normalized 1))
  9285. (match (org-find-property "CUSTOM_ID" id)))
  9286. (if match (progn (goto-char match) (setf type 'dedicated))
  9287. (error "No match for custom ID: %s" id))))
  9288. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9289. ;; Look for coderef targets if S is enclosed within parenthesis.
  9290. (let ((coderef (match-string-no-properties 1 normalized))
  9291. (re (substring s-single-re 1 -1)))
  9292. (goto-char (point-min))
  9293. (catch :coderef-match
  9294. (while (re-search-forward re nil t)
  9295. (let ((element (org-element-at-point)))
  9296. (when (and (memq (org-element-type element)
  9297. '(example-block src-block))
  9298. ;; Build proper regexp according to current
  9299. ;; block's label format.
  9300. (let ((label-fmt
  9301. (regexp-quote
  9302. (or (org-element-property :label-fmt element)
  9303. org-coderef-label-format))))
  9304. (save-excursion
  9305. (beginning-of-line)
  9306. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9307. (format label-fmt coderef))))))
  9308. (setq type 'dedicated)
  9309. (goto-char (match-beginning 1))
  9310. (throw :coderef-match nil))))
  9311. (goto-char origin)
  9312. (error "No match for coderef: %s" coderef))))
  9313. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9314. ;; Look for a regular expression.
  9315. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9316. (match-string 1 s)))
  9317. ;; From here, we handle fuzzy links.
  9318. ;;
  9319. ;; Look for targets, only if not in a headline search.
  9320. ((and (not starred)
  9321. (let ((target (format "<<%s>>" s-multi-re)))
  9322. (catch :target-match
  9323. (goto-char (point-min))
  9324. (while (re-search-forward target nil t)
  9325. (backward-char)
  9326. (let ((context (org-element-context)))
  9327. (when (eq (org-element-type context) 'target)
  9328. (setq type 'dedicated)
  9329. (goto-char (org-element-property :begin context))
  9330. (throw :target-match t))))
  9331. nil))))
  9332. ;; Look for elements named after S, only if not in a headline
  9333. ;; search.
  9334. ((and (not starred)
  9335. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9336. (catch :name-match
  9337. (goto-char (point-min))
  9338. (while (re-search-forward name nil t)
  9339. (let ((element (org-element-at-point)))
  9340. (when (equal words
  9341. (split-string
  9342. (org-element-property :name element)))
  9343. (setq type 'dedicated)
  9344. (beginning-of-line)
  9345. (throw :name-match t))))
  9346. nil))))
  9347. ;; Regular text search. Prefer headlines in Org mode buffers.
  9348. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9349. ;; statistics cookies and tags.
  9350. ((and (derived-mode-p 'org-mode)
  9351. (let ((title-re
  9352. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9353. org-outline-regexp-bol
  9354. org-comment-string
  9355. (mapconcat #'regexp-quote words ".+")))
  9356. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9357. (comment-re (eval-when-compile
  9358. (format "\\`%s[ \t]+" org-comment-string))))
  9359. (goto-char (point-min))
  9360. (catch :found
  9361. (while (re-search-forward title-re nil t)
  9362. (when (equal words
  9363. (split-string
  9364. (replace-regexp-in-string
  9365. cookie-re ""
  9366. (replace-regexp-in-string
  9367. comment-re "" (org-get-heading t t t)))))
  9368. (throw :found t)))
  9369. nil)))
  9370. (beginning-of-line)
  9371. (setq type 'dedicated))
  9372. ;; Offer to create non-existent headline depending on
  9373. ;; `org-link-search-must-match-exact-headline'.
  9374. ((and (derived-mode-p 'org-mode)
  9375. (not org-link-search-inhibit-query)
  9376. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9377. (yes-or-no-p "No match - create this as a new heading? "))
  9378. (goto-char (point-max))
  9379. (unless (bolp) (newline))
  9380. (org-insert-heading nil t t)
  9381. (insert s "\n")
  9382. (beginning-of-line 0))
  9383. ;; Only headlines are looked after. No need to process
  9384. ;; further: throw an error.
  9385. ((and (derived-mode-p 'org-mode)
  9386. (or starred org-link-search-must-match-exact-headline))
  9387. (goto-char origin)
  9388. (error "No match for fuzzy expression: %s" normalized))
  9389. ;; Regular text search.
  9390. ((catch :fuzzy-match
  9391. (goto-char (point-min))
  9392. (while (re-search-forward s-multi-re nil t)
  9393. ;; Skip match if it contains AVOID-POS or it is included in
  9394. ;; a link with a description but outside the description.
  9395. (unless (or (and avoid-pos
  9396. (<= (match-beginning 0) avoid-pos)
  9397. (> (match-end 0) avoid-pos))
  9398. (and (save-match-data
  9399. (org-in-regexp org-bracket-link-regexp))
  9400. (match-beginning 3)
  9401. (or (> (match-beginning 3) (point))
  9402. (<= (match-end 3) (point)))
  9403. (org-element-lineage
  9404. (save-match-data (org-element-context))
  9405. '(link) t)))
  9406. (goto-char (match-beginning 0))
  9407. (setq type 'fuzzy)
  9408. (throw :fuzzy-match t)))
  9409. nil))
  9410. ;; All failed. Throw an error.
  9411. (t (goto-char origin)
  9412. (error "No match for fuzzy expression: %s" normalized)))
  9413. ;; Disclose surroundings of match, if appropriate.
  9414. (when (and (derived-mode-p 'org-mode) (not stealth))
  9415. (org-show-context 'link-search))
  9416. type))
  9417. (defun org-get-buffer-for-internal-link (buffer)
  9418. "Return a buffer to be used for displaying the link target of internal links."
  9419. (cond
  9420. ((not org-display-internal-link-with-indirect-buffer)
  9421. buffer)
  9422. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9423. (message "Buffer is already a clone, not making another one")
  9424. ;; we also do not modify visibility in this case
  9425. buffer)
  9426. (t ; make a new indirect buffer for displaying the link
  9427. (let* ((bn (buffer-name buffer))
  9428. (ibn (concat bn "(Clone)"))
  9429. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9430. (with-current-buffer ib (org-overview))
  9431. ib))))
  9432. (defun org-do-occur (regexp &optional cleanup)
  9433. "Call the Emacs command `occur'.
  9434. If CLEANUP is non-nil, remove the printout of the regular expression
  9435. in the *Occur* buffer. This is useful if the regex is long and not useful
  9436. to read."
  9437. (occur regexp)
  9438. (when cleanup
  9439. (let ((cwin (selected-window)) win beg end)
  9440. (when (setq win (get-buffer-window "*Occur*"))
  9441. (select-window win))
  9442. (goto-char (point-min))
  9443. (when (re-search-forward "match[a-z]+" nil t)
  9444. (setq beg (match-end 0))
  9445. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9446. (setq end (1- (match-beginning 0)))))
  9447. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9448. (goto-char (point-min))
  9449. (select-window cwin))))
  9450. ;;; The Mark Ring
  9451. (defvar org-mark-ring nil
  9452. "Mark ring for positions before jumps in Org mode.")
  9453. (defvar org-mark-ring-last-goto nil
  9454. "Last position in the mark ring used to go back.")
  9455. ;; Fill and close the ring
  9456. (setq org-mark-ring nil)
  9457. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  9458. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  9459. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  9460. org-mark-ring)
  9461. (defun org-mark-ring-push (&optional pos buffer)
  9462. "Put the current position into the mark ring and rotate it.
  9463. Also push position into the Emacs mark ring. If optional
  9464. argument POS and BUFFER are not nil, mark this location instead."
  9465. (interactive)
  9466. (let ((pos (or pos (point)))
  9467. (buffer (or buffer (current-buffer))))
  9468. (with-current-buffer buffer
  9469. (org-with-point-at pos (push-mark nil t)))
  9470. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  9471. (move-marker (car org-mark-ring) pos buffer))
  9472. (message
  9473. (substitute-command-keys
  9474. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  9475. (defun org-mark-ring-goto (&optional n)
  9476. "Jump to the previous position in the mark ring.
  9477. With prefix arg N, jump back that many stored positions. When
  9478. called several times in succession, walk through the entire ring.
  9479. Org mode commands jumping to a different position in the current file,
  9480. or to another Org file, automatically push the old position onto the ring."
  9481. (interactive "p")
  9482. (let (p m)
  9483. (if (eq last-command this-command)
  9484. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  9485. (setq p org-mark-ring))
  9486. (setq org-mark-ring-last-goto p)
  9487. (setq m (car p))
  9488. (pop-to-buffer-same-window (marker-buffer m))
  9489. (goto-char m)
  9490. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  9491. (defun org-add-angle-brackets (s)
  9492. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  9493. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  9494. s)
  9495. ;;; Following specific links
  9496. (defvar org-agenda-buffer-tmp-name)
  9497. (defvar org-agenda-start-on-weekday)
  9498. (defun org-follow-timestamp-link ()
  9499. "Open an agenda view for the time-stamp date/range at point."
  9500. (cond
  9501. ((org-at-date-range-p t)
  9502. (let ((org-agenda-start-on-weekday)
  9503. (t1 (match-string 1))
  9504. (t2 (match-string 2)) tt1 tt2)
  9505. (setq tt1 (time-to-days (org-time-string-to-time t1))
  9506. tt2 (time-to-days (org-time-string-to-time t2)))
  9507. (let ((org-agenda-buffer-tmp-name
  9508. (format "*Org Agenda(a:%s)"
  9509. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  9510. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  9511. ((org-at-timestamp-p 'lax)
  9512. (let ((org-agenda-buffer-tmp-name
  9513. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  9514. (org-agenda-list nil (time-to-days (org-time-string-to-time
  9515. (substring (match-string 1) 0 10)))
  9516. 1)))
  9517. (t (error "This should not happen"))))
  9518. ;;; Following file links
  9519. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  9520. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  9521. (declare-function mailcap-mime-info
  9522. "mailcap" (string &optional request no-decode))
  9523. (defvar org-wait nil)
  9524. (defun org-open-file (path &optional in-emacs line search)
  9525. "Open the file at PATH.
  9526. First, this expands any special file name abbreviations. Then the
  9527. configuration variable `org-file-apps' is checked if it contains an
  9528. entry for this file type, and if yes, the corresponding command is launched.
  9529. If no application is found, Emacs simply visits the file.
  9530. With optional prefix argument IN-EMACS, Emacs will visit the file.
  9531. With a double \\[universal-argument] \\[universal-argument] \
  9532. prefix arg, Org tries to avoid opening in Emacs
  9533. and to use an external application to visit the file.
  9534. Optional LINE specifies a line to go to, optional SEARCH a string
  9535. to search for. If LINE or SEARCH is given, the file will be
  9536. opened in Emacs, unless an entry from org-file-apps that makes
  9537. use of groups in a regexp matches.
  9538. If you want to change the way frames are used when following a
  9539. link, please customize `org-link-frame-setup'.
  9540. If the file does not exist, an error is thrown."
  9541. (let* ((file (if (equal path "")
  9542. buffer-file-name
  9543. (substitute-in-file-name (expand-file-name path))))
  9544. (file-apps (append org-file-apps (org-default-apps)))
  9545. (apps (cl-remove-if
  9546. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9547. (apps-dlink (cl-remove-if-not
  9548. 'org-file-apps-entry-match-against-dlink-p file-apps))
  9549. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  9550. (dirp (unless remp (file-directory-p file)))
  9551. (file (if (and dirp org-open-directory-means-index-dot-org)
  9552. (concat (file-name-as-directory file) "index.org")
  9553. file))
  9554. (a-m-a-p (assq 'auto-mode apps))
  9555. (dfile (downcase file))
  9556. ;; Reconstruct the original link from the PATH, LINE and
  9557. ;; SEARCH args.
  9558. (link (cond (line (concat file "::" (number-to-string line)))
  9559. (search (concat file "::" search))
  9560. (t file)))
  9561. (dlink (downcase link))
  9562. (ext
  9563. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  9564. (match-string 1 dfile)))
  9565. (save-position-maybe
  9566. (let ((old-buffer (current-buffer))
  9567. (old-pos (point))
  9568. (old-mode major-mode))
  9569. (lambda ()
  9570. (and (derived-mode-p 'org-mode)
  9571. (eq old-mode 'org-mode)
  9572. (or (not (eq old-buffer (current-buffer)))
  9573. (not (eq old-pos (point))))
  9574. (org-mark-ring-push old-pos old-buffer)))))
  9575. cmd link-match-data)
  9576. (cond
  9577. ((member in-emacs '((16) system))
  9578. (setq cmd (cdr (assq 'system apps))))
  9579. (in-emacs (setq cmd 'emacs))
  9580. (t
  9581. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  9582. (and dirp (cdr (assq 'directory apps)))
  9583. ;; First, try matching against apps-dlink if we
  9584. ;; get a match here, store the match data for
  9585. ;; later.
  9586. (let ((match (assoc-default dlink apps-dlink
  9587. 'string-match)))
  9588. (if match
  9589. (progn (setq link-match-data (match-data))
  9590. match)
  9591. (progn (setq in-emacs (or in-emacs line search))
  9592. nil))) ; if we have no match in apps-dlink,
  9593. ; always open the file in emacs if line or search
  9594. ; is given (for backwards compatibility)
  9595. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  9596. 'string-match)
  9597. (cdr (assoc ext apps))
  9598. (cdr (assq t apps))))))
  9599. (when (eq cmd 'system)
  9600. (setq cmd (cdr (assq 'system apps))))
  9601. (when (eq cmd 'default)
  9602. (setq cmd (cdr (assoc t apps))))
  9603. (when (eq cmd 'mailcap)
  9604. (require 'mailcap)
  9605. (mailcap-parse-mailcaps)
  9606. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  9607. (command (mailcap-mime-info mime-type)))
  9608. (if (stringp command)
  9609. (setq cmd command)
  9610. (setq cmd 'emacs))))
  9611. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  9612. (not (file-exists-p file))
  9613. (not org-open-non-existing-files))
  9614. (user-error "No such file: %s" file))
  9615. (cond
  9616. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  9617. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  9618. (while (string-match "['\"]%s['\"]" cmd)
  9619. (setq cmd (replace-match "%s" t t cmd)))
  9620. (setq cmd (replace-regexp-in-string
  9621. "%s"
  9622. (shell-quote-argument (convert-standard-filename file))
  9623. cmd
  9624. nil t))
  9625. ;; Replace "%1", "%2" etc. in command with group matches from regex
  9626. (save-match-data
  9627. (let ((match-index 1)
  9628. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  9629. (set-match-data link-match-data)
  9630. (while (<= match-index number-of-groups)
  9631. (let ((regex (concat "%" (number-to-string match-index)))
  9632. (replace-with (match-string match-index dlink)))
  9633. (while (string-match regex cmd)
  9634. (setq cmd (replace-match replace-with t t cmd))))
  9635. (setq match-index (+ match-index 1)))))
  9636. (save-window-excursion
  9637. (message "Running %s...done" cmd)
  9638. (start-process-shell-command cmd nil cmd)
  9639. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  9640. ((or (stringp cmd)
  9641. (eq cmd 'emacs))
  9642. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  9643. (widen)
  9644. (cond (line (org-goto-line line)
  9645. (when (derived-mode-p 'org-mode) (org-reveal)))
  9646. (search (condition-case err
  9647. (org-link-search search)
  9648. ;; Save position before error-ing out so user
  9649. ;; can easily move back to the original buffer.
  9650. (error (funcall save-position-maybe)
  9651. (error (nth 1 err)))))))
  9652. ((functionp cmd)
  9653. (save-match-data
  9654. (set-match-data link-match-data)
  9655. (condition-case nil
  9656. (funcall cmd file link)
  9657. ;; FIXME: Remove this check when most default installations
  9658. ;; of Emacs have at least Org 9.0.
  9659. ((debug wrong-number-of-arguments wrong-type-argument
  9660. invalid-function)
  9661. (user-error "Please see Org News for version 9.0 about \
  9662. `org-file-apps'--Lisp error: %S" cmd)))))
  9663. ((consp cmd)
  9664. ;; FIXME: Remove this check when most default installations of
  9665. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  9666. ;; fall back to `org-link-frame-setup' for an old usage of
  9667. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  9668. (user-error "Please see Org News for version 9.0 about \
  9669. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  9670. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  9671. (funcall save-position-maybe)))
  9672. (defun org-file-apps-entry-match-against-dlink-p (entry)
  9673. "This function returns non-nil if `entry' uses a regular
  9674. expression which should be matched against the whole link by
  9675. org-open-file.
  9676. It assumes that is the case when the entry uses a regular
  9677. expression which has at least one grouping construct and the
  9678. action is either a lisp form or a command string containing
  9679. `%1', i.e. using at least one subexpression match as a
  9680. parameter."
  9681. (let ((selector (car entry))
  9682. (action (cdr entry)))
  9683. (if (stringp selector)
  9684. (and (> (regexp-opt-depth selector) 0)
  9685. (or (and (stringp action)
  9686. (string-match "%[0-9]" action))
  9687. (consp action)))
  9688. nil)))
  9689. (defun org-default-apps ()
  9690. "Return the default applications for this operating system."
  9691. (cond
  9692. ((eq system-type 'darwin)
  9693. org-file-apps-defaults-macosx)
  9694. ((eq system-type 'windows-nt)
  9695. org-file-apps-defaults-windowsnt)
  9696. (t org-file-apps-defaults-gnu)))
  9697. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  9698. "Convert extensions to regular expressions in the cars of LIST.
  9699. Also, weed out any non-string entries, because the return value is used
  9700. only for regexp matching.
  9701. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  9702. point to the symbol `emacs', indicating that the file should
  9703. be opened in Emacs."
  9704. (append
  9705. (delq nil
  9706. (mapcar (lambda (x)
  9707. (unless (not (stringp (car x)))
  9708. (if (string-match "\\W" (car x))
  9709. x
  9710. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  9711. list))
  9712. (when add-auto-mode
  9713. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  9714. (defvar ange-ftp-name-format)
  9715. (defun org-file-remote-p (file)
  9716. "Test whether FILE specifies a location on a remote system.
  9717. Return non-nil if the location is indeed remote.
  9718. For example, the filename \"/user@host:/foo\" specifies a location
  9719. on the system \"/user@host:\"."
  9720. (cond ((fboundp 'file-remote-p)
  9721. (file-remote-p file))
  9722. ((fboundp 'tramp-handle-file-remote-p)
  9723. (tramp-handle-file-remote-p file))
  9724. ((and (boundp 'ange-ftp-name-format)
  9725. (string-match (car ange-ftp-name-format) file))
  9726. t)))
  9727. ;;;; Refiling
  9728. (defun org-get-org-file ()
  9729. "Read a filename, with default directory `org-directory'."
  9730. (let ((default (or org-default-notes-file remember-data-file)))
  9731. (read-file-name (format "File name [%s]: " default)
  9732. (file-name-as-directory org-directory)
  9733. default)))
  9734. (defun org-notes-order-reversed-p ()
  9735. "Check if the current file should receive notes in reversed order."
  9736. (cond
  9737. ((not org-reverse-note-order) nil)
  9738. ((eq t org-reverse-note-order) t)
  9739. ((not (listp org-reverse-note-order)) nil)
  9740. (t (catch 'exit
  9741. (dolist (entry org-reverse-note-order)
  9742. (when (string-match (car entry) buffer-file-name)
  9743. (throw 'exit (cdr entry))))))))
  9744. (defvar org-refile-target-table nil
  9745. "The list of refile targets, created by `org-refile'.")
  9746. (defvar org-agenda-new-buffers nil
  9747. "Buffers created to visit agenda files.")
  9748. (defvar org-refile-cache nil
  9749. "Cache for refile targets.")
  9750. (defvar org-refile-markers nil
  9751. "All the markers used for caching refile locations.")
  9752. (defun org-refile-marker (pos)
  9753. "Get a new refile marker, but only if caching is in use."
  9754. (if (not org-refile-use-cache)
  9755. pos
  9756. (let ((m (make-marker)))
  9757. (move-marker m pos)
  9758. (push m org-refile-markers)
  9759. m)))
  9760. (defun org-refile-cache-clear ()
  9761. "Clear the refile cache and disable all the markers."
  9762. (dolist (m org-refile-markers) (move-marker m nil))
  9763. (setq org-refile-markers nil)
  9764. (setq org-refile-cache nil)
  9765. (message "Refile cache has been cleared"))
  9766. (defun org-refile-cache-check-set (set)
  9767. "Check if all the markers in the cache still have live buffers."
  9768. (let (marker)
  9769. (catch 'exit
  9770. (while (and set (setq marker (nth 3 (pop set))))
  9771. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  9772. (when (and marker (null (marker-buffer marker)))
  9773. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  9774. (sit-for 3)
  9775. (throw 'exit nil)))
  9776. t)))
  9777. (defun org-refile-cache-put (set &rest identifiers)
  9778. "Push the refile targets SET into the cache, under IDENTIFIERS."
  9779. (let* ((key (sha1 (prin1-to-string identifiers)))
  9780. (entry (assoc key org-refile-cache)))
  9781. (if entry
  9782. (setcdr entry set)
  9783. (push (cons key set) org-refile-cache))))
  9784. (defun org-refile-cache-get (&rest identifiers)
  9785. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  9786. (cond
  9787. ((not org-refile-cache) nil)
  9788. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  9789. (t
  9790. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  9791. org-refile-cache))))
  9792. (and set (org-refile-cache-check-set set) set)))))
  9793. (defvar org-outline-path-cache nil
  9794. "Alist between buffer positions and outline paths.
  9795. It value is an alist (POSITION . PATH) where POSITION is the
  9796. buffer position at the beginning of an entry and PATH is a list
  9797. of strings describing the outline path for that entry, in reverse
  9798. order.")
  9799. (defun org-refile-get-targets (&optional default-buffer)
  9800. "Produce a table with refile targets."
  9801. (let ((case-fold-search nil)
  9802. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  9803. (entries (or org-refile-targets '((nil . (:level . 1)))))
  9804. targets tgs files desc descre)
  9805. (message "Getting targets...")
  9806. (with-current-buffer (or default-buffer (current-buffer))
  9807. (dolist (entry entries)
  9808. (setq files (car entry) desc (cdr entry))
  9809. (cond
  9810. ((null files) (setq files (list (current-buffer))))
  9811. ((eq files 'org-agenda-files)
  9812. (setq files (org-agenda-files 'unrestricted)))
  9813. ((and (symbolp files) (fboundp files))
  9814. (setq files (funcall files)))
  9815. ((and (symbolp files) (boundp files))
  9816. (setq files (symbol-value files))))
  9817. (when (stringp files) (setq files (list files)))
  9818. (cond
  9819. ((eq (car desc) :tag)
  9820. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  9821. ((eq (car desc) :todo)
  9822. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  9823. ((eq (car desc) :regexp)
  9824. (setq descre (cdr desc)))
  9825. ((eq (car desc) :level)
  9826. (setq descre (concat "^\\*\\{" (number-to-string
  9827. (if org-odd-levels-only
  9828. (1- (* 2 (cdr desc)))
  9829. (cdr desc)))
  9830. "\\}[ \t]")))
  9831. ((eq (car desc) :maxlevel)
  9832. (setq descre (concat "^\\*\\{1," (number-to-string
  9833. (if org-odd-levels-only
  9834. (1- (* 2 (cdr desc)))
  9835. (cdr desc)))
  9836. "\\}[ \t]")))
  9837. (t (error "Bad refiling target description %s" desc)))
  9838. (dolist (f files)
  9839. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  9840. (or
  9841. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  9842. (progn
  9843. (when (bufferp f)
  9844. (setq f (buffer-file-name (buffer-base-buffer f))))
  9845. (setq f (and f (expand-file-name f)))
  9846. (when (eq org-refile-use-outline-path 'file)
  9847. (push (list (file-name-nondirectory f) f nil nil) tgs))
  9848. (when (eq org-refile-use-outline-path 'buffer-name)
  9849. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  9850. (when (eq org-refile-use-outline-path 'full-file-path)
  9851. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  9852. (org-with-wide-buffer
  9853. (goto-char (point-min))
  9854. (setq org-outline-path-cache nil)
  9855. (while (re-search-forward descre nil t)
  9856. (beginning-of-line)
  9857. (let ((case-fold-search nil))
  9858. (looking-at org-complex-heading-regexp))
  9859. (let ((begin (point))
  9860. (heading (match-string-no-properties 4)))
  9861. (unless (or (and
  9862. org-refile-target-verify-function
  9863. (not
  9864. (funcall org-refile-target-verify-function)))
  9865. (not heading))
  9866. (let ((re (format org-complex-heading-regexp-format
  9867. (regexp-quote heading)))
  9868. (target
  9869. (if (not org-refile-use-outline-path) heading
  9870. (mapconcat
  9871. #'identity
  9872. (append
  9873. (pcase org-refile-use-outline-path
  9874. (`file (list (file-name-nondirectory
  9875. (buffer-file-name
  9876. (buffer-base-buffer)))))
  9877. (`full-file-path
  9878. (list (buffer-file-name
  9879. (buffer-base-buffer))))
  9880. (`buffer-name
  9881. (list (buffer-name
  9882. (buffer-base-buffer))))
  9883. (_ nil))
  9884. (mapcar (lambda (s) (replace-regexp-in-string
  9885. "/" "\\/" s nil t))
  9886. (org-get-outline-path t t)))
  9887. "/"))))
  9888. (push (list target f re (org-refile-marker (point)))
  9889. tgs)))
  9890. (when (= (point) begin)
  9891. ;; Verification function has not moved point.
  9892. (end-of-line)))))))
  9893. (when org-refile-use-cache
  9894. (org-refile-cache-put tgs (buffer-file-name) descre))
  9895. (setq targets (append tgs targets))))))
  9896. (message "Getting targets...done")
  9897. (delete-dups (nreverse targets))))
  9898. (defun org--get-outline-path-1 (&optional use-cache)
  9899. "Return outline path to current headline.
  9900. Outline path is a list of strings, in reverse order. When
  9901. optional argument USE-CACHE is non-nil, make use of a cache. See
  9902. `org-get-outline-path' for details.
  9903. Assume buffer is widened and point is on a headline."
  9904. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  9905. (let ((p (point))
  9906. (heading (let ((case-fold-search nil))
  9907. (looking-at org-complex-heading-regexp)
  9908. (if (not (match-end 4)) ""
  9909. ;; Remove statistics cookies.
  9910. (org-trim
  9911. (org-link-display-format
  9912. (replace-regexp-in-string
  9913. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  9914. (match-string-no-properties 4))))))))
  9915. (if (org-up-heading-safe)
  9916. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  9917. (when use-cache
  9918. (push (cons p path) org-outline-path-cache))
  9919. path)
  9920. ;; This is a new root node. Since we assume we are moving
  9921. ;; forward, we can drop previous cache so as to limit number
  9922. ;; of associations there.
  9923. (let ((path (list heading)))
  9924. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  9925. path)))))
  9926. (defun org-get-outline-path (&optional with-self use-cache)
  9927. "Return the outline path to the current entry.
  9928. An outline path is a list of ancestors for current headline, as
  9929. a list of strings. Statistics cookies are removed and links are
  9930. replaced with their description, if any, or their path otherwise.
  9931. When optional argument WITH-SELF is non-nil, the path also
  9932. includes the current headline.
  9933. When optional argument USE-CACHE is non-nil, cache outline paths
  9934. between calls to this function so as to avoid backtracking. This
  9935. argument is useful when planning to find more than one outline
  9936. path in the same document. In that case, there are two
  9937. conditions to satisfy:
  9938. - `org-outline-path-cache' is set to nil before starting the
  9939. process;
  9940. - outline paths are computed by increasing buffer positions."
  9941. (org-with-wide-buffer
  9942. (and (or (and with-self (org-back-to-heading t))
  9943. (org-up-heading-safe))
  9944. (reverse (org--get-outline-path-1 use-cache)))))
  9945. (defun org-format-outline-path (path &optional width prefix separator)
  9946. "Format the outline path PATH for display.
  9947. WIDTH is the maximum number of characters that is available.
  9948. PREFIX is a prefix to be included in the returned string,
  9949. such as the file name.
  9950. SEPARATOR is inserted between the different parts of the path,
  9951. the default is \"/\"."
  9952. (setq width (or width 79))
  9953. (setq path (delq nil path))
  9954. (unless (> width 0)
  9955. (user-error "Argument `width' must be positive"))
  9956. (setq separator (or separator "/"))
  9957. (let* ((org-odd-levels-only nil)
  9958. (fpath (concat
  9959. prefix (and prefix path separator)
  9960. (mapconcat
  9961. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  9962. (cl-loop for head in path
  9963. for n from 0
  9964. collect (org-add-props
  9965. head nil 'face
  9966. (nth (% n org-n-level-faces) org-level-faces)))
  9967. separator))))
  9968. (when (> (length fpath) width)
  9969. (if (< width 7)
  9970. ;; It's unlikely that `width' will be this small, but don't
  9971. ;; waste characters by adding ".." if it is.
  9972. (setq fpath (substring fpath 0 width))
  9973. (setf (substring fpath (- width 2)) "..")))
  9974. fpath))
  9975. (defun org-display-outline-path (&optional file current separator just-return-string)
  9976. "Display the current outline path in the echo area.
  9977. If FILE is non-nil, prepend the output with the file name.
  9978. If CURRENT is non-nil, append the current heading to the output.
  9979. SEPARATOR is passed through to `org-format-outline-path'. It separates
  9980. the different parts of the path and defaults to \"/\".
  9981. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  9982. (interactive "P")
  9983. (let* (case-fold-search
  9984. (bfn (buffer-file-name (buffer-base-buffer)))
  9985. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  9986. res)
  9987. (when current (setq path (append path
  9988. (save-excursion
  9989. (org-back-to-heading t)
  9990. (when (looking-at org-complex-heading-regexp)
  9991. (list (match-string 4)))))))
  9992. (setq res
  9993. (org-format-outline-path
  9994. path
  9995. (1- (frame-width))
  9996. (and file bfn (concat (file-name-nondirectory bfn) separator))
  9997. separator))
  9998. (if just-return-string
  9999. (org-no-properties res)
  10000. (org-unlogged-message "%s" res))))
  10001. (defvar org-refile-history nil
  10002. "History for refiling operations.")
  10003. (defvar org-after-refile-insert-hook nil
  10004. "Hook run after `org-refile' has inserted its stuff at the new location.
  10005. Note that this is still *before* the stuff will be removed from
  10006. the *old* location.")
  10007. (defvar org-capture-last-stored-marker)
  10008. (defvar org-refile-keep nil
  10009. "Non-nil means `org-refile' will copy instead of refile.")
  10010. (defun org-copy ()
  10011. "Like `org-refile', but copy."
  10012. (interactive)
  10013. (let ((org-refile-keep t))
  10014. (funcall 'org-refile nil nil nil "Copy")))
  10015. (defun org-refile (&optional arg default-buffer rfloc msg)
  10016. "Move the entry or entries at point to another heading.
  10017. The list of target headings is compiled using the information in
  10018. `org-refile-targets', which see.
  10019. At the target location, the entry is filed as a subitem of the
  10020. target heading. Depending on `org-reverse-note-order', the new
  10021. subitem will either be the first or the last subitem.
  10022. If there is an active region, all entries in that region will be
  10023. refiled. However, the region must fulfill the requirement that
  10024. the first heading sets the top-level of the moved text.
  10025. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10026. location
  10027. and not actually move anything.
  10028. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10029. location where the last
  10030. refiling operation has put the subtree.
  10031. With a numeric prefix argument of `2', refile to the running clock.
  10032. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10033. being set to t and copy to the target location, don't move it.
  10034. Beware that keeping refiled entries may result in duplicated ID
  10035. properties.
  10036. RFLOC can be a refile location obtained in a different way.
  10037. MSG is a string to replace \"Refile\" in the default prompt with
  10038. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10039. See also `org-refile-use-outline-path'.
  10040. If you are using target caching (see `org-refile-use-cache'), you
  10041. have to clear the target cache in order to find new targets.
  10042. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10043. prefix argument (`C-u C-u C-u C-c C-w')."
  10044. (interactive "P")
  10045. (if (member arg '(0 (64)))
  10046. (org-refile-cache-clear)
  10047. (let* ((actionmsg (cond (msg msg)
  10048. ((equal arg 3) "Refile (and keep)")
  10049. (t "Refile")))
  10050. (regionp (org-region-active-p))
  10051. (region-start (and regionp (region-beginning)))
  10052. (region-end (and regionp (region-end)))
  10053. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10054. pos it nbuf file level reversed)
  10055. (setq last-command nil)
  10056. (when regionp
  10057. (goto-char region-start)
  10058. (or (bolp) (goto-char (point-at-bol)))
  10059. (setq region-start (point))
  10060. (unless (or (org-kill-is-subtree-p
  10061. (buffer-substring region-start region-end))
  10062. (prog1 org-refile-active-region-within-subtree
  10063. (let ((s (point-at-eol)))
  10064. (org-toggle-heading)
  10065. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10066. (user-error "The region is not a (sequence of) subtree(s)")))
  10067. (if (equal arg '(16))
  10068. (org-refile-goto-last-stored)
  10069. (when (or
  10070. (and (equal arg 2)
  10071. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10072. (prog1
  10073. (setq it (list (or org-clock-heading "running clock")
  10074. (buffer-file-name
  10075. (marker-buffer org-clock-hd-marker))
  10076. ""
  10077. (marker-position org-clock-hd-marker)))
  10078. (setq arg nil)))
  10079. (setq it
  10080. (or rfloc
  10081. (let (heading-text)
  10082. (save-excursion
  10083. (unless (and arg (listp arg))
  10084. (org-back-to-heading t)
  10085. (setq heading-text
  10086. (replace-regexp-in-string
  10087. org-bracket-link-regexp
  10088. "\\3"
  10089. (or (nth 4 (org-heading-components))
  10090. ""))))
  10091. (org-refile-get-location
  10092. (cond ((and arg (listp arg)) "Goto")
  10093. (regionp (concat actionmsg " region to"))
  10094. (t (concat actionmsg " subtree \""
  10095. heading-text "\" to")))
  10096. default-buffer
  10097. (and (not (equal '(4) arg))
  10098. org-refile-allow-creating-parent-nodes)))))))
  10099. (setq file (nth 1 it)
  10100. pos (nth 3 it))
  10101. (when (and (not arg)
  10102. pos
  10103. (equal (buffer-file-name) file)
  10104. (if regionp
  10105. (and (>= pos region-start)
  10106. (<= pos region-end))
  10107. (and (>= pos (point))
  10108. (< pos (save-excursion
  10109. (org-end-of-subtree t t))))))
  10110. (error "Cannot refile to position inside the tree or region"))
  10111. (setq nbuf (or (find-buffer-visiting file)
  10112. (find-file-noselect file)))
  10113. (if (and arg (not (equal arg 3)))
  10114. (progn
  10115. (pop-to-buffer-same-window nbuf)
  10116. (goto-char (cond (pos)
  10117. ((org-notes-order-reversed-p) (point-min))
  10118. (t (point-max))))
  10119. (org-show-context 'org-goto))
  10120. (if regionp
  10121. (progn
  10122. (org-kill-new (buffer-substring region-start region-end))
  10123. (org-save-markers-in-region region-start region-end))
  10124. (org-copy-subtree 1 nil t))
  10125. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10126. (find-file-noselect file)))
  10127. (setq reversed (org-notes-order-reversed-p))
  10128. (org-with-wide-buffer
  10129. (if pos
  10130. (progn
  10131. (goto-char pos)
  10132. (setq level (org-get-valid-level (funcall outline-level) 1))
  10133. (goto-char
  10134. (if reversed
  10135. (or (outline-next-heading) (point-max))
  10136. (or (save-excursion (org-get-next-sibling))
  10137. (org-end-of-subtree t t)
  10138. (point-max)))))
  10139. (setq level 1)
  10140. (if (not reversed)
  10141. (goto-char (point-max))
  10142. (goto-char (point-min))
  10143. (or (outline-next-heading) (goto-char (point-max)))))
  10144. (unless (bolp) (newline))
  10145. (org-paste-subtree level nil nil t)
  10146. (when org-log-refile
  10147. (org-add-log-setup 'refile nil nil org-log-refile)
  10148. (unless (eq org-log-refile 'note)
  10149. (save-excursion (org-add-log-note))))
  10150. (and org-auto-align-tags
  10151. (let ((org-loop-over-headlines-in-active-region nil))
  10152. (org-set-tags nil t)))
  10153. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10154. :last-refile)))
  10155. (when bookmark-name
  10156. (with-demoted-errors
  10157. (bookmark-set bookmark-name))))
  10158. ;; If we are refiling for capture, make sure that the
  10159. ;; last-capture pointers point here
  10160. (when (bound-and-true-p org-capture-is-refiling)
  10161. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10162. :last-capture-marker)))
  10163. (when bookmark-name
  10164. (with-demoted-errors
  10165. (bookmark-set bookmark-name))))
  10166. (move-marker org-capture-last-stored-marker (point)))
  10167. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10168. (run-hooks 'org-after-refile-insert-hook)))
  10169. (unless org-refile-keep
  10170. (if regionp
  10171. (delete-region (point) (+ (point) (- region-end region-start)))
  10172. (org-preserve-local-variables
  10173. (delete-region
  10174. (and (org-back-to-heading t) (point))
  10175. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
  10176. (when (featurep 'org-inlinetask)
  10177. (org-inlinetask-remove-END-maybe))
  10178. (setq org-markers-to-move nil)
  10179. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10180. (defun org-refile-goto-last-stored ()
  10181. "Go to the location where the last refile was stored."
  10182. (interactive)
  10183. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10184. (message "This is the location of the last refile"))
  10185. (defun org-refile--get-location (refloc tbl)
  10186. "When user refile to REFLOC, find the associated target in TBL.
  10187. Also check `org-refile-target-table'."
  10188. (car (delq
  10189. nil
  10190. (mapcar
  10191. (lambda (r) (or (assoc r tbl)
  10192. (assoc r org-refile-target-table)))
  10193. (list (replace-regexp-in-string "/$" "" refloc)
  10194. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10195. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10196. "Prompt the user for a refile location, using PROMPT.
  10197. PROMPT should not be suffixed with a colon and a space, because
  10198. this function appends the default value from
  10199. `org-refile-history' automatically, if that is not empty."
  10200. (let ((org-refile-targets org-refile-targets)
  10201. (org-refile-use-outline-path org-refile-use-outline-path))
  10202. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10203. (unless org-refile-target-table
  10204. (user-error "No refile targets"))
  10205. (let* ((cbuf (current-buffer))
  10206. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10207. (cfunc (if (and org-refile-use-outline-path
  10208. org-outline-path-complete-in-steps)
  10209. #'org-olpath-completing-read
  10210. #'completing-read))
  10211. (extra (if org-refile-use-outline-path "/" ""))
  10212. (cbnex (concat (buffer-name) extra))
  10213. (filename (and cfn (expand-file-name cfn)))
  10214. (tbl (mapcar
  10215. (lambda (x)
  10216. (if (and (not (member org-refile-use-outline-path
  10217. '(file full-file-path)))
  10218. (not (equal filename (nth 1 x))))
  10219. (cons (concat (car x) extra " ("
  10220. (file-name-nondirectory (nth 1 x)) ")")
  10221. (cdr x))
  10222. (cons (concat (car x) extra) (cdr x))))
  10223. org-refile-target-table))
  10224. (completion-ignore-case t)
  10225. cdef
  10226. (prompt (concat prompt
  10227. (or (and (car org-refile-history)
  10228. (concat " (default " (car org-refile-history) ")"))
  10229. (and (assoc cbnex tbl) (setq cdef cbnex)
  10230. (concat " (default " cbnex ")"))) ": "))
  10231. pa answ parent-target child parent old-hist)
  10232. (setq old-hist org-refile-history)
  10233. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10234. nil 'org-refile-history (or cdef (car org-refile-history))))
  10235. (if (setq pa (org-refile--get-location answ tbl))
  10236. (progn
  10237. (org-refile-check-position pa)
  10238. (when (or (not org-refile-history)
  10239. (not (eq old-hist org-refile-history))
  10240. (not (equal (car pa) (car org-refile-history))))
  10241. (setq org-refile-history
  10242. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10243. org-refile-history
  10244. (cdr org-refile-history))))
  10245. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10246. (pop org-refile-history)))
  10247. pa)
  10248. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10249. (progn
  10250. (setq parent (match-string 1 answ)
  10251. child (match-string 2 answ))
  10252. (setq parent-target (org-refile--get-location parent tbl))
  10253. (when (and parent-target
  10254. (or (eq new-nodes t)
  10255. (and (eq new-nodes 'confirm)
  10256. (y-or-n-p (format "Create new node \"%s\"? "
  10257. child)))))
  10258. (org-refile-new-child parent-target child)))
  10259. (user-error "Invalid target location")))))
  10260. (declare-function org-string-nw-p "org-macs" (s))
  10261. (defun org-refile-check-position (refile-pointer)
  10262. "Check if the refile pointer matches the headline to which it points."
  10263. (let* ((file (nth 1 refile-pointer))
  10264. (re (nth 2 refile-pointer))
  10265. (pos (nth 3 refile-pointer))
  10266. buffer)
  10267. (if (and (not (markerp pos)) (not file))
  10268. (user-error "Please indicate a target file in the refile path")
  10269. (when (org-string-nw-p re)
  10270. (setq buffer (if (markerp pos)
  10271. (marker-buffer pos)
  10272. (or (find-buffer-visiting file)
  10273. (find-file-noselect file))))
  10274. (with-current-buffer buffer
  10275. (org-with-wide-buffer
  10276. (goto-char pos)
  10277. (beginning-of-line 1)
  10278. (unless (looking-at-p re)
  10279. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10280. (defun org-refile-new-child (parent-target child)
  10281. "Use refile target PARENT-TARGET to add new CHILD below it."
  10282. (unless parent-target
  10283. (error "Cannot find parent for new node"))
  10284. (let ((file (nth 1 parent-target))
  10285. (pos (nth 3 parent-target))
  10286. level)
  10287. (with-current-buffer (or (find-buffer-visiting file)
  10288. (find-file-noselect file))
  10289. (org-with-wide-buffer
  10290. (if pos
  10291. (goto-char pos)
  10292. (goto-char (point-max))
  10293. (unless (bolp) (newline)))
  10294. (when (looking-at org-outline-regexp)
  10295. (setq level (funcall outline-level))
  10296. (org-end-of-subtree t t))
  10297. (org-back-over-empty-lines)
  10298. (insert "\n" (make-string
  10299. (if pos (org-get-valid-level level 1) 1) ?*)
  10300. " " child "\n")
  10301. (beginning-of-line 0)
  10302. (list (concat (car parent-target) "/" child) file "" (point))))))
  10303. (defun org-olpath-completing-read (prompt collection &rest args)
  10304. "Read an outline path like a file name."
  10305. (let ((thetable collection))
  10306. (apply #'completing-read
  10307. prompt
  10308. (lambda (string predicate &optional flag)
  10309. (cond
  10310. ((eq flag nil) (try-completion string thetable))
  10311. ((eq flag t)
  10312. (let ((l (length string)))
  10313. (mapcar (lambda (x)
  10314. (let ((r (substring x l))
  10315. (f (if (string-match " ([^)]*)$" x)
  10316. (match-string 0 x)
  10317. "")))
  10318. (if (string-match "/" r)
  10319. (concat string (substring r 0 (match-end 0)) f)
  10320. x)))
  10321. (all-completions string thetable predicate))))
  10322. ;; Exact match?
  10323. ((eq flag 'lambda) (assoc string thetable))))
  10324. args)))
  10325. ;;;; Dynamic blocks
  10326. (defun org-find-dblock (name)
  10327. "Find the first dynamic block with name NAME in the buffer.
  10328. If not found, stay at current position and return nil."
  10329. (let ((case-fold-search t) pos)
  10330. (save-excursion
  10331. (goto-char (point-min))
  10332. (setq pos (and (re-search-forward
  10333. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10334. (match-beginning 0))))
  10335. (when pos (goto-char pos))
  10336. pos))
  10337. (defun org-create-dblock (plist)
  10338. "Create a dynamic block section, with parameters taken from PLIST.
  10339. PLIST must contain a :name entry which is used as the name of the block."
  10340. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10341. (end-of-line 1)
  10342. (newline))
  10343. (let ((col (current-column))
  10344. (name (plist-get plist :name)))
  10345. (insert "#+BEGIN: " name)
  10346. (while plist
  10347. (if (eq (car plist) :name)
  10348. (setq plist (cddr plist))
  10349. (insert " " (prin1-to-string (pop plist)))))
  10350. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10351. (beginning-of-line -2)))
  10352. (defun org-prepare-dblock ()
  10353. "Prepare dynamic block for refresh.
  10354. This empties the block, puts the cursor at the insert position and returns
  10355. the property list including an extra property :name with the block name."
  10356. (unless (looking-at org-dblock-start-re)
  10357. (user-error "Not at a dynamic block"))
  10358. (let* ((begdel (1+ (match-end 0)))
  10359. (name (org-no-properties (match-string 1)))
  10360. (params (append (list :name name)
  10361. (read (concat "(" (match-string 3) ")")))))
  10362. (save-excursion
  10363. (beginning-of-line 1)
  10364. (skip-chars-forward " \t")
  10365. (setq params (plist-put params :indentation-column (current-column))))
  10366. (unless (re-search-forward org-dblock-end-re nil t)
  10367. (error "Dynamic block not terminated"))
  10368. (setq params
  10369. (append params
  10370. (list :content (buffer-substring
  10371. begdel (match-beginning 0)))))
  10372. (delete-region begdel (match-beginning 0))
  10373. (goto-char begdel)
  10374. (open-line 1)
  10375. params))
  10376. (defun org-map-dblocks (&optional command)
  10377. "Apply COMMAND to all dynamic blocks in the current buffer.
  10378. If COMMAND is not given, use `org-update-dblock'."
  10379. (let ((cmd (or command 'org-update-dblock)))
  10380. (save-excursion
  10381. (goto-char (point-min))
  10382. (while (re-search-forward org-dblock-start-re nil t)
  10383. (goto-char (match-beginning 0))
  10384. (save-excursion
  10385. (condition-case nil
  10386. (funcall cmd)
  10387. (error (message "Error during update of dynamic block"))))
  10388. (unless (re-search-forward org-dblock-end-re nil t)
  10389. (error "Dynamic block not terminated"))))))
  10390. (defun org-dblock-update (&optional arg)
  10391. "User command for updating dynamic blocks.
  10392. Update the dynamic block at point. With prefix ARG, update all dynamic
  10393. blocks in the buffer."
  10394. (interactive "P")
  10395. (if arg
  10396. (org-update-all-dblocks)
  10397. (or (looking-at org-dblock-start-re)
  10398. (org-beginning-of-dblock))
  10399. (org-update-dblock)))
  10400. (defun org-update-dblock ()
  10401. "Update the dynamic block at point.
  10402. This means to empty the block, parse for parameters and then call
  10403. the correct writing function."
  10404. (interactive)
  10405. (save-excursion
  10406. (let* ((win (selected-window))
  10407. (pos (point))
  10408. (line (org-current-line))
  10409. (params (org-prepare-dblock))
  10410. (name (plist-get params :name))
  10411. (indent (plist-get params :indentation-column))
  10412. (cmd (intern (concat "org-dblock-write:" name))))
  10413. (message "Updating dynamic block `%s' at line %d..." name line)
  10414. (funcall cmd params)
  10415. (message "Updating dynamic block `%s' at line %d...done" name line)
  10416. (goto-char pos)
  10417. (when (and indent (> indent 0))
  10418. (setq indent (make-string indent ?\ ))
  10419. (save-excursion
  10420. (select-window win)
  10421. (org-beginning-of-dblock)
  10422. (forward-line 1)
  10423. (while (not (looking-at org-dblock-end-re))
  10424. (insert indent)
  10425. (beginning-of-line 2))
  10426. (when (looking-at org-dblock-end-re)
  10427. (and (looking-at "[ \t]+")
  10428. (replace-match ""))
  10429. (insert indent)))))))
  10430. (defun org-beginning-of-dblock ()
  10431. "Find the beginning of the dynamic block at point.
  10432. Error if there is no such block at point."
  10433. (let ((pos (point))
  10434. beg)
  10435. (end-of-line 1)
  10436. (if (and (re-search-backward org-dblock-start-re nil t)
  10437. (setq beg (match-beginning 0))
  10438. (re-search-forward org-dblock-end-re nil t)
  10439. (> (match-end 0) pos))
  10440. (goto-char beg)
  10441. (goto-char pos)
  10442. (error "Not in a dynamic block"))))
  10443. (defun org-update-all-dblocks ()
  10444. "Update all dynamic blocks in the buffer.
  10445. This function can be used in a hook."
  10446. (interactive)
  10447. (when (derived-mode-p 'org-mode)
  10448. (org-map-dblocks 'org-update-dblock)))
  10449. ;;;; Completion
  10450. (declare-function org-export-backend-options "ox" (cl-x) t)
  10451. (defun org-get-export-keywords ()
  10452. "Return a list of all currently understood export keywords.
  10453. Export keywords include options, block names, attributes and
  10454. keywords relative to each registered export back-end."
  10455. (let (keywords)
  10456. (dolist (backend
  10457. (bound-and-true-p org-export-registered-backends)
  10458. (delq nil keywords))
  10459. ;; Back-end name (for keywords, like #+LATEX:)
  10460. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10461. (dolist (option-entry (org-export-backend-options backend))
  10462. ;; Back-end options.
  10463. (push (nth 1 option-entry) keywords)))))
  10464. (defconst org-options-keywords
  10465. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10466. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10467. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10468. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10469. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10470. (defcustom org-structure-template-alist
  10471. '(("a" . "export ascii")
  10472. ("c" . "center")
  10473. ("C" . "comment")
  10474. ("e" . "example")
  10475. ("E" . "export")
  10476. ("h" . "export html")
  10477. ("l" . "export latex")
  10478. ("q" . "quote")
  10479. ("s" . "src")
  10480. ("v" . "verse"))
  10481. "Structure completion elements.
  10482. This is an alist of keys and block types. With
  10483. `org-insert-structure-template' a block can be inserted through a
  10484. menu. The block type is inserted, with \"#+BEGIN_\" and
  10485. \"#+END_\" added automatically. The menukeys are determined
  10486. based on the key elements in the `org-structure-template-alist'.
  10487. If two entries have the keys \"a\" and \"aa\" respectively, the
  10488. former will be inserted by typing \"a TAB/RET/SPC\" and the
  10489. latter will be inserted by typing \"aa\". If an entry with the
  10490. key \"aab\" is later added it would be inserted by typing \"ab\".
  10491. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  10492. block can be inserted by pressing TAB after the string \"<KEY\".
  10493. "
  10494. :group 'org-edit-structure
  10495. :type '(repeat
  10496. (cons (string :tag "Key")
  10497. (string :tag "Template")))
  10498. :package-version '(Org . "9.2"))
  10499. (defun org--insert-structure-template-mks ()
  10500. "Present `org-structure-template-alist' with `org-mks'.
  10501. Menus are added if keys require more than one keystroke.
  10502. Tabs are added to single key entires when needing more than one stroke.
  10503. Keys longer than two characters are reduced to two characters."
  10504. (let* (case-fold-search
  10505. (templates (append org-structure-template-alist
  10506. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  10507. (keys (mapcar #'car templates))
  10508. (start-letters (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  10509. ;; Sort each element of `org-structure-template-alist' into
  10510. ;; sublists according to the first letter.
  10511. (superlist (mapcar (lambda (letter)
  10512. (list letter
  10513. (cl-remove-if-not
  10514. (apply-partially #'string-match-p (concat "^" letter))
  10515. templates :key #'car)))
  10516. start-letters)))
  10517. (org-mks
  10518. (apply #'append
  10519. ;; Make an `org-mks' table. If only one element is
  10520. ;; present in a sublist, make it part of the top-menu,
  10521. ;; otherwise make a submenu according to the starting
  10522. ;; letter and populate it.
  10523. (mapcar (lambda (sublist)
  10524. (if (eq 1 (length (cadr sublist)))
  10525. (mapcar (lambda (elm)
  10526. (list (substring (car elm) 0 1)
  10527. (cdr elm) ""))
  10528. (cadr sublist))
  10529. ;; Create submenu.
  10530. (let* ((topkey (car sublist))
  10531. (elms (cadr sublist))
  10532. (keys (mapcar #'car elms))
  10533. (long (> (length elms) 3)))
  10534. (append
  10535. (list
  10536. ;; Make a description of the submenu.
  10537. (list topkey
  10538. (concat
  10539. (mapconcat #'cdr
  10540. (cl-subseq elms 0 (if long 3 (length elms)))
  10541. ", ")
  10542. (when long ", ..."))))
  10543. ;; List of entries in submenu.
  10544. (cl-mapcar #'list
  10545. (org--insert-structure-template-unique-keys keys)
  10546. (mapcar #'cdr elms)
  10547. (make-list (length elms) ""))))))
  10548. superlist))
  10549. "Select a key\n============"
  10550. "Key: ")))
  10551. (defun org--insert-structure-template-unique-keys (keys)
  10552. "Make list of unique, two character long elements from KEYS.
  10553. Elements of length one have a tab appended. Elements of length
  10554. two are kept as is. Longer elements are truncated to length two.
  10555. If an element cannot be made unique an error is raised."
  10556. (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  10557. menu-keys)
  10558. (dolist (key orderd-keys)
  10559. (let ((potential-key
  10560. (cl-case (length key)
  10561. (1 (concat key "\t"))
  10562. (2 key)
  10563. (otherwise
  10564. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  10565. (mapcar (apply-partially #'concat (substring key 0 1))
  10566. (split-string (substring key 1) "" t)))))))
  10567. (if (or (not potential-key) (assoc potential-key menu-keys))
  10568. (user-error "Could not make unique key for %s." key)
  10569. (push (cons potential-key key) menu-keys))))
  10570. (mapcar #'car
  10571. (cl-sort menu-keys #'<
  10572. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  10573. (defun org-insert-structure-template (type)
  10574. "Insert a block structure of the type #+begin_foo/#+end_foo.
  10575. First choose a block based on `org-structure-template-alist'.
  10576. Alternatively, type RET, TAB or SPC to write the block type.
  10577. With an active region, wrap the region in the block. Otherwise,
  10578. insert an empty block."
  10579. (interactive
  10580. (list (pcase (org--insert-structure-template-mks)
  10581. (`("\t" . ,_) (read-string "Structure type: "))
  10582. (`(,_ ,choice . ,_) choice))))
  10583. (let* ((region? (use-region-p))
  10584. (col (current-indentation))
  10585. (indent (make-string col ?\s))
  10586. (special? (string-match-p "\\(src\\|export\\)\\'" type))
  10587. (region-string (and region?
  10588. (buffer-substring (region-beginning)
  10589. (region-end))))
  10590. (region-end-blank (and region?
  10591. (save-excursion
  10592. (goto-char (region-end))
  10593. (when (looking-at "[ \t]*$")
  10594. (replace-match "")
  10595. t))))
  10596. s)
  10597. (when region? (delete-region (region-beginning) (region-end)))
  10598. (unless (save-excursion (skip-chars-backward "[ \t]") (bolp))
  10599. (insert "\n"))
  10600. (beginning-of-line)
  10601. (save-excursion
  10602. (insert
  10603. (with-temp-buffer
  10604. (when region?
  10605. (insert region-string "\n")
  10606. (when (string-match-p
  10607. (concat "\\`" (regexp-opt '("example" "export" "src")))
  10608. type)
  10609. (org-escape-code-in-region (point-min) (point-max))))
  10610. (goto-char (point-min))
  10611. ;; Delete trailing white-lines.
  10612. (when region?
  10613. (while (looking-at-p "^[ \t]*$")
  10614. (delete-region (line-beginning-position)
  10615. (line-beginning-position 2))))
  10616. (save-excursion
  10617. (while (not (eobp))
  10618. (unless (looking-at-p indent)
  10619. (insert indent))
  10620. (forward-line)))
  10621. (insert
  10622. indent
  10623. (format "#+begin_%s%s\n" type (if special? " " "")))
  10624. (unless region? (indent-to col))
  10625. (setq s (point))
  10626. (goto-char (point-max))
  10627. (skip-chars-backward "[ \t\n]" s)
  10628. (delete-region (line-end-position) (point-max))
  10629. (insert "\n" indent
  10630. (format "#+end_%s" (car (split-string type)))
  10631. (if region-end-blank "" "\n"))
  10632. (buffer-substring (point-min) (point))))
  10633. (when (and (eobp) (not (bolp))) (insert "\n")))
  10634. (cond (special?
  10635. (end-of-line))
  10636. (t
  10637. (forward-line)
  10638. (skip-chars-forward "[ \t]*")))))
  10639. ;;;; TODO, DEADLINE, Comments
  10640. (defun org-toggle-comment ()
  10641. "Change the COMMENT state of an entry."
  10642. (interactive)
  10643. (save-excursion
  10644. (org-back-to-heading)
  10645. (let ((case-fold-search nil))
  10646. (looking-at org-complex-heading-regexp))
  10647. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  10648. (skip-chars-forward " \t")
  10649. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  10650. (if (org-in-commented-heading-p t)
  10651. (delete-region (point)
  10652. (progn (search-forward " " (line-end-position) 'move)
  10653. (skip-chars-forward " \t")
  10654. (point)))
  10655. (insert org-comment-string)
  10656. (unless (eolp) (insert " ")))))
  10657. (defvar org-last-todo-state-is-todo nil
  10658. "This is non-nil when the last TODO state change led to a TODO state.
  10659. If the last change removed the TODO tag or switched to DONE, then
  10660. this is nil.")
  10661. (defvar org-setting-tags nil) ; dynamically scoped
  10662. (defvar org-todo-setup-filter-hook nil
  10663. "Hook for functions that pre-filter todo specs.
  10664. Each function takes a todo spec and returns either nil or the spec
  10665. transformed into canonical form." )
  10666. (defvar org-todo-get-default-hook nil
  10667. "Hook for functions that get a default item for todo.
  10668. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  10669. nil or a string to be used for the todo mark." )
  10670. (defvar org-agenda-headline-snapshot-before-repeat)
  10671. (defun org-current-effective-time ()
  10672. "Return current time adjusted for `org-extend-today-until' variable."
  10673. (let* ((ct (org-current-time))
  10674. (dct (decode-time ct))
  10675. (ct1
  10676. (cond
  10677. (org-use-last-clock-out-time-as-effective-time
  10678. (or (org-clock-get-last-clock-out-time) ct))
  10679. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  10680. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  10681. (t ct))))
  10682. ct1))
  10683. (defun org-todo-yesterday (&optional arg)
  10684. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  10685. (interactive "P")
  10686. (if (eq major-mode 'org-agenda-mode)
  10687. (apply 'org-agenda-todo-yesterday arg)
  10688. (let* ((org-use-effective-time t)
  10689. (hour (nth 2 (decode-time (org-current-time))))
  10690. (org-extend-today-until (1+ hour)))
  10691. (org-todo arg))))
  10692. (defvar org-block-entry-blocking ""
  10693. "First entry preventing the TODO state change.")
  10694. (defun org-cancel-repeater ()
  10695. "Cancel a repeater by setting its numeric value to zero."
  10696. (interactive)
  10697. (save-excursion
  10698. (org-back-to-heading t)
  10699. (let ((bound1 (point))
  10700. (bound0 (save-excursion (outline-next-heading) (point))))
  10701. (when (and (re-search-forward
  10702. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  10703. org-deadline-time-regexp "\\)\\|\\("
  10704. org-ts-regexp "\\)")
  10705. bound0 t)
  10706. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  10707. bound1 t))
  10708. (replace-match "0" t nil nil 1)))))
  10709. (defvar org-state)
  10710. (defvar org-blocked-by-checkboxes)
  10711. (defun org-todo (&optional arg)
  10712. "Change the TODO state of an item.
  10713. The state of an item is given by a keyword at the start of the heading,
  10714. like
  10715. *** TODO Write paper
  10716. *** DONE Call mom
  10717. The different keywords are specified in the variable `org-todo-keywords'.
  10718. By default the available states are \"TODO\" and \"DONE\". So, for this
  10719. example: when the item starts with TODO, it is changed to DONE.
  10720. When it starts with DONE, the DONE is removed. And when neither TODO nor
  10721. DONE are present, add TODO at the beginning of the heading.
  10722. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  10723. state.
  10724. With numeric prefix ARG, switch to that state.
  10725. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  10726. next set of TODO \
  10727. keywords (nextset).
  10728. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  10729. prefix, circumvent any state blocking.
  10730. With a numeric prefix arg of 0, inhibit note taking for the change.
  10731. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  10732. When called through ELisp, arg is also interpreted in the following way:
  10733. `none' -> empty state
  10734. \"\" -> switch to empty state
  10735. `done' -> switch to DONE
  10736. `nextset' -> switch to the next set of keywords
  10737. `previousset' -> switch to the previous set of keywords
  10738. \"WAITING\" -> switch to the specified keyword, but only if it
  10739. really is a member of `org-todo-keywords'."
  10740. (interactive "P")
  10741. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10742. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10743. 'region-start-level 'region))
  10744. org-loop-over-headlines-in-active-region)
  10745. (org-map-entries
  10746. `(org-todo ,arg)
  10747. org-loop-over-headlines-in-active-region
  10748. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  10749. (when (equal arg '(16)) (setq arg 'nextset))
  10750. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  10751. (let ((org-blocker-hook org-blocker-hook)
  10752. commentp
  10753. case-fold-search)
  10754. (when (equal arg '(64))
  10755. (setq arg nil org-blocker-hook nil))
  10756. (when (and org-blocker-hook
  10757. (or org-inhibit-blocking
  10758. (org-entry-get nil "NOBLOCKING")))
  10759. (setq org-blocker-hook nil))
  10760. (save-excursion
  10761. (catch 'exit
  10762. (org-back-to-heading t)
  10763. (when (org-in-commented-heading-p t)
  10764. (org-toggle-comment)
  10765. (setq commentp t))
  10766. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  10767. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  10768. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  10769. (let* ((match-data (match-data))
  10770. (startpos (copy-marker (line-beginning-position)))
  10771. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  10772. (org-log-done org-log-done)
  10773. (org-log-repeat org-log-repeat)
  10774. (org-todo-log-states org-todo-log-states)
  10775. (org-inhibit-logging
  10776. (if (equal arg 0)
  10777. (progn (setq arg nil) 'note) org-inhibit-logging))
  10778. (this (match-string 1))
  10779. (hl-pos (match-beginning 0))
  10780. (head (org-get-todo-sequence-head this))
  10781. (ass (assoc head org-todo-kwd-alist))
  10782. (interpret (nth 1 ass))
  10783. (done-word (nth 3 ass))
  10784. (final-done-word (nth 4 ass))
  10785. (org-last-state (or this ""))
  10786. (completion-ignore-case t)
  10787. (member (member this org-todo-keywords-1))
  10788. (tail (cdr member))
  10789. (org-state (cond
  10790. ((and org-todo-key-trigger
  10791. (or (and (equal arg '(4))
  10792. (eq org-use-fast-todo-selection 'prefix))
  10793. (and (not arg) org-use-fast-todo-selection
  10794. (not (eq org-use-fast-todo-selection
  10795. 'prefix)))))
  10796. ;; Use fast selection.
  10797. (org-fast-todo-selection))
  10798. ((and (equal arg '(4))
  10799. (or (not org-use-fast-todo-selection)
  10800. (not org-todo-key-trigger)))
  10801. ;; Read a state with completion.
  10802. (completing-read
  10803. "State: " (mapcar #'list org-todo-keywords-1)
  10804. nil t))
  10805. ((eq arg 'right)
  10806. (if this
  10807. (if tail (car tail) nil)
  10808. (car org-todo-keywords-1)))
  10809. ((eq arg 'left)
  10810. (unless (equal member org-todo-keywords-1)
  10811. (if this
  10812. (nth (- (length org-todo-keywords-1)
  10813. (length tail) 2)
  10814. org-todo-keywords-1)
  10815. (org-last org-todo-keywords-1))))
  10816. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  10817. (setq arg nil))) ;hack to fall back to cycling
  10818. (arg
  10819. ;; User or caller requests a specific state.
  10820. (cond
  10821. ((equal arg "") nil)
  10822. ((eq arg 'none) nil)
  10823. ((eq arg 'done) (or done-word (car org-done-keywords)))
  10824. ((eq arg 'nextset)
  10825. (or (car (cdr (member head org-todo-heads)))
  10826. (car org-todo-heads)))
  10827. ((eq arg 'previousset)
  10828. (let ((org-todo-heads (reverse org-todo-heads)))
  10829. (or (car (cdr (member head org-todo-heads)))
  10830. (car org-todo-heads))))
  10831. ((car (member arg org-todo-keywords-1)))
  10832. ((stringp arg)
  10833. (user-error "State `%s' not valid in this file" arg))
  10834. ((nth (1- (prefix-numeric-value arg))
  10835. org-todo-keywords-1))))
  10836. ((null member) (or head (car org-todo-keywords-1)))
  10837. ((equal this final-done-word) nil) ;-> make empty
  10838. ((null tail) nil) ;-> first entry
  10839. ((memq interpret '(type priority))
  10840. (if (eq this-command last-command)
  10841. (car tail)
  10842. (if (> (length tail) 0)
  10843. (or done-word (car org-done-keywords))
  10844. nil)))
  10845. (t
  10846. (car tail))))
  10847. (org-state (or
  10848. (run-hook-with-args-until-success
  10849. 'org-todo-get-default-hook org-state org-last-state)
  10850. org-state))
  10851. (next (if org-state (concat " " org-state " ") " "))
  10852. (change-plist (list :type 'todo-state-change :from this :to org-state
  10853. :position startpos))
  10854. dolog now-done-p)
  10855. (when org-blocker-hook
  10856. (let (org-blocked-by-checkboxes block-reason)
  10857. (setq org-last-todo-state-is-todo
  10858. (not (member this org-done-keywords)))
  10859. (unless (save-excursion
  10860. (save-match-data
  10861. (org-with-wide-buffer
  10862. (run-hook-with-args-until-failure
  10863. 'org-blocker-hook change-plist))))
  10864. (setq block-reason (if org-blocked-by-checkboxes
  10865. "contained checkboxes"
  10866. (format "\"%s\"" org-block-entry-blocking)))
  10867. (if (called-interactively-p 'interactive)
  10868. (user-error "TODO state change from %s to %s blocked (by %s)"
  10869. this org-state block-reason)
  10870. ;; Fail silently.
  10871. (message "TODO state change from %s to %s blocked (by %s)"
  10872. this org-state block-reason)
  10873. (throw 'exit nil)))))
  10874. (store-match-data match-data)
  10875. (replace-match next t t)
  10876. (cond ((equal this org-state)
  10877. (message "TODO state was already %s" (org-trim next)))
  10878. ((not (pos-visible-in-window-p hl-pos))
  10879. (message "TODO state changed to %s" (org-trim next))))
  10880. (unless head
  10881. (setq head (org-get-todo-sequence-head org-state)
  10882. ass (assoc head org-todo-kwd-alist)
  10883. interpret (nth 1 ass)
  10884. done-word (nth 3 ass)
  10885. final-done-word (nth 4 ass)))
  10886. (when (memq arg '(nextset previousset))
  10887. (message "Keyword-Set %d/%d: %s"
  10888. (- (length org-todo-sets) -1
  10889. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  10890. (length org-todo-sets)
  10891. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  10892. (setq org-last-todo-state-is-todo
  10893. (not (member org-state org-done-keywords)))
  10894. (setq now-done-p (and (member org-state org-done-keywords)
  10895. (not (member this org-done-keywords))))
  10896. (and logging (org-local-logging logging))
  10897. (when (and (or org-todo-log-states org-log-done)
  10898. (not (eq org-inhibit-logging t))
  10899. (not (memq arg '(nextset previousset))))
  10900. ;; We need to look at recording a time and note.
  10901. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  10902. (nth 2 (assoc this org-todo-log-states))))
  10903. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  10904. (setq dolog 'time))
  10905. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  10906. (and org-state
  10907. (member org-state org-not-done-keywords)
  10908. (not (member this org-not-done-keywords))))
  10909. ;; This is now a todo state and was not one before
  10910. ;; If there was a CLOSED time stamp, get rid of it.
  10911. (org-add-planning-info nil nil 'closed))
  10912. (when (and now-done-p org-log-done)
  10913. ;; It is now done, and it was not done before.
  10914. (org-add-planning-info 'closed (org-current-effective-time))
  10915. (when (and (not dolog) (eq 'note org-log-done))
  10916. (org-add-log-setup 'done org-state this 'note)))
  10917. (when (and org-state dolog)
  10918. ;; This is a non-nil state, and we need to log it.
  10919. (org-add-log-setup 'state org-state this dolog)))
  10920. ;; Fixup tag positioning.
  10921. (org-todo-trigger-tag-changes org-state)
  10922. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  10923. (when org-provide-todo-statistics
  10924. (org-update-parent-todo-statistics))
  10925. (run-hooks 'org-after-todo-state-change-hook)
  10926. (when (and arg (not (member org-state org-done-keywords)))
  10927. (setq head (org-get-todo-sequence-head org-state)))
  10928. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  10929. ;; Do we need to trigger a repeat?
  10930. (when now-done-p
  10931. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  10932. ;; This is for the agenda, take a snapshot of the headline.
  10933. (save-match-data
  10934. (setq org-agenda-headline-snapshot-before-repeat
  10935. (org-get-heading))))
  10936. (org-auto-repeat-maybe org-state))
  10937. ;; Fixup cursor location if close to the keyword.
  10938. (when (and (outline-on-heading-p)
  10939. (not (bolp))
  10940. (save-excursion (beginning-of-line 1)
  10941. (looking-at org-todo-line-regexp))
  10942. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  10943. (goto-char (or (match-end 2) (match-end 1)))
  10944. (and (looking-at " ") (just-one-space)))
  10945. (when org-trigger-hook
  10946. (save-excursion
  10947. (run-hook-with-args 'org-trigger-hook change-plist)))
  10948. (when commentp (org-toggle-comment))))))))
  10949. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  10950. "Block turning an entry into a TODO, using the hierarchy.
  10951. This checks whether the current task should be blocked from state
  10952. changes. Such blocking occurs when:
  10953. 1. The task has children which are not all in a completed state.
  10954. 2. A task has a parent with the property :ORDERED:, and there
  10955. are siblings prior to the current task with incomplete
  10956. status.
  10957. 3. The parent of the task is blocked because it has siblings that should
  10958. be done first, or is child of a block grandparent TODO entry."
  10959. (if (not org-enforce-todo-dependencies)
  10960. t ; if locally turned off don't block
  10961. (catch 'dont-block
  10962. ;; If this is not a todo state change, or if this entry is already DONE,
  10963. ;; do not block
  10964. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  10965. (member (plist-get change-plist :from)
  10966. (cons 'done org-done-keywords))
  10967. (member (plist-get change-plist :to)
  10968. (cons 'todo org-not-done-keywords))
  10969. (not (plist-get change-plist :to)))
  10970. (throw 'dont-block t))
  10971. ;; If this task has children, and any are undone, it's blocked
  10972. (save-excursion
  10973. (org-back-to-heading t)
  10974. (let ((this-level (funcall outline-level)))
  10975. (outline-next-heading)
  10976. (let ((child-level (funcall outline-level)))
  10977. (while (and (not (eobp))
  10978. (> child-level this-level))
  10979. ;; this todo has children, check whether they are all
  10980. ;; completed
  10981. (when (and (not (org-entry-is-done-p))
  10982. (org-entry-is-todo-p))
  10983. (setq org-block-entry-blocking (org-get-heading))
  10984. (throw 'dont-block nil))
  10985. (outline-next-heading)
  10986. (setq child-level (funcall outline-level))))))
  10987. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  10988. ;; any previous siblings are undone, it's blocked
  10989. (save-excursion
  10990. (org-back-to-heading t)
  10991. (let* ((pos (point))
  10992. (parent-pos (and (org-up-heading-safe) (point)))
  10993. (case-fold-search nil))
  10994. (unless parent-pos (throw 'dont-block t)) ; no parent
  10995. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  10996. (forward-line 1)
  10997. (re-search-forward org-not-done-heading-regexp pos t))
  10998. (setq org-block-entry-blocking (match-string 0))
  10999. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11000. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11001. (while t
  11002. (goto-char parent-pos)
  11003. (unless (looking-at org-not-done-heading-regexp)
  11004. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11005. (setq pos (point))
  11006. (setq parent-pos (and (org-up-heading-safe) (point)))
  11007. (unless parent-pos (throw 'dont-block t)) ; no parent
  11008. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11009. (forward-line 1)
  11010. (re-search-forward org-not-done-heading-regexp pos t)
  11011. (setq org-block-entry-blocking (org-get-heading)))
  11012. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11013. (defcustom org-track-ordered-property-with-tag nil
  11014. "Should the ORDERED property also be shown as a tag?
  11015. The ORDERED property decides if an entry should require subtasks to be
  11016. completed in sequence. Since a property is not very visible, setting
  11017. this option means that toggling the ORDERED property with the command
  11018. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11019. not relevant for the behavior, but it makes things more visible.
  11020. Note that toggling the tag with tags commands will not change the property
  11021. and therefore not influence behavior!
  11022. This can be t, meaning the tag ORDERED should be used, It can also be a
  11023. string to select a different tag for this task."
  11024. :group 'org-todo
  11025. :type '(choice
  11026. (const :tag "No tracking" nil)
  11027. (const :tag "Track with ORDERED tag" t)
  11028. (string :tag "Use other tag")))
  11029. (defun org-toggle-ordered-property ()
  11030. "Toggle the ORDERED property of the current entry.
  11031. For better visibility, you can track the value of this property with a tag.
  11032. See variable `org-track-ordered-property-with-tag'."
  11033. (interactive)
  11034. (let* ((t1 org-track-ordered-property-with-tag)
  11035. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11036. (save-excursion
  11037. (org-back-to-heading)
  11038. (if (org-entry-get nil "ORDERED")
  11039. (progn
  11040. (org-delete-property "ORDERED")
  11041. (and tag (org-toggle-tag tag 'off))
  11042. (message "Subtasks can be completed in arbitrary order"))
  11043. (org-entry-put nil "ORDERED" "t")
  11044. (and tag (org-toggle-tag tag 'on))
  11045. (message "Subtasks must be completed in sequence")))))
  11046. (defun org-block-todo-from-checkboxes (change-plist)
  11047. "Block turning an entry into a TODO, using checkboxes.
  11048. This checks whether the current task should be blocked from state
  11049. changes because there are unchecked boxes in this entry."
  11050. (if (not org-enforce-todo-checkbox-dependencies)
  11051. t ; if locally turned off don't block
  11052. (catch 'dont-block
  11053. ;; If this is not a todo state change, or if this entry is already DONE,
  11054. ;; do not block
  11055. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11056. (member (plist-get change-plist :from)
  11057. (cons 'done org-done-keywords))
  11058. (member (plist-get change-plist :to)
  11059. (cons 'todo org-not-done-keywords))
  11060. (not (plist-get change-plist :to)))
  11061. (throw 'dont-block t))
  11062. ;; If this task has checkboxes that are not checked, it's blocked
  11063. (save-excursion
  11064. (org-back-to-heading t)
  11065. (let ((beg (point)) end)
  11066. (outline-next-heading)
  11067. (setq end (point))
  11068. (goto-char beg)
  11069. (when (org-list-search-forward
  11070. (concat (org-item-beginning-re)
  11071. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11072. "\\[[- ]\\]")
  11073. end t)
  11074. (when (boundp 'org-blocked-by-checkboxes)
  11075. (setq org-blocked-by-checkboxes t))
  11076. (throw 'dont-block nil))))
  11077. t))) ; do not block
  11078. (defun org-entry-blocked-p ()
  11079. "Non-nil if entry at point is blocked."
  11080. (and (not (org-entry-get nil "NOBLOCKING"))
  11081. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11082. (not (run-hook-with-args-until-failure
  11083. 'org-blocker-hook
  11084. (list :type 'todo-state-change
  11085. :position (point)
  11086. :from 'todo
  11087. :to 'done)))))
  11088. (defun org-update-statistics-cookies (all)
  11089. "Update the statistics cookie, either from TODO or from checkboxes.
  11090. This should be called with the cursor in a line with a statistics
  11091. cookie. When called with a \\[universal-argument] prefix, update
  11092. all statistics cookies in the buffer."
  11093. (interactive "P")
  11094. (if all
  11095. (progn
  11096. (org-update-checkbox-count 'all)
  11097. (org-map-entries 'org-update-parent-todo-statistics))
  11098. (if (not (org-at-heading-p))
  11099. (org-update-checkbox-count)
  11100. (let ((pos (point-marker))
  11101. end l1 l2)
  11102. (ignore-errors (org-back-to-heading t))
  11103. (if (not (org-at-heading-p))
  11104. (org-update-checkbox-count)
  11105. (setq l1 (org-outline-level))
  11106. (setq end (save-excursion
  11107. (outline-next-heading)
  11108. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11109. (point)))
  11110. (if (and (save-excursion
  11111. (re-search-forward
  11112. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11113. (not (save-excursion (re-search-forward
  11114. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11115. (org-update-checkbox-count)
  11116. (if (and l2 (> l2 l1))
  11117. (progn
  11118. (goto-char end)
  11119. (org-update-parent-todo-statistics))
  11120. (goto-char pos)
  11121. (beginning-of-line 1)
  11122. (while (re-search-forward
  11123. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11124. (point-at-eol) t)
  11125. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11126. (goto-char pos)
  11127. (move-marker pos nil)))))
  11128. (defvar org-entry-property-inherited-from) ;; defined below
  11129. (defun org-update-parent-todo-statistics ()
  11130. "Update any statistics cookie in the parent of the current headline.
  11131. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11132. the entire subtree and this will travel up the hierarchy and update
  11133. statistics everywhere."
  11134. (let* ((prop (save-excursion (org-up-heading-safe)
  11135. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11136. (recursive (or (not org-hierarchical-todo-statistics)
  11137. (and prop (string-match "\\<recursive\\>" prop))))
  11138. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11139. 0))
  11140. (first t)
  11141. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11142. level ltoggle l1 new ndel
  11143. (cnt-all 0) (cnt-done 0) is-percent kwd
  11144. checkbox-beg cookie-present)
  11145. (catch 'exit
  11146. (save-excursion
  11147. (beginning-of-line 1)
  11148. (setq ltoggle (funcall outline-level))
  11149. ;; Three situations are to consider:
  11150. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11151. ;; to the top-level ancestor on the headline;
  11152. ;; 2. If parent has "recursive" property, repeat up to the
  11153. ;; headline setting that property, taking inheritance into
  11154. ;; account;
  11155. ;; 3. Else, move up to direct parent and proceed only once.
  11156. (while (and (setq level (org-up-heading-safe))
  11157. (or recursive first)
  11158. (>= (point) lim))
  11159. (setq first nil cookie-present nil)
  11160. (unless (and level
  11161. (not (string-match
  11162. "\\<checkbox\\>"
  11163. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11164. "")))))
  11165. (throw 'exit nil))
  11166. (while (re-search-forward box-re (point-at-eol) t)
  11167. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11168. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11169. (save-match-data
  11170. (unless (outline-next-heading) (throw 'exit nil))
  11171. (while (and (looking-at org-complex-heading-regexp)
  11172. (> (setq l1 (length (match-string 1))) level))
  11173. (setq kwd (and (or recursive (= l1 ltoggle))
  11174. (match-string 2)))
  11175. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11176. (and (eq org-provide-todo-statistics t)
  11177. (or (member kwd org-done-keywords)))
  11178. (and (listp org-provide-todo-statistics)
  11179. (stringp (car org-provide-todo-statistics))
  11180. (or (member kwd org-provide-todo-statistics)
  11181. (member kwd org-done-keywords)))
  11182. (and (listp org-provide-todo-statistics)
  11183. (listp (car org-provide-todo-statistics))
  11184. (or (member kwd (car org-provide-todo-statistics))
  11185. (and (member kwd org-done-keywords)
  11186. (member kwd (cadr org-provide-todo-statistics))))))
  11187. (setq cnt-all (1+ cnt-all))
  11188. (and (eq org-provide-todo-statistics t)
  11189. kwd
  11190. (setq cnt-all (1+ cnt-all))))
  11191. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11192. (member kwd org-done-keywords))
  11193. (and (listp org-provide-todo-statistics)
  11194. (listp (car org-provide-todo-statistics))
  11195. (member kwd org-done-keywords)
  11196. (member kwd (cadr org-provide-todo-statistics)))
  11197. (and (listp org-provide-todo-statistics)
  11198. (stringp (car org-provide-todo-statistics))
  11199. (member kwd org-done-keywords)))
  11200. (setq cnt-done (1+ cnt-done)))
  11201. (outline-next-heading)))
  11202. (setq new
  11203. (if is-percent
  11204. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11205. (max 1 cnt-all)))
  11206. (format "[%d/%d]" cnt-done cnt-all))
  11207. ndel (- (match-end 0) checkbox-beg))
  11208. (goto-char checkbox-beg)
  11209. (insert new)
  11210. (delete-region (point) (+ (point) ndel))
  11211. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11212. (when cookie-present
  11213. (run-hook-with-args 'org-after-todo-statistics-hook
  11214. cnt-done (- cnt-all cnt-done))))))
  11215. (run-hooks 'org-todo-statistics-hook)))
  11216. (defvar org-after-todo-statistics-hook nil
  11217. "Hook that is called after a TODO statistics cookie has been updated.
  11218. Each function is called with two arguments: the number of not-done entries
  11219. and the number of done entries.
  11220. For example, the following function, when added to this hook, will switch
  11221. an entry to DONE when all children are done, and back to TODO when new
  11222. entries are set to a TODO status. Note that this hook is only called
  11223. when there is a statistics cookie in the headline!
  11224. (defun org-summary-todo (n-done n-not-done)
  11225. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11226. (let (org-log-done org-log-states) ; turn off logging
  11227. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11228. ")
  11229. (defvar org-todo-statistics-hook nil
  11230. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11231. This hook runs even if there is no statistics cookie present, in which case
  11232. `org-after-todo-statistics-hook' would not run.")
  11233. (defun org-todo-trigger-tag-changes (state)
  11234. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11235. (let ((l org-todo-state-tags-triggers)
  11236. changes)
  11237. (when (or (not state) (equal state ""))
  11238. (setq changes (append changes (cdr (assoc "" l)))))
  11239. (when (and (stringp state) (> (length state) 0))
  11240. (setq changes (append changes (cdr (assoc state l)))))
  11241. (when (member state org-not-done-keywords)
  11242. (setq changes (append changes (cdr (assq 'todo l)))))
  11243. (when (member state org-done-keywords)
  11244. (setq changes (append changes (cdr (assq 'done l)))))
  11245. (dolist (c changes)
  11246. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11247. (defun org-local-logging (value)
  11248. "Get logging settings from a property VALUE."
  11249. ;; Directly set the variables, they are already local.
  11250. (setq org-log-done nil
  11251. org-log-repeat nil
  11252. org-todo-log-states nil)
  11253. (dolist (w (split-string value))
  11254. (let (a)
  11255. (cond
  11256. ((setq a (assoc w org-startup-options))
  11257. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11258. (set (nth 1 a) (nth 2 a))))
  11259. ((setq a (org-extract-log-state-settings w))
  11260. (and (member (car a) org-todo-keywords-1)
  11261. (push a org-todo-log-states)))))))
  11262. (defun org-get-todo-sequence-head (kwd)
  11263. "Return the head of the TODO sequence to which KWD belongs.
  11264. If KWD is not set, check if there is a text property remembering the
  11265. right sequence."
  11266. (let (p)
  11267. (cond
  11268. ((not kwd)
  11269. (or (get-text-property (point-at-bol) 'org-todo-head)
  11270. (progn
  11271. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11272. nil (point-at-eol)))
  11273. (get-text-property p 'org-todo-head))))
  11274. ((not (member kwd org-todo-keywords-1))
  11275. (car org-todo-keywords-1))
  11276. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11277. (defun org-fast-todo-selection ()
  11278. "Fast TODO keyword selection with single keys.
  11279. Returns the new TODO keyword, or nil if no state change should occur."
  11280. (let* ((fulltable org-todo-key-alist)
  11281. (done-keywords org-done-keywords) ;; needed for the faces.
  11282. (maxlen (apply 'max (mapcar
  11283. (lambda (x)
  11284. (if (stringp (car x)) (string-width (car x)) 0))
  11285. fulltable)))
  11286. (expert nil)
  11287. (fwidth (+ maxlen 3 1 3))
  11288. (ncol (/ (- (window-width) 4) fwidth))
  11289. tg cnt e c tbl
  11290. groups ingroup)
  11291. (save-excursion
  11292. (save-window-excursion
  11293. (if expert
  11294. (set-buffer (get-buffer-create " *Org todo*"))
  11295. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11296. (erase-buffer)
  11297. (setq-local org-done-keywords done-keywords)
  11298. (setq tbl fulltable cnt 0)
  11299. (while (setq e (pop tbl))
  11300. (cond
  11301. ((equal e '(:startgroup))
  11302. (push '() groups) (setq ingroup t)
  11303. (unless (= cnt 0)
  11304. (setq cnt 0)
  11305. (insert "\n"))
  11306. (insert "{ "))
  11307. ((equal e '(:endgroup))
  11308. (setq ingroup nil cnt 0)
  11309. (insert "}\n"))
  11310. ((equal e '(:newline))
  11311. (unless (= cnt 0)
  11312. (setq cnt 0)
  11313. (insert "\n")
  11314. (setq e (car tbl))
  11315. (while (equal (car tbl) '(:newline))
  11316. (insert "\n")
  11317. (setq tbl (cdr tbl)))))
  11318. (t
  11319. (setq tg (car e) c (cdr e))
  11320. (when ingroup (push tg (car groups)))
  11321. (setq tg (org-add-props tg nil 'face
  11322. (org-get-todo-face tg)))
  11323. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11324. (insert "[" c "] " tg (make-string
  11325. (- fwidth 4 (length tg)) ?\ ))
  11326. (when (= (setq cnt (1+ cnt)) ncol)
  11327. (insert "\n")
  11328. (when ingroup (insert " "))
  11329. (setq cnt 0)))))
  11330. (insert "\n")
  11331. (goto-char (point-min))
  11332. (unless expert (org-fit-window-to-buffer))
  11333. (message "[a-z..]:Set [SPC]:clear")
  11334. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11335. (cond
  11336. ((or (= c ?\C-g)
  11337. (and (= c ?q) (not (rassoc c fulltable))))
  11338. (setq quit-flag t))
  11339. ((= c ?\ ) nil)
  11340. ((setq e (rassoc c fulltable) tg (car e))
  11341. tg)
  11342. (t (setq quit-flag t)))))))
  11343. (defun org-entry-is-todo-p ()
  11344. (member (org-get-todo-state) org-not-done-keywords))
  11345. (defun org-entry-is-done-p ()
  11346. (member (org-get-todo-state) org-done-keywords))
  11347. (defun org-get-todo-state ()
  11348. "Return the TODO keyword of the current subtree."
  11349. (save-excursion
  11350. (org-back-to-heading t)
  11351. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11352. (match-end 2)
  11353. (match-string 2))))
  11354. (defun org-at-date-range-p (&optional inactive-ok)
  11355. "Non-nil if point is inside a date range.
  11356. When optional argument INACTIVE-OK is non-nil, also consider
  11357. inactive time ranges.
  11358. When this function returns a non-nil value, match data is set
  11359. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11360. on INACTIVE-OK."
  11361. (interactive)
  11362. (save-excursion
  11363. (catch 'exit
  11364. (let ((pos (point)))
  11365. (skip-chars-backward "^[<\r\n")
  11366. (skip-chars-backward "<[")
  11367. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11368. (>= (match-end 0) pos)
  11369. (throw 'exit t))
  11370. (skip-chars-backward "^<[\r\n")
  11371. (skip-chars-backward "<[")
  11372. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11373. (>= (match-end 0) pos)
  11374. (throw 'exit t)))
  11375. nil)))
  11376. (defun org-get-repeat (&optional timestamp)
  11377. "Check if there is a time-stamp with repeater in this entry.
  11378. Return the repeater, as a string, or nil. Also return nil when
  11379. this function is called before first heading.
  11380. When optional argument TIMESTAMP is a string, extract the
  11381. repeater from there instead."
  11382. (save-match-data
  11383. (cond (timestamp
  11384. (and (string-match org-repeat-re timestamp)
  11385. (match-string-no-properties 1 timestamp)))
  11386. ((org-before-first-heading-p) nil)
  11387. (t
  11388. (save-excursion
  11389. (org-back-to-heading t)
  11390. (let ((end (org-entry-end-position)))
  11391. (catch :repeat
  11392. (while (re-search-forward org-repeat-re end t)
  11393. (when (save-match-data (org-at-timestamp-p 'agenda))
  11394. (throw :repeat (match-string-no-properties 1)))))))))))
  11395. (defvar org-last-changed-timestamp)
  11396. (defvar org-last-inserted-timestamp)
  11397. (defvar org-log-post-message)
  11398. (defvar org-log-note-purpose)
  11399. (defvar org-log-note-how nil)
  11400. (defvar org-log-note-extra)
  11401. (defun org-auto-repeat-maybe (done-word)
  11402. "Check if the current headline contains a repeated time-stamp.
  11403. If yes, set TODO state back to what it was and change the base date
  11404. of repeating deadline/scheduled time stamps to new date.
  11405. This function is run automatically after each state change to a DONE state."
  11406. (let* ((repeat (org-get-repeat))
  11407. (aa (assoc org-last-state org-todo-kwd-alist))
  11408. (interpret (nth 1 aa))
  11409. (head (nth 2 aa))
  11410. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11411. (msg "Entry repeats: ")
  11412. (org-log-done nil)
  11413. (org-todo-log-states nil)
  11414. (end (copy-marker (org-entry-end-position))))
  11415. (unwind-protect
  11416. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11417. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11418. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11419. (and (stringp org-todo-repeat-to-state)
  11420. org-todo-repeat-to-state)
  11421. (and org-todo-repeat-to-state org-last-state))))
  11422. (org-todo (cond
  11423. ((and to-state (member to-state org-todo-keywords-1))
  11424. to-state)
  11425. ((eq interpret 'type) org-last-state)
  11426. (head)
  11427. (t 'none))))
  11428. (org-back-to-heading t)
  11429. (org-add-planning-info nil nil 'closed)
  11430. ;; When `org-log-repeat' is non-nil or entry contains
  11431. ;; a clock, set LAST_REPEAT property.
  11432. (when (or org-log-repeat
  11433. (catch :clock
  11434. (save-excursion
  11435. (while (re-search-forward org-clock-line-re end t)
  11436. (when (org-at-clock-log-p) (throw :clock t))))))
  11437. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11438. (org-time-stamp-format t t)
  11439. (current-time))))
  11440. (when org-log-repeat
  11441. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11442. (memq 'org-add-log-note post-command-hook))
  11443. ;; We are already setup for some record.
  11444. (when (eq org-log-repeat 'note)
  11445. ;; Make sure we take a note, not only a time stamp.
  11446. (setq org-log-note-how 'note))
  11447. ;; Set up for taking a record.
  11448. (org-add-log-setup 'state
  11449. (or done-word (car org-done-keywords))
  11450. org-last-state
  11451. org-log-repeat)))
  11452. (let ((planning-re (regexp-opt
  11453. (list org-scheduled-string org-deadline-string))))
  11454. (while (re-search-forward org-ts-regexp end t)
  11455. (let* ((ts (match-string 0))
  11456. (planning? (org-at-planning-p))
  11457. (type (if (not planning?) "Plain:"
  11458. (save-excursion
  11459. (re-search-backward
  11460. planning-re (line-beginning-position) t)
  11461. (match-string 0)))))
  11462. (cond
  11463. ;; Ignore fake time-stamps (e.g., within comments).
  11464. ((not (org-at-timestamp-p 'agenda)))
  11465. ;; Time-stamps without a repeater are usually
  11466. ;; skipped. However, a SCHEDULED time-stamp without
  11467. ;; one is removed, as they are no longer relevant.
  11468. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11469. ts))
  11470. (when (equal type org-scheduled-string)
  11471. (org-remove-timestamp-with-keyword type)))
  11472. (t
  11473. (let ((n (string-to-number (match-string 2 ts)))
  11474. (what (match-string 3 ts)))
  11475. (when (equal what "w") (setq n (* n 7) what "d"))
  11476. (when (and (equal what "h")
  11477. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11478. ts)))
  11479. (user-error
  11480. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11481. has been set"
  11482. n))
  11483. ;; Preparation, see if we need to modify the start
  11484. ;; date for the change.
  11485. (when (match-end 1)
  11486. (let ((time (save-match-data
  11487. (org-time-string-to-time ts))))
  11488. (cond
  11489. ((equal (match-string 1 ts) ".")
  11490. ;; Shift starting date to today
  11491. (org-timestamp-change
  11492. (- (org-today) (time-to-days time))
  11493. 'day))
  11494. ((equal (match-string 1 ts) "+")
  11495. (let ((nshiftmax 10)
  11496. (nshift 0))
  11497. (while (or (= nshift 0)
  11498. (not (time-less-p (current-time) time)))
  11499. (when (= (cl-incf nshift) nshiftmax)
  11500. (or (y-or-n-p
  11501. (format "%d repeater intervals were not \
  11502. enough to shift date past today. Continue? "
  11503. nshift))
  11504. (user-error "Abort")))
  11505. (org-timestamp-change n (cdr (assoc what whata)))
  11506. (org-in-regexp org-ts-regexp3)
  11507. (setq ts (match-string 1))
  11508. (setq time
  11509. (save-match-data
  11510. (org-time-string-to-time ts)))))
  11511. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11512. ;; Rematch, so that we have everything in place
  11513. ;; for the real shift.
  11514. (org-in-regexp org-ts-regexp3)
  11515. (setq ts (match-string 1))
  11516. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11517. ts)))))
  11518. (save-excursion
  11519. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11520. (setq msg
  11521. (concat
  11522. msg type " " org-last-changed-timestamp " "))))))))
  11523. (setq org-log-post-message msg)
  11524. (message "%s" msg))
  11525. (set-marker end nil))))
  11526. (defun org-show-todo-tree (arg)
  11527. "Make a compact tree which shows all headlines marked with TODO.
  11528. The tree will show the lines where the regexp matches, and all higher
  11529. headlines above the match.
  11530. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11531. With a numeric prefix N, construct a sparse tree for the Nth element
  11532. of `org-todo-keywords-1'."
  11533. (interactive "P")
  11534. (let ((case-fold-search nil)
  11535. (kwd-re
  11536. (cond ((null arg) org-not-done-regexp)
  11537. ((equal arg '(4))
  11538. (let ((kwd
  11539. (completing-read "Keyword (or KWD1|KWD2|...): "
  11540. (mapcar #'list org-todo-keywords-1))))
  11541. (concat "\\("
  11542. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11543. "\\)\\>")))
  11544. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11545. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11546. org-todo-keywords-1)))
  11547. (t (user-error "Invalid prefix argument: %s" arg)))))
  11548. (message "%d TODO entries found"
  11549. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11550. (defun org--deadline-or-schedule (arg type time)
  11551. "Insert DEADLINE or SCHEDULE information in current entry.
  11552. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11553. `org-schedule' for information about ARG and TIME arguments."
  11554. (let* ((deadline? (eq type 'deadline))
  11555. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11556. (log (if deadline? org-log-redeadline org-log-reschedule))
  11557. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11558. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11559. ;; Save repeater cookie from either TIME or current scheduled
  11560. ;; time stamp. We are going to insert it back at the end of
  11561. ;; the process.
  11562. (repeater (or (and (org-string-nw-p time)
  11563. ;; We use `org-repeat-re' because we need
  11564. ;; to tell the difference between a real
  11565. ;; repeater and a time delta, e.g. "+2d".
  11566. (string-match org-repeat-re time)
  11567. (match-string 1 time))
  11568. (and (org-string-nw-p old-date)
  11569. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11570. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11571. old-date)
  11572. (match-string 1 old-date)))))
  11573. (pcase arg
  11574. (`(4)
  11575. (when (and old-date log)
  11576. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11577. nil old-date log))
  11578. (org-remove-timestamp-with-keyword keyword)
  11579. (message (if deadline? "Item no longer has a deadline."
  11580. "Item is no longer scheduled.")))
  11581. (`(16)
  11582. (save-excursion
  11583. (org-back-to-heading t)
  11584. (let ((regexp (if deadline? org-deadline-time-regexp
  11585. org-scheduled-time-regexp)))
  11586. (if (not (re-search-forward regexp (line-end-position 2) t))
  11587. (user-error (if deadline? "No deadline information to update"
  11588. "No scheduled information to update"))
  11589. (let* ((rpl0 (match-string 1))
  11590. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  11591. (msg (if deadline? "Warn starting from" "Delay until")))
  11592. (replace-match
  11593. (concat keyword
  11594. " <" rpl
  11595. (format " -%dd"
  11596. (abs (- (time-to-days
  11597. (save-match-data
  11598. (org-read-date
  11599. nil t nil msg old-date-time)))
  11600. (time-to-days old-date-time))))
  11601. ">") t t))))))
  11602. (_
  11603. (org-add-planning-info type time 'closed)
  11604. (when (and old-date
  11605. log
  11606. (not (equal old-date org-last-inserted-timestamp)))
  11607. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  11608. org-last-inserted-timestamp
  11609. old-date
  11610. log))
  11611. (when repeater
  11612. (save-excursion
  11613. (org-back-to-heading t)
  11614. (when (re-search-forward
  11615. (concat keyword " " org-last-inserted-timestamp)
  11616. (line-end-position 2)
  11617. t)
  11618. (goto-char (1- (match-end 0)))
  11619. (insert " " repeater)
  11620. (setq org-last-inserted-timestamp
  11621. (concat (substring org-last-inserted-timestamp 0 -1)
  11622. " " repeater
  11623. (substring org-last-inserted-timestamp -1))))))
  11624. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  11625. org-last-inserted-timestamp)))))
  11626. (defun org-deadline (arg &optional time)
  11627. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  11628. With one universal prefix argument, remove any deadline from the item.
  11629. With two universal prefix arguments, prompt for a warning delay.
  11630. With argument TIME, set the deadline at the corresponding date. TIME
  11631. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11632. (interactive "P")
  11633. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11634. (org-map-entries
  11635. (lambda () (org--deadline-or-schedule arg 'deadline time))
  11636. nil
  11637. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11638. 'region-start-level
  11639. 'region)
  11640. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11641. (org--deadline-or-schedule arg 'deadline time)))
  11642. (defun org-schedule (arg &optional time)
  11643. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  11644. With one universal prefix argument, remove any scheduling date from the item.
  11645. With two universal prefix arguments, prompt for a delay cookie.
  11646. With argument TIME, scheduled at the corresponding date. TIME can
  11647. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11648. (interactive "P")
  11649. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11650. (org-map-entries
  11651. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  11652. nil
  11653. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11654. 'region-start-level
  11655. 'region)
  11656. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11657. (org--deadline-or-schedule arg 'scheduled time)))
  11658. (defun org-get-scheduled-time (pom &optional inherit)
  11659. "Get the scheduled time as a time tuple, of a format suitable
  11660. for calling org-schedule with, or if there is no scheduling,
  11661. returns nil."
  11662. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  11663. (when time
  11664. (apply 'encode-time (org-parse-time-string time)))))
  11665. (defun org-get-deadline-time (pom &optional inherit)
  11666. "Get the deadline as a time tuple, of a format suitable for
  11667. calling org-deadline with, or if there is no scheduling, returns
  11668. nil."
  11669. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  11670. (when time
  11671. (apply 'encode-time (org-parse-time-string time)))))
  11672. (defun org-remove-timestamp-with-keyword (keyword)
  11673. "Remove all time stamps with KEYWORD in the current entry."
  11674. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  11675. beg)
  11676. (save-excursion
  11677. (org-back-to-heading t)
  11678. (setq beg (point))
  11679. (outline-next-heading)
  11680. (while (re-search-backward re beg t)
  11681. (replace-match "")
  11682. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  11683. (equal (char-before) ?\ ))
  11684. (backward-delete-char 1)
  11685. (when (string-match "^[ \t]*$" (buffer-substring
  11686. (point-at-bol) (point-at-eol)))
  11687. (delete-region (point-at-bol)
  11688. (min (point-max) (1+ (point-at-eol))))))))))
  11689. (defvar org-time-was-given) ; dynamically scoped parameter
  11690. (defvar org-end-time-was-given) ; dynamically scoped parameter
  11691. (defun org-at-planning-p ()
  11692. "Non-nil when point is on a planning info line."
  11693. ;; This is as accurate and faster than `org-element-at-point' since
  11694. ;; planning info location is fixed in the section.
  11695. (org-with-wide-buffer
  11696. (beginning-of-line)
  11697. (and (looking-at-p org-planning-line-re)
  11698. (eq (point)
  11699. (ignore-errors
  11700. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  11701. (org-back-to-heading t)
  11702. (org-with-limited-levels (org-back-to-heading t)))
  11703. (line-beginning-position 2))))))
  11704. (defun org-add-planning-info (what &optional time &rest remove)
  11705. "Insert new timestamp with keyword in the planning line.
  11706. WHAT indicates what kind of time stamp to add. It is a symbol
  11707. among `closed', `deadline', `scheduled' and nil. TIME indicates
  11708. the time to use. If none is given, the user is prompted for
  11709. a date. REMOVE indicates what kind of entries to remove. An old
  11710. WHAT entry will also be removed."
  11711. (let (org-time-was-given org-end-time-was-given default-time default-input)
  11712. (catch 'exit
  11713. (when (and (memq what '(scheduled deadline))
  11714. (or (not time)
  11715. (and (stringp time)
  11716. (string-match "^[-+]+[0-9]" time))))
  11717. ;; Try to get a default date/time from existing timestamp
  11718. (save-excursion
  11719. (org-back-to-heading t)
  11720. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  11721. (when (re-search-forward (if (eq what 'scheduled)
  11722. org-scheduled-time-regexp
  11723. org-deadline-time-regexp)
  11724. end t)
  11725. (setq ts (match-string 1)
  11726. default-time (apply 'encode-time (org-parse-time-string ts))
  11727. default-input (and ts (org-get-compact-tod ts)))))))
  11728. (when what
  11729. (setq time
  11730. (if (stringp time)
  11731. ;; This is a string (relative or absolute), set
  11732. ;; proper date.
  11733. (apply #'encode-time
  11734. (org-read-date-analyze
  11735. time default-time (decode-time default-time)))
  11736. ;; If necessary, get the time from the user
  11737. (or time (org-read-date nil 'to-time nil nil
  11738. default-time default-input)))))
  11739. (org-with-wide-buffer
  11740. (org-back-to-heading t)
  11741. (forward-line)
  11742. (unless (bolp) (insert "\n"))
  11743. (cond ((looking-at-p org-planning-line-re)
  11744. ;; Move to current indentation.
  11745. (skip-chars-forward " \t")
  11746. ;; Check if we have to remove something.
  11747. (dolist (type (if what (cons what remove) remove))
  11748. (save-excursion
  11749. (when (re-search-forward
  11750. (cl-case type
  11751. (closed org-closed-time-regexp)
  11752. (deadline org-deadline-time-regexp)
  11753. (scheduled org-scheduled-time-regexp)
  11754. (otherwise
  11755. (error "Invalid planning type: %s" type)))
  11756. (line-end-position) t)
  11757. ;; Delete until next keyword or end of line.
  11758. (delete-region
  11759. (match-beginning 0)
  11760. (if (re-search-forward org-keyword-time-not-clock-regexp
  11761. (line-end-position)
  11762. t)
  11763. (match-beginning 0)
  11764. (line-end-position))))))
  11765. ;; If there is nothing more to add and no more keyword
  11766. ;; is left, remove the line completely.
  11767. (if (and (looking-at-p "[ \t]*$") (not what))
  11768. (delete-region (line-beginning-position)
  11769. (line-beginning-position 2))
  11770. ;; If we removed last keyword, do not leave trailing
  11771. ;; white space at the end of line.
  11772. (let ((p (point)))
  11773. (save-excursion
  11774. (end-of-line)
  11775. (unless (= (skip-chars-backward " \t" p) 0)
  11776. (delete-region (point) (line-end-position)))))))
  11777. ((not what) (throw 'exit nil)) ; Nothing to do.
  11778. (t (insert-before-markers "\n")
  11779. (backward-char 1)
  11780. (when org-adapt-indentation
  11781. (indent-to-column (1+ (org-outline-level))))))
  11782. (when what
  11783. ;; Insert planning keyword.
  11784. (insert (cl-case what
  11785. (closed org-closed-string)
  11786. (deadline org-deadline-string)
  11787. (scheduled org-scheduled-string)
  11788. (otherwise (error "Invalid planning type: %s" what)))
  11789. " ")
  11790. ;; Insert associated timestamp.
  11791. (let ((ts (org-insert-time-stamp
  11792. time
  11793. (or org-time-was-given
  11794. (and (eq what 'closed) org-log-done-with-time))
  11795. (eq what 'closed)
  11796. nil nil (list org-end-time-was-given))))
  11797. (unless (eolp) (insert " "))
  11798. ts))))))
  11799. (defvar org-log-note-marker (make-marker)
  11800. "Marker pointing at the entry where the note is to be inserted.")
  11801. (defvar org-log-note-purpose nil)
  11802. (defvar org-log-note-state nil)
  11803. (defvar org-log-note-previous-state nil)
  11804. (defvar org-log-note-extra nil)
  11805. (defvar org-log-note-window-configuration nil)
  11806. (defvar org-log-note-return-to (make-marker))
  11807. (defvar org-log-note-effective-time nil
  11808. "Remembered current time so that dynamically scoped
  11809. `org-extend-today-until' affects timestamps in state change log")
  11810. (defvar org-log-post-message nil
  11811. "Message to be displayed after a log note has been stored.
  11812. The auto-repeater uses this.")
  11813. (defun org-add-note ()
  11814. "Add a note to the current entry.
  11815. This is done in the same way as adding a state change note."
  11816. (interactive)
  11817. (org-add-log-setup 'note))
  11818. (defun org-log-beginning (&optional create)
  11819. "Return expected start of log notes in current entry.
  11820. When optional argument CREATE is non-nil, the function creates
  11821. a drawer to store notes, if necessary. Returned position ignores
  11822. narrowing."
  11823. (org-with-wide-buffer
  11824. (let ((drawer (org-log-into-drawer)))
  11825. (cond
  11826. (drawer
  11827. (org-end-of-meta-data)
  11828. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  11829. (end (if (org-at-heading-p) (point)
  11830. (save-excursion (outline-next-heading) (point))))
  11831. (case-fold-search t))
  11832. (catch 'exit
  11833. ;; Try to find existing drawer.
  11834. (while (re-search-forward regexp end t)
  11835. (let ((element (org-element-at-point)))
  11836. (when (eq (org-element-type element) 'drawer)
  11837. (let ((cend (org-element-property :contents-end element)))
  11838. (when (and (not org-log-states-order-reversed) cend)
  11839. (goto-char cend)))
  11840. (throw 'exit nil))))
  11841. ;; No drawer found. Create one, if permitted.
  11842. (when create
  11843. (unless (bolp) (insert "\n"))
  11844. (let ((beg (point)))
  11845. (insert ":" drawer ":\n:END:\n")
  11846. (org-indent-region beg (point))
  11847. (org-flag-region
  11848. (line-end-position -1) (1- (point)) t 'org-hide-drawer))
  11849. (end-of-line -1)))))
  11850. (t
  11851. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  11852. (skip-chars-forward " \t\n")
  11853. (beginning-of-line)
  11854. (unless org-log-states-order-reversed
  11855. (org-skip-over-state-notes)
  11856. (skip-chars-backward " \t\n")
  11857. (forward-line)))))
  11858. (if (bolp) (point) (line-beginning-position 2))))
  11859. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  11860. "Set up the post command hook to take a note.
  11861. If this is about to TODO state change, the new state is expected in STATE.
  11862. HOW is an indicator what kind of note should be created.
  11863. EXTRA is additional text that will be inserted into the notes buffer."
  11864. (move-marker org-log-note-marker (point))
  11865. (setq org-log-note-purpose purpose
  11866. org-log-note-state state
  11867. org-log-note-previous-state prev-state
  11868. org-log-note-how how
  11869. org-log-note-extra extra
  11870. org-log-note-effective-time (org-current-effective-time))
  11871. (add-hook 'post-command-hook 'org-add-log-note 'append))
  11872. (defun org-skip-over-state-notes ()
  11873. "Skip past the list of State notes in an entry."
  11874. (when (ignore-errors (goto-char (org-in-item-p)))
  11875. (let* ((struct (org-list-struct))
  11876. (prevs (org-list-prevs-alist struct))
  11877. (regexp
  11878. (concat "[ \t]*- +"
  11879. (replace-regexp-in-string
  11880. " +" " +"
  11881. (org-replace-escapes
  11882. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  11883. `(("%d" . ,org-ts-regexp-inactive)
  11884. ("%D" . ,org-ts-regexp)
  11885. ("%s" . "\"\\S-+\"")
  11886. ("%S" . "\"\\S-+\"")
  11887. ("%t" . ,org-ts-regexp-inactive)
  11888. ("%T" . ,org-ts-regexp)
  11889. ("%u" . ".*?")
  11890. ("%U" . ".*?")))))))
  11891. (while (looking-at-p regexp)
  11892. (goto-char (or (org-list-get-next-item (point) struct prevs)
  11893. (org-list-get-item-end (point) struct)))))))
  11894. (defun org-add-log-note (&optional _purpose)
  11895. "Pop up a window for taking a note, and add this note later."
  11896. (remove-hook 'post-command-hook 'org-add-log-note)
  11897. (setq org-log-note-window-configuration (current-window-configuration))
  11898. (delete-other-windows)
  11899. (move-marker org-log-note-return-to (point))
  11900. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  11901. (goto-char org-log-note-marker)
  11902. (org-switch-to-buffer-other-window "*Org Note*")
  11903. (erase-buffer)
  11904. (if (memq org-log-note-how '(time state))
  11905. (org-store-log-note)
  11906. (let ((org-inhibit-startup t)) (org-mode))
  11907. (insert (format "# Insert note for %s.
  11908. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  11909. (cond
  11910. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  11911. ((eq org-log-note-purpose 'done) "closed todo item")
  11912. ((eq org-log-note-purpose 'state)
  11913. (format "state change from \"%s\" to \"%s\""
  11914. (or org-log-note-previous-state "")
  11915. (or org-log-note-state "")))
  11916. ((eq org-log-note-purpose 'reschedule)
  11917. "rescheduling")
  11918. ((eq org-log-note-purpose 'delschedule)
  11919. "no longer scheduled")
  11920. ((eq org-log-note-purpose 'redeadline)
  11921. "changing deadline")
  11922. ((eq org-log-note-purpose 'deldeadline)
  11923. "removing deadline")
  11924. ((eq org-log-note-purpose 'refile)
  11925. "refiling")
  11926. ((eq org-log-note-purpose 'note)
  11927. "this entry")
  11928. (t (error "This should not happen")))))
  11929. (when org-log-note-extra (insert org-log-note-extra))
  11930. (setq-local org-finish-function 'org-store-log-note)
  11931. (run-hooks 'org-log-buffer-setup-hook)))
  11932. (defvar org-note-abort nil) ; dynamically scoped
  11933. (defun org-store-log-note ()
  11934. "Finish taking a log note, and insert it to where it belongs."
  11935. (let ((txt (prog1 (buffer-string)
  11936. (kill-buffer)))
  11937. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  11938. lines)
  11939. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  11940. (setq txt (replace-match "" t t txt)))
  11941. (when (string-match "\\s-+\\'" txt)
  11942. (setq txt (replace-match "" t t txt)))
  11943. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  11944. (when (org-string-nw-p note)
  11945. (setq note
  11946. (org-replace-escapes
  11947. note
  11948. (list (cons "%u" (user-login-name))
  11949. (cons "%U" user-full-name)
  11950. (cons "%t" (format-time-string
  11951. (org-time-stamp-format 'long 'inactive)
  11952. org-log-note-effective-time))
  11953. (cons "%T" (format-time-string
  11954. (org-time-stamp-format 'long nil)
  11955. org-log-note-effective-time))
  11956. (cons "%d" (format-time-string
  11957. (org-time-stamp-format nil 'inactive)
  11958. org-log-note-effective-time))
  11959. (cons "%D" (format-time-string
  11960. (org-time-stamp-format nil nil)
  11961. org-log-note-effective-time))
  11962. (cons "%s" (cond
  11963. ((not org-log-note-state) "")
  11964. ((string-match-p org-ts-regexp
  11965. org-log-note-state)
  11966. (format "\"[%s]\""
  11967. (substring org-log-note-state 1 -1)))
  11968. (t (format "\"%s\"" org-log-note-state))))
  11969. (cons "%S"
  11970. (cond
  11971. ((not org-log-note-previous-state) "")
  11972. ((string-match-p org-ts-regexp
  11973. org-log-note-previous-state)
  11974. (format "\"[%s]\""
  11975. (substring
  11976. org-log-note-previous-state 1 -1)))
  11977. (t (format "\"%s\""
  11978. org-log-note-previous-state)))))))
  11979. (when lines (setq note (concat note " \\\\")))
  11980. (push note lines))
  11981. (when (and lines (not org-note-abort))
  11982. (with-current-buffer (marker-buffer org-log-note-marker)
  11983. (org-with-wide-buffer
  11984. ;; Find location for the new note.
  11985. (goto-char org-log-note-marker)
  11986. (set-marker org-log-note-marker nil)
  11987. ;; Note associated to a clock is to be located right after
  11988. ;; the clock. Do not move point.
  11989. (unless (eq org-log-note-purpose 'clock-out)
  11990. (goto-char (org-log-beginning t)))
  11991. ;; Make sure point is at the beginning of an empty line.
  11992. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  11993. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  11994. ;; In an existing list, add a new item at the top level.
  11995. ;; Otherwise, indent line like a regular one.
  11996. (let ((itemp (org-in-item-p)))
  11997. (if itemp
  11998. (indent-line-to
  11999. (let ((struct (save-excursion
  12000. (goto-char itemp) (org-list-struct))))
  12001. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12002. (org-indent-line)))
  12003. (insert (org-list-bullet-string "-") (pop lines))
  12004. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12005. (dolist (line lines)
  12006. (insert "\n")
  12007. (indent-line-to ind)
  12008. (insert line)))
  12009. (message "Note stored")
  12010. (org-back-to-heading t))
  12011. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12012. ;; from within `org-add-log-note' because `buffer-undo-list'
  12013. ;; is then modified outside of `org-with-remote-undo'.
  12014. (when (eq this-command 'org-agenda-todo)
  12015. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12016. ;; Don't add undo information when called from `org-agenda-todo'.
  12017. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12018. (set-window-configuration org-log-note-window-configuration)
  12019. (with-current-buffer (marker-buffer org-log-note-return-to)
  12020. (goto-char org-log-note-return-to))
  12021. (move-marker org-log-note-return-to nil)
  12022. (when org-log-post-message (message "%s" org-log-post-message))))
  12023. (defun org-remove-empty-drawer-at (pos)
  12024. "Remove an empty drawer at position POS.
  12025. POS may also be a marker."
  12026. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12027. (org-with-wide-buffer
  12028. (goto-char pos)
  12029. (let ((drawer (org-element-at-point)))
  12030. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12031. (not (org-element-property :contents-begin drawer)))
  12032. (delete-region (org-element-property :begin drawer)
  12033. (progn (goto-char (org-element-property :end drawer))
  12034. (skip-chars-backward " \r\t\n")
  12035. (forward-line)
  12036. (point))))))))
  12037. (defvar org-ts-type nil)
  12038. (defun org-sparse-tree (&optional arg type)
  12039. "Create a sparse tree, prompt for the details.
  12040. This command can create sparse trees. You first need to select the type
  12041. of match used to create the tree:
  12042. t Show all TODO entries.
  12043. T Show entries with a specific TODO keyword.
  12044. m Show entries selected by a tags/property match.
  12045. p Enter a property name and its value (both with completion on existing
  12046. names/values) and show entries with that property.
  12047. r Show entries matching a regular expression (`/' can be used as well).
  12048. b Show deadlines and scheduled items before a date.
  12049. a Show deadlines and scheduled items after a date.
  12050. d Show deadlines due within `org-deadline-warning-days'.
  12051. D Show deadlines and scheduled items between a date range."
  12052. (interactive "P")
  12053. (setq type (or type org-sparse-tree-default-date-type))
  12054. (setq org-ts-type type)
  12055. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12056. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12057. \[c]ycle through date types: %s"
  12058. (cl-case type
  12059. (all "all timestamps")
  12060. (scheduled "only scheduled")
  12061. (deadline "only deadline")
  12062. (active "only active timestamps")
  12063. (inactive "only inactive timestamps")
  12064. (closed "with a closed time-stamp")
  12065. (otherwise "scheduled/deadline")))
  12066. (let ((answer (read-char-exclusive)))
  12067. (cl-case answer
  12068. (?c
  12069. (org-sparse-tree
  12070. arg
  12071. (cadr
  12072. (memq type '(nil all scheduled deadline active inactive closed)))))
  12073. (?d (call-interactively 'org-check-deadlines))
  12074. (?b (call-interactively 'org-check-before-date))
  12075. (?a (call-interactively 'org-check-after-date))
  12076. (?D (call-interactively 'org-check-dates-range))
  12077. (?t (call-interactively 'org-show-todo-tree))
  12078. (?T (org-show-todo-tree '(4)))
  12079. (?m (call-interactively 'org-match-sparse-tree))
  12080. ((?p ?P)
  12081. (let* ((kwd (completing-read
  12082. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12083. (value (completing-read
  12084. "Value: " (mapcar #'list (org-property-values kwd)))))
  12085. (unless (string-match "\\`{.*}\\'" value)
  12086. (setq value (concat "\"" value "\"")))
  12087. (org-match-sparse-tree arg (concat kwd "=" value))))
  12088. ((?r ?R ?/) (call-interactively 'org-occur))
  12089. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12090. (defvar-local org-occur-highlights nil
  12091. "List of overlays used for occur matches.")
  12092. (defvar-local org-occur-parameters nil
  12093. "Parameters of the active org-occur calls.
  12094. This is a list, each call to org-occur pushes as cons cell,
  12095. containing the regular expression and the callback, onto the list.
  12096. The list can contain several entries if `org-occur' has been called
  12097. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12098. will only contain one set of parameters. When the highlights are
  12099. removed (for example with `C-c C-c', or with the next edit (depending
  12100. on `org-remove-highlights-with-change'), this variable is emptied
  12101. as well.")
  12102. (defun org-occur (regexp &optional keep-previous callback)
  12103. "Make a compact tree which shows all matches of REGEXP.
  12104. The tree will show the lines where the regexp matches, and any other context
  12105. defined in `org-show-context-detail', which see.
  12106. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12107. done by a previous call to `org-occur' will be kept, to allow stacking of
  12108. calls to this command.
  12109. Optional argument CALLBACK can be a function of no argument. In this case,
  12110. it is called with point at the end of the match, match data being set
  12111. accordingly. Current match is shown only if the return value is non-nil.
  12112. The function must neither move point nor alter narrowing."
  12113. (interactive "sRegexp: \nP")
  12114. (when (equal regexp "")
  12115. (user-error "Regexp cannot be empty"))
  12116. (unless keep-previous
  12117. (org-remove-occur-highlights nil nil t))
  12118. (push (cons regexp callback) org-occur-parameters)
  12119. (let ((cnt 0))
  12120. (save-excursion
  12121. (goto-char (point-min))
  12122. (when (or (not keep-previous) ; do not want to keep
  12123. (not org-occur-highlights)) ; no previous matches
  12124. ;; hide everything
  12125. (org-overview))
  12126. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12127. (isearch-no-upper-case-p regexp t)
  12128. org-occur-case-fold-search)))
  12129. (while (re-search-forward regexp nil t)
  12130. (when (or (not callback)
  12131. (save-match-data (funcall callback)))
  12132. (setq cnt (1+ cnt))
  12133. (when org-highlight-sparse-tree-matches
  12134. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12135. (org-show-context 'occur-tree)))))
  12136. (when org-remove-highlights-with-change
  12137. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12138. nil 'local))
  12139. (unless org-sparse-tree-open-archived-trees
  12140. (org-hide-archived-subtrees (point-min) (point-max)))
  12141. (run-hooks 'org-occur-hook)
  12142. (when (called-interactively-p 'interactive)
  12143. (message "%d match(es) for regexp %s" cnt regexp))
  12144. cnt))
  12145. (defun org-occur-next-match (&optional n _reset)
  12146. "Function for `next-error-function' to find sparse tree matches.
  12147. N is the number of matches to move, when negative move backwards.
  12148. This function always goes back to the starting point when no
  12149. match is found."
  12150. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12151. (search-func (if (< n 0)
  12152. 'previous-single-char-property-change
  12153. 'next-single-char-property-change))
  12154. (n (abs n))
  12155. (pos (point))
  12156. p1)
  12157. (catch 'exit
  12158. (while (setq p1 (funcall search-func (point) 'org-type))
  12159. (when (equal p1 limit)
  12160. (goto-char pos)
  12161. (user-error "No more matches"))
  12162. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12163. (setq n (1- n))
  12164. (when (= n 0)
  12165. (goto-char p1)
  12166. (throw 'exit (point))))
  12167. (goto-char p1))
  12168. (goto-char p1)
  12169. (user-error "No more matches"))))
  12170. (defun org-highlight-new-match (beg end)
  12171. "Highlight from BEG to END and mark the highlight is an occur headline."
  12172. (let ((ov (make-overlay beg end)))
  12173. (overlay-put ov 'face 'secondary-selection)
  12174. (overlay-put ov 'org-type 'org-occur)
  12175. (push ov org-occur-highlights)))
  12176. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12177. "Remove the occur highlights from the buffer.
  12178. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12179. from the `before-change-functions' in the current buffer."
  12180. (interactive)
  12181. (unless org-inhibit-highlight-removal
  12182. (mapc #'delete-overlay org-occur-highlights)
  12183. (setq org-occur-highlights nil)
  12184. (setq org-occur-parameters nil)
  12185. (unless noremove
  12186. (remove-hook 'before-change-functions
  12187. 'org-remove-occur-highlights 'local))))
  12188. ;;;; Priorities
  12189. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12190. "Regular expression matching the priority indicator.")
  12191. (defvar org-remove-priority-next-time nil)
  12192. (defun org-priority-up ()
  12193. "Increase the priority of the current item."
  12194. (interactive)
  12195. (org-priority 'up))
  12196. (defun org-priority-down ()
  12197. "Decrease the priority of the current item."
  12198. (interactive)
  12199. (org-priority 'down))
  12200. (defun org-priority (&optional action _show)
  12201. "Change the priority of an item.
  12202. ACTION can be `set', `up', `down', or a character."
  12203. (interactive "P")
  12204. (if (equal action '(4))
  12205. (org-show-priority)
  12206. (unless org-enable-priority-commands
  12207. (user-error "Priority commands are disabled"))
  12208. (setq action (or action 'set))
  12209. (let (current new news have remove)
  12210. (save-excursion
  12211. (org-back-to-heading t)
  12212. (when (looking-at org-priority-regexp)
  12213. (setq current (string-to-char (match-string 2))
  12214. have t))
  12215. (cond
  12216. ((eq action 'remove)
  12217. (setq remove t new ?\ ))
  12218. ((or (eq action 'set)
  12219. (integerp action))
  12220. (if (not (eq action 'set))
  12221. (setq new action)
  12222. (message "Priority %c-%c, SPC to remove: "
  12223. org-highest-priority org-lowest-priority)
  12224. (save-match-data
  12225. (setq new (read-char-exclusive))))
  12226. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12227. (= (upcase org-lowest-priority) org-lowest-priority))
  12228. (setq new (upcase new)))
  12229. (cond ((equal new ?\ ) (setq remove t))
  12230. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12231. (user-error "Priority must be between `%c' and `%c'"
  12232. org-highest-priority org-lowest-priority))))
  12233. ((eq action 'up)
  12234. (setq new (if have
  12235. (1- current) ; normal cycling
  12236. ;; last priority was empty
  12237. (if (eq last-command this-command)
  12238. org-lowest-priority ; wrap around empty to lowest
  12239. ;; default
  12240. (if org-priority-start-cycle-with-default
  12241. org-default-priority
  12242. (1- org-default-priority))))))
  12243. ((eq action 'down)
  12244. (setq new (if have
  12245. (1+ current) ; normal cycling
  12246. ;; last priority was empty
  12247. (if (eq last-command this-command)
  12248. org-highest-priority ; wrap around empty to highest
  12249. ;; default
  12250. (if org-priority-start-cycle-with-default
  12251. org-default-priority
  12252. (1+ org-default-priority))))))
  12253. (t (user-error "Invalid action")))
  12254. (when (or (< (upcase new) org-highest-priority)
  12255. (> (upcase new) org-lowest-priority))
  12256. (if (and (memq action '(up down))
  12257. (not have) (not (eq last-command this-command)))
  12258. ;; `new' is from default priority
  12259. (error
  12260. "The default can not be set, see `org-default-priority' why")
  12261. ;; normal cycling: `new' is beyond highest/lowest priority
  12262. ;; and is wrapped around to the empty priority
  12263. (setq remove t)))
  12264. (setq news (format "%c" new))
  12265. (if have
  12266. (if remove
  12267. (replace-match "" t t nil 1)
  12268. (replace-match news t t nil 2))
  12269. (if remove
  12270. (user-error "No priority cookie found in line")
  12271. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12272. (if (match-end 2)
  12273. (progn
  12274. (goto-char (match-end 2))
  12275. (insert " [#" news "]"))
  12276. (goto-char (match-beginning 3))
  12277. (insert "[#" news "] "))))
  12278. (org-set-tags nil 'align))
  12279. (if remove
  12280. (message "Priority removed")
  12281. (message "Priority of current item set to %s" news)))))
  12282. (defun org-show-priority ()
  12283. "Show the priority of the current item.
  12284. This priority is composed of the main priority given with the [#A] cookies,
  12285. and by additional input from the age of a schedules or deadline entry."
  12286. (interactive)
  12287. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12288. (org-get-at-bol 'priority)
  12289. (save-excursion
  12290. (save-match-data
  12291. (beginning-of-line)
  12292. (and (looking-at org-heading-regexp)
  12293. (org-get-priority (match-string 0))))))))
  12294. (message "Priority is %d" (if pri pri -1000))))
  12295. (defun org-get-priority (s)
  12296. "Find priority cookie and return priority."
  12297. (save-match-data
  12298. (if (functionp org-get-priority-function)
  12299. (funcall org-get-priority-function)
  12300. (if (not (string-match org-priority-regexp s))
  12301. (* 1000 (- org-lowest-priority org-default-priority))
  12302. (* 1000 (- org-lowest-priority
  12303. (string-to-char (match-string 2 s))))))))
  12304. ;;;; Tags
  12305. (defvar org-agenda-archives-mode)
  12306. (defvar org-map-continue-from nil
  12307. "Position from where mapping should continue.
  12308. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12309. (defvar org-scanner-tags nil
  12310. "The current tag list while the tags scanner is running.")
  12311. (defvar org-trust-scanner-tags nil
  12312. "Should `org-get-tags' use the tags for the scanner.
  12313. This is for internal dynamical scoping only.
  12314. When this is non-nil, the function `org-get-tags' will return the value
  12315. of `org-scanner-tags' instead of building the list by itself. This
  12316. can lead to large speed-ups when the tags scanner is used in a file with
  12317. many entries, and when the list of tags is retrieved, for example to
  12318. obtain a list of properties. Building the tags list for each entry in such
  12319. a file becomes an N^2 operation - but with this variable set, it scales
  12320. as N.")
  12321. (defvar org--matcher-tags-todo-only nil)
  12322. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12323. "Scan headline tags with inheritance and produce output ACTION.
  12324. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12325. or `agenda' to produce an entry list for an agenda view. It can also be
  12326. a Lisp form or a function that should be called at each matched headline, in
  12327. this case the return value is a list of all return values from these calls.
  12328. MATCHER is a function accepting three arguments, returning
  12329. a non-nil value whenever a given set of tags qualifies a headline
  12330. for inclusion. See `org-make-tags-matcher' for more information.
  12331. As a special case, it can also be set to t (respectively nil) in
  12332. order to match all (respectively none) headline.
  12333. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  12334. included in the output.
  12335. START-LEVEL can be a string with asterisks, reducing the scope to
  12336. headlines matching this string."
  12337. (require 'org-agenda)
  12338. (let* ((re (concat "^"
  12339. (if start-level
  12340. ;; Get the correct level to match
  12341. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12342. org-outline-regexp)
  12343. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  12344. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  12345. (props (list 'face 'default
  12346. 'done-face 'org-agenda-done
  12347. 'undone-face 'default
  12348. 'mouse-face 'highlight
  12349. 'org-not-done-regexp org-not-done-regexp
  12350. 'org-todo-regexp org-todo-regexp
  12351. 'org-complex-heading-regexp org-complex-heading-regexp
  12352. 'help-echo
  12353. (format "mouse-2 or RET jump to Org file %S"
  12354. (abbreviate-file-name
  12355. (or (buffer-file-name (buffer-base-buffer))
  12356. (buffer-name (buffer-base-buffer)))))))
  12357. (org-map-continue-from nil)
  12358. lspos tags tags-list
  12359. (tags-alist (list (cons 0 org-file-tags)))
  12360. (llast 0) rtn rtn1 level category i txt
  12361. todo marker entry priority
  12362. ts-date ts-date-type ts-date-pair)
  12363. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12364. (setq action (list 'lambda nil action)))
  12365. (save-excursion
  12366. (goto-char (point-min))
  12367. (when (eq action 'sparse-tree)
  12368. (org-overview)
  12369. (org-remove-occur-highlights))
  12370. (while (let (case-fold-search)
  12371. (re-search-forward re nil t))
  12372. (setq org-map-continue-from nil)
  12373. (catch :skip
  12374. ;; Ignore closing parts of inline tasks.
  12375. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  12376. (throw :skip t))
  12377. (setq todo
  12378. ;; TODO: is the 1-2 difference a bug?
  12379. (when (match-end 1) (match-string-no-properties 2))
  12380. tags (when (match-end 4) (match-string-no-properties 4)))
  12381. (goto-char (setq lspos (match-beginning 0)))
  12382. (setq level (org-reduced-level (org-outline-level))
  12383. category (org-get-category))
  12384. (when (eq action 'agenda)
  12385. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12386. ts-date (car ts-date-pair)
  12387. ts-date-type (cdr ts-date-pair)))
  12388. (setq i llast llast level)
  12389. ;; remove tag lists from same and sublevels
  12390. (while (>= i level)
  12391. (when (setq entry (assoc i tags-alist))
  12392. (setq tags-alist (delete entry tags-alist)))
  12393. (setq i (1- i)))
  12394. ;; add the next tags
  12395. (when tags
  12396. (setq tags (org-split-string tags ":")
  12397. tags-alist
  12398. (cons (cons level tags) tags-alist)))
  12399. ;; compile tags for current headline
  12400. (setq tags-list
  12401. (if org-use-tag-inheritance
  12402. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12403. tags)
  12404. org-scanner-tags tags-list)
  12405. (when org-use-tag-inheritance
  12406. (setcdr (car tags-alist)
  12407. (mapcar (lambda (x)
  12408. (setq x (copy-sequence x))
  12409. (org-add-prop-inherited x))
  12410. (cdar tags-alist))))
  12411. (when (and tags org-use-tag-inheritance
  12412. (or (not (eq t org-use-tag-inheritance))
  12413. org-tags-exclude-from-inheritance))
  12414. ;; Selective inheritance, remove uninherited ones.
  12415. (setcdr (car tags-alist)
  12416. (org-remove-uninherited-tags (cdar tags-alist))))
  12417. (when (and
  12418. ;; eval matcher only when the todo condition is OK
  12419. (and (or (not todo-only) (member todo org-todo-keywords-1))
  12420. (if (functionp matcher)
  12421. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12422. (funcall matcher todo tags-list level))
  12423. matcher))
  12424. ;; Call the skipper, but return t if it does not
  12425. ;; skip, so that the `and' form continues evaluating.
  12426. (progn
  12427. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12428. t)
  12429. ;; Check if timestamps are deselecting this entry
  12430. (or (not todo-only)
  12431. (and (member todo org-todo-keywords-1)
  12432. (or (not org-agenda-tags-todo-honor-ignore-options)
  12433. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12434. ;; select this headline
  12435. (cond
  12436. ((eq action 'sparse-tree)
  12437. (and org-highlight-sparse-tree-matches
  12438. (org-get-heading) (match-end 0)
  12439. (org-highlight-new-match
  12440. (match-beginning 1) (match-end 1)))
  12441. (org-show-context 'tags-tree))
  12442. ((eq action 'agenda)
  12443. (setq txt (org-agenda-format-item
  12444. ""
  12445. (concat
  12446. (if (eq org-tags-match-list-sublevels 'indented)
  12447. (make-string (1- level) ?.) "")
  12448. (org-get-heading))
  12449. (make-string level ?\s)
  12450. category
  12451. tags-list)
  12452. priority (org-get-priority txt))
  12453. (goto-char lspos)
  12454. (setq marker (org-agenda-new-marker))
  12455. (org-add-props txt props
  12456. 'org-marker marker 'org-hd-marker marker 'org-category category
  12457. 'todo-state todo
  12458. 'ts-date ts-date
  12459. 'priority priority
  12460. 'type (concat "tagsmatch" ts-date-type))
  12461. (push txt rtn))
  12462. ((functionp action)
  12463. (setq org-map-continue-from nil)
  12464. (save-excursion
  12465. (setq rtn1 (funcall action))
  12466. (push rtn1 rtn)))
  12467. (t (user-error "Invalid action")))
  12468. ;; if we are to skip sublevels, jump to end of subtree
  12469. (unless org-tags-match-list-sublevels
  12470. (org-end-of-subtree t)
  12471. (backward-char 1))))
  12472. ;; Get the correct position from where to continue
  12473. (if org-map-continue-from
  12474. (goto-char org-map-continue-from)
  12475. (and (= (point) lspos) (end-of-line 1)))))
  12476. (when (and (eq action 'sparse-tree)
  12477. (not org-sparse-tree-open-archived-trees))
  12478. (org-hide-archived-subtrees (point-min) (point-max)))
  12479. (nreverse rtn)))
  12480. (defun org-remove-uninherited-tags (tags)
  12481. "Remove all tags that are not inherited from the list TAGS."
  12482. (cond
  12483. ((eq org-use-tag-inheritance t)
  12484. (if org-tags-exclude-from-inheritance
  12485. (org-delete-all org-tags-exclude-from-inheritance tags)
  12486. tags))
  12487. ((not org-use-tag-inheritance) nil)
  12488. ((stringp org-use-tag-inheritance)
  12489. (delq nil (mapcar
  12490. (lambda (x)
  12491. (if (and (string-match org-use-tag-inheritance x)
  12492. (not (member x org-tags-exclude-from-inheritance)))
  12493. x nil))
  12494. tags)))
  12495. ((listp org-use-tag-inheritance)
  12496. (delq nil (mapcar
  12497. (lambda (x)
  12498. (if (member x org-use-tag-inheritance) x nil))
  12499. tags)))))
  12500. (defun org-match-sparse-tree (&optional todo-only match)
  12501. "Create a sparse tree according to tags string MATCH.
  12502. MATCH is a string with match syntax. It can contain a selection
  12503. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12504. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12505. those. See the manual for details.
  12506. If optional argument TODO-ONLY is non-nil, only select lines that
  12507. are also TODO tasks."
  12508. (interactive "P")
  12509. (org-agenda-prepare-buffers (list (current-buffer)))
  12510. (let ((org--matcher-tags-todo-only todo-only))
  12511. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12512. org--matcher-tags-todo-only)))
  12513. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12514. (defvar org-cached-props nil)
  12515. (defun org-cached-entry-get (pom property)
  12516. (if (or (eq t org-use-property-inheritance)
  12517. (and (stringp org-use-property-inheritance)
  12518. (let ((case-fold-search t))
  12519. (string-match-p org-use-property-inheritance property)))
  12520. (and (listp org-use-property-inheritance)
  12521. (member-ignore-case property org-use-property-inheritance)))
  12522. ;; Caching is not possible, check it directly.
  12523. (org-entry-get pom property 'inherit)
  12524. ;; Get all properties, so we can do complicated checks easily.
  12525. (cdr (assoc-string property
  12526. (or org-cached-props
  12527. (setq org-cached-props (org-entry-properties pom)))
  12528. t))))
  12529. (defun org-global-tags-completion-table (&optional files)
  12530. "Return the list of all tags in all agenda buffer/files.
  12531. Optional FILES argument is a list of files which can be used
  12532. instead of the agenda files."
  12533. (save-excursion
  12534. (org-uniquify
  12535. (delq nil
  12536. (apply #'append
  12537. (mapcar
  12538. (lambda (file)
  12539. (set-buffer (find-file-noselect file))
  12540. (org-tag-add-to-alist
  12541. (org-get-buffer-tags)
  12542. (mapcar (lambda (x)
  12543. (and (stringp (car-safe x))
  12544. (list (car-safe x))))
  12545. org-current-tag-alist)))
  12546. (if (car-safe files) files
  12547. (org-agenda-files))))))))
  12548. (defun org-make-tags-matcher (match)
  12549. "Create the TAGS/TODO matcher form for the selection string MATCH.
  12550. Returns a cons of the selection string MATCH and a function
  12551. implementing the matcher.
  12552. The matcher is to be called at an Org entry, with point on the
  12553. headline, and returns non-nil if the entry matches the selection
  12554. string MATCH. It must be called with three arguments: the TODO
  12555. keyword at the entry (or nil if none), the list of all tags at
  12556. the entry including inherited ones and the reduced level of the
  12557. headline. Additionally, the category of the entry, if any, must
  12558. be specified as the text property `org-category' on the headline.
  12559. This function sets the variable `org--matcher-tags-todo-only' to
  12560. a non-nil value if the matcher restricts matching to TODO
  12561. entries, otherwise it is not touched.
  12562. See also `org-scan-tags'."
  12563. (unless match
  12564. ;; Get a new match request, with completion against the global
  12565. ;; tags table and the local tags in current buffer.
  12566. (let ((org-last-tags-completion-table
  12567. (org-tag-add-to-alist
  12568. (org-get-buffer-tags)
  12569. (org-global-tags-completion-table))))
  12570. (setq match
  12571. (completing-read
  12572. "Match: "
  12573. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  12574. (let ((match0 match)
  12575. (re (concat
  12576. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  12577. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  12578. "\\([<>=]\\{1,2\\}\\)"
  12579. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  12580. "\\|" org-tag-re "\\)"))
  12581. (start 0)
  12582. tagsmatch todomatch tagsmatcher todomatcher)
  12583. ;; Expand group tags.
  12584. (setq match (org-tags-expand match))
  12585. ;; Check if there is a TODO part of this match, which would be the
  12586. ;; part after a "/". To make sure that this slash is not part of
  12587. ;; a property value to be matched against, we also check that
  12588. ;; there is no / after that slash. First, find the last slash.
  12589. (let ((s 0))
  12590. (while (string-match "/+" match s)
  12591. (setq start (match-beginning 0))
  12592. (setq s (match-end 0))))
  12593. (if (and (string-match "/+" match start)
  12594. (not (string-match-p "\"" match start)))
  12595. ;; Match contains also a TODO-matching request.
  12596. (progn
  12597. (setq tagsmatch (substring match 0 (match-beginning 0)))
  12598. (setq todomatch (substring match (match-end 0)))
  12599. (when (string-prefix-p "!" todomatch)
  12600. (setq org--matcher-tags-todo-only t)
  12601. (setq todomatch (substring todomatch 1)))
  12602. (when (string-match "\\`\\s-*\\'" todomatch)
  12603. (setq todomatch nil)))
  12604. ;; Only matching tags.
  12605. (setq tagsmatch match)
  12606. (setq todomatch nil))
  12607. ;; Make the tags matcher.
  12608. (when (org-string-nw-p tagsmatch)
  12609. (let ((orlist nil)
  12610. (orterms (org-split-string tagsmatch "|"))
  12611. term)
  12612. (while (setq term (pop orterms))
  12613. (while (and (equal (substring term -1) "\\") orterms)
  12614. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  12615. (while (string-match re term)
  12616. (let* ((rest (substring term (match-end 0)))
  12617. (minus (and (match-end 1)
  12618. (equal (match-string 1 term) "-")))
  12619. (tag (save-match-data
  12620. (replace-regexp-in-string
  12621. "\\\\-" "-" (match-string 2 term))))
  12622. (regexp (eq (string-to-char tag) ?{))
  12623. (levelp (match-end 4))
  12624. (propp (match-end 5))
  12625. (mm
  12626. (cond
  12627. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  12628. (levelp
  12629. `(,(org-op-to-function (match-string 3 term))
  12630. level
  12631. ,(string-to-number (match-string 4 term))))
  12632. (propp
  12633. (let* ((gv (pcase (upcase (match-string 5 term))
  12634. ("CATEGORY"
  12635. '(get-text-property (point) 'org-category))
  12636. ("TODO" 'todo)
  12637. (p `(org-cached-entry-get nil ,p))))
  12638. (pv (match-string 7 term))
  12639. (regexp (eq (string-to-char pv) ?{))
  12640. (strp (eq (string-to-char pv) ?\"))
  12641. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  12642. (po (org-op-to-function (match-string 6 term)
  12643. (if timep 'time strp))))
  12644. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  12645. (when timep (setq pv (org-matcher-time pv)))
  12646. (cond ((and regexp (eq po '/=))
  12647. `(not (string-match ,pv (or ,gv ""))))
  12648. (regexp `(string-match ,pv (or ,gv "")))
  12649. (strp `(,po (or ,gv "") ,pv))
  12650. (t
  12651. `(,po
  12652. (string-to-number (or ,gv ""))
  12653. ,(string-to-number pv))))))
  12654. (t `(member ,tag tags-list)))))
  12655. (push (if minus `(not ,mm) mm) tagsmatcher)
  12656. (setq term rest)))
  12657. (push `(and ,@tagsmatcher) orlist)
  12658. (setq tagsmatcher nil))
  12659. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  12660. ;; Make the TODO matcher.
  12661. (when (org-string-nw-p todomatch)
  12662. (let ((orlist nil))
  12663. (dolist (term (org-split-string todomatch "|"))
  12664. (while (string-match re term)
  12665. (let* ((minus (and (match-end 1)
  12666. (equal (match-string 1 term) "-")))
  12667. (kwd (match-string 2 term))
  12668. (regexp (eq (string-to-char kwd) ?{))
  12669. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  12670. `(equal todo ,kwd))))
  12671. (push (if minus `(not ,mm) mm) todomatcher))
  12672. (setq term (substring term (match-end 0))))
  12673. (push (if (> (length todomatcher) 1)
  12674. (cons 'and todomatcher)
  12675. (car todomatcher))
  12676. orlist)
  12677. (setq todomatcher nil))
  12678. (setq todomatcher (cons 'or orlist))))
  12679. ;; Return the string and function of the matcher. If no
  12680. ;; tags-specific or todo-specific matcher exists, match
  12681. ;; everything.
  12682. (let ((matcher (if (and tagsmatcher todomatcher)
  12683. `(and ,tagsmatcher ,todomatcher)
  12684. (or tagsmatcher todomatcher t))))
  12685. (when org--matcher-tags-todo-only
  12686. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  12687. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  12688. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  12689. "Expand group tags in MATCH.
  12690. This replaces every group tag in MATCH with a regexp tag search.
  12691. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  12692. will be replaced like this:
  12693. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12694. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12695. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  12696. Replacing by a regexp preserves the structure of the match.
  12697. E.g., this expansion
  12698. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  12699. will match anything tagged with \"Lab\" and \"Home\", or tagged
  12700. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  12701. A group tag in MATCH can contain regular expressions of its own.
  12702. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  12703. will be replaced like this:
  12704. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  12705. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  12706. assumed to be a single group tag, and the function will return
  12707. the list of tags in this group.
  12708. When DOWNCASE is non-nil, expand downcased TAGS."
  12709. (if org-group-tags
  12710. (let* ((case-fold-search t)
  12711. (stable org-mode-syntax-table)
  12712. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  12713. (taggroups (if downcased
  12714. (mapcar (lambda (tg) (mapcar #'downcase tg))
  12715. taggroups)
  12716. taggroups))
  12717. (taggroups-keys (mapcar #'car taggroups))
  12718. (return-match (if downcased (downcase match) match))
  12719. (count 0)
  12720. (work-already-expanded tags-already-expanded)
  12721. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  12722. ;; @ and _ are allowed as word-components in tags.
  12723. (modify-syntax-entry ?@ "w" stable)
  12724. (modify-syntax-entry ?_ "w" stable)
  12725. ;; Temporarily replace regexp-expressions in the match-expression.
  12726. (while (string-match "{.+?}" return-match)
  12727. (cl-incf count)
  12728. (push (match-string 0 return-match) regexps-in-match)
  12729. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  12730. (while (and taggroups-keys
  12731. (with-syntax-table stable
  12732. (string-match
  12733. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  12734. (regexp-opt taggroups-keys) "\\>\\)")
  12735. return-match)))
  12736. (let* ((dir (match-string 1 return-match))
  12737. (tag (match-string 2 return-match))
  12738. (tag (if downcased (downcase tag) tag)))
  12739. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  12740. (member tag tags-already-expanded))
  12741. (setq tags-in-group (assoc tag taggroups))
  12742. (push tag work-already-expanded)
  12743. ;; Recursively expand each tag in the group, if the tag hasn't
  12744. ;; already been expanded. Restore the match-data after all recursive calls.
  12745. (save-match-data
  12746. (let (tags-expanded)
  12747. (dolist (x (cdr tags-in-group))
  12748. (if (and (member x taggroups-keys)
  12749. (not (member x work-already-expanded)))
  12750. (setq tags-expanded
  12751. (delete-dups
  12752. (append
  12753. (org-tags-expand x t downcased
  12754. work-already-expanded)
  12755. tags-expanded)))
  12756. (setq tags-expanded
  12757. (append (list x) tags-expanded)))
  12758. (setq work-already-expanded
  12759. (delete-dups
  12760. (append tags-expanded
  12761. work-already-expanded))))
  12762. (setq tags-in-group
  12763. (delete-dups (cons (car tags-in-group)
  12764. tags-expanded)))))
  12765. ;; Filter tag-regexps from tags.
  12766. (setq regexp-in-group-escaped
  12767. (delq nil (mapcar (lambda (x)
  12768. (if (stringp x)
  12769. (and (equal "{" (substring x 0 1))
  12770. (equal "}" (substring x -1))
  12771. x)
  12772. x))
  12773. tags-in-group))
  12774. regexp-in-group
  12775. (mapcar (lambda (x)
  12776. (substring x 1 -1))
  12777. regexp-in-group-escaped)
  12778. tags-in-group
  12779. (delq nil (mapcar (lambda (x)
  12780. (if (stringp x)
  12781. (and (not (equal "{" (substring x 0 1)))
  12782. (not (equal "}" (substring x -1)))
  12783. x)
  12784. x))
  12785. tags-in-group)))
  12786. ;; If single-as-list, do no more in the while-loop.
  12787. (if (not single-as-list)
  12788. (progn
  12789. (when regexp-in-group
  12790. (setq regexp-in-group
  12791. (concat "\\|"
  12792. (mapconcat 'identity regexp-in-group
  12793. "\\|"))))
  12794. (setq tags-in-group
  12795. (concat dir
  12796. "{\\<"
  12797. (regexp-opt tags-in-group)
  12798. "\\>"
  12799. regexp-in-group
  12800. "}"))
  12801. (when (stringp tags-in-group)
  12802. (org-add-props tags-in-group '(grouptag t)))
  12803. (setq return-match
  12804. (replace-match tags-in-group t t return-match)))
  12805. (setq tags-in-group
  12806. (append regexp-in-group-escaped tags-in-group))))
  12807. (setq taggroups-keys (delete tag taggroups-keys))))
  12808. ;; Add the regular expressions back into the match-expression again.
  12809. (while regexps-in-match
  12810. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  12811. (pop regexps-in-match)
  12812. return-match t t))
  12813. (cl-decf count))
  12814. (if single-as-list
  12815. (if tags-in-group tags-in-group (list return-match))
  12816. return-match))
  12817. (if single-as-list
  12818. (list (if downcased (downcase match) match))
  12819. match)))
  12820. (defun org-op-to-function (op &optional stringp)
  12821. "Turn an operator into the appropriate function."
  12822. (setq op
  12823. (cond
  12824. ((equal op "<" ) '(< org-string< org-time<))
  12825. ((equal op ">" ) '(> org-string> org-time>))
  12826. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  12827. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  12828. ((member op '("=" "==")) '(= string= org-time=))
  12829. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  12830. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  12831. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  12832. (defvar org-tags-overlay (make-overlay 1 1))
  12833. (delete-overlay org-tags-overlay)
  12834. (defun org-add-prop-inherited (s)
  12835. (add-text-properties 0 (length s) '(inherited t) s)
  12836. s)
  12837. (defun org-toggle-tag (tag &optional onoff)
  12838. "Toggle the tag TAG for the current line.
  12839. If ONOFF is `on' or `off', don't toggle but set to this state."
  12840. (save-excursion
  12841. (org-back-to-heading t)
  12842. (let ((current
  12843. ;; Reverse the tags list so any new tag is appended to the
  12844. ;; current list of tags.
  12845. (nreverse (org-get-tags)))
  12846. res)
  12847. (pcase onoff
  12848. (`off (setq current (delete tag current)))
  12849. ((or `on (guard (not (member tag current))))
  12850. (setq res t)
  12851. (cl-pushnew tag current :test #'equal))
  12852. (_ (setq current (delete tag current))))
  12853. (org-set-tags-to (nreverse current))
  12854. (run-hooks 'org-after-tags-change-hook)
  12855. res)))
  12856. (defun org--align-tags-here (to-col)
  12857. "Align tags on the current headline to TO-COL.
  12858. Assume point is on a headline."
  12859. (when (and (org-match-line org-tag-line-re)
  12860. (< (point) (match-beginning 1)))
  12861. (let ((pos (point))
  12862. (shift (if (>= to-col 0) to-col
  12863. (- (abs to-col) (string-width (match-string 1))))))
  12864. ;; Delete all blanks before tags.
  12865. (goto-char (match-beginning 1))
  12866. (skip-chars-backward " \t")
  12867. (delete-region (point) (match-beginning 1))
  12868. ;; Insert new blanks.
  12869. (insert (make-string (max 1 (- shift (current-column))) ?\s))
  12870. ;; Preserve initial position, if possible. In any case, stop
  12871. ;; before tags.
  12872. (when (< pos (point)) (goto-char pos)))))
  12873. (defun org-set-tags-command (&optional arg just-align)
  12874. "Call the set-tags command for the current entry."
  12875. (interactive "P")
  12876. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  12877. (org-set-tags arg just-align)
  12878. (save-excursion
  12879. (unless (and (org-region-active-p)
  12880. org-loop-over-headlines-in-active-region)
  12881. (org-back-to-heading t))
  12882. (org-set-tags arg just-align))))
  12883. (defun org-set-tags-to (data)
  12884. "Set the tags of the current entry to DATA, replacing current tags.
  12885. DATA may be a tags string like \":aa:bb:cc:\", or a list of tags.
  12886. If DATA is nil or the empty string, all tags are removed."
  12887. (interactive "sTags: ")
  12888. (let ((data
  12889. (pcase (if (stringp data) (org-trim data) data)
  12890. ((or `nil "") nil)
  12891. ((pred listp) (org-make-tag-string data))
  12892. ((pred stringp)
  12893. (org-make-tag-string (org-split-string data ":+")))
  12894. (_ (error "Invalid tag specification: %S" data)))))
  12895. (org-with-wide-buffer
  12896. (org-back-to-heading t)
  12897. (let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  12898. (when (or (match-end 5) data)
  12899. (goto-char (or (match-beginning 5) (line-end-position)))
  12900. (skip-chars-backward " \t")
  12901. (delete-region (point) (line-end-position))
  12902. (when data
  12903. (insert " " data)
  12904. (org-set-tags nil 'align))))))
  12905. (defun org-align-all-tags ()
  12906. "Align the tags in all headings."
  12907. (interactive)
  12908. (save-excursion
  12909. (or (ignore-errors (org-back-to-heading t))
  12910. (outline-next-heading))
  12911. (if (org-at-heading-p)
  12912. (org-set-tags t)
  12913. (message "No headings"))))
  12914. (defvar org-indent-indentation-per-level)
  12915. (defun org-set-tags (&optional arg just-align)
  12916. "Set the tags for the current headline.
  12917. With prefix ARG, realign all tags in headings in the current buffer.
  12918. When JUST-ALIGN is non-nil, only align tags."
  12919. (interactive "P")
  12920. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12921. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12922. 'region-start-level
  12923. 'region))
  12924. org-loop-over-headlines-in-active-region)
  12925. (org-map-entries
  12926. ;; We don't use ARG and JUST-ALIGN here because these args
  12927. ;; are not useful when looping over headlines.
  12928. #'org-set-tags
  12929. org-loop-over-headlines-in-active-region
  12930. cl
  12931. '(when (org-invisible-p) (org-end-of-subtree nil t))))
  12932. (let ((org-setting-tags t))
  12933. (if arg
  12934. (save-excursion
  12935. (goto-char (point-min))
  12936. (while (re-search-forward org-outline-regexp-bol nil t)
  12937. (org-set-tags nil t)
  12938. (end-of-line))
  12939. (message "All tags realigned to column %d" org-tags-column))
  12940. (let* ((current (org-make-tag-string (org-get-tags nil t)))
  12941. (tags
  12942. (if just-align current
  12943. ;; Get a new set of tags from the user.
  12944. (save-excursion
  12945. (let* ((table
  12946. (setq
  12947. org-last-tags-completion-table
  12948. (org-tag-add-to-alist
  12949. (and
  12950. org-complete-tags-always-offer-all-agenda-tags
  12951. (org-global-tags-completion-table
  12952. (org-agenda-files)))
  12953. (or org-current-tag-alist
  12954. (org-get-buffer-tags)))))
  12955. (current-tags (org-split-string current ":"))
  12956. (inherited-tags
  12957. (nreverse (nthcdr (length current-tags)
  12958. (nreverse (org-get-tags))))))
  12959. (replace-regexp-in-string
  12960. "\\([-+&]+\\|,\\)"
  12961. ":"
  12962. (if (or (eq t org-use-fast-tag-selection)
  12963. (and org-use-fast-tag-selection
  12964. (delq nil (mapcar #'cdr table))))
  12965. (org-fast-tag-selection
  12966. current-tags inherited-tags table
  12967. (and org-fast-tag-selection-include-todo
  12968. org-todo-key-alist))
  12969. (let ((org-add-colon-after-tag-completion
  12970. (< 1 (length table))))
  12971. (org-trim
  12972. (completing-read
  12973. "Tags: "
  12974. #'org-tags-completion-function
  12975. nil nil current 'org-tags-history))))))))))
  12976. (when org-tags-sort-function
  12977. (setq tags
  12978. (mapconcat
  12979. #'identity
  12980. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  12981. org-tags-sort-function)
  12982. ":")))
  12983. (if (or (string= ":" tags)
  12984. (string= "::" tags))
  12985. (setq tags ""))
  12986. (if (not (org-string-nw-p tags)) (setq tags "")
  12987. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  12988. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  12989. ;; Insert new tags at the correct column.
  12990. (unless (equal current tags)
  12991. (save-excursion
  12992. (beginning-of-line)
  12993. (let ((case-fold-search nil))
  12994. (looking-at org-complex-heading-regexp))
  12995. ;; Remove current tags, if any.
  12996. (when (match-end 5) (replace-match "" nil nil nil 5))
  12997. ;; Insert new tags, if any. Otherwise, remove trailing
  12998. ;; white spaces.
  12999. (end-of-line)
  13000. (if (not (equal tags ""))
  13001. ;; When text is being inserted on an invisible
  13002. ;; region boundary, it can be inadvertently sucked
  13003. ;; into invisibility.
  13004. (org-flag-region (point) (progn (insert " " tags) (point))
  13005. nil
  13006. 'outline)
  13007. (skip-chars-backward " \t")
  13008. (delete-region (point) (line-end-position)))))
  13009. ;; Align tags, if any. Fix tags column if `org-indent-mode'
  13010. ;; is on.
  13011. (unless (equal tags "")
  13012. (let* ((level (save-excursion
  13013. (beginning-of-line)
  13014. (skip-chars-forward "\\*")))
  13015. (offset (if (bound-and-true-p org-indent-mode)
  13016. (* (1- org-indent-indentation-per-level)
  13017. (1- level))
  13018. 0))
  13019. (tags-column
  13020. (+ org-tags-column
  13021. (if (> org-tags-column 0) (- offset) offset))))
  13022. (org--align-tags-here tags-column))))
  13023. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13024. (defun org-change-tag-in-region (beg end tag off)
  13025. "Add or remove TAG for each entry in the region.
  13026. This works in the agenda, and also in an Org buffer."
  13027. (interactive
  13028. (list (region-beginning) (region-end)
  13029. (let ((org-last-tags-completion-table
  13030. (if (derived-mode-p 'org-mode)
  13031. (org-tag-add-to-alist
  13032. (org-get-buffer-tags)
  13033. (org-global-tags-completion-table))
  13034. (org-global-tags-completion-table))))
  13035. (completing-read
  13036. "Tag: " 'org-tags-completion-function nil nil nil
  13037. 'org-tags-history))
  13038. (progn
  13039. (message "[s]et or [r]emove? ")
  13040. (equal (read-char-exclusive) ?r))))
  13041. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13042. (let ((agendap (equal major-mode 'org-agenda-mode))
  13043. l1 l2 m buf pos newhead (cnt 0))
  13044. (goto-char end)
  13045. (setq l2 (1- (org-current-line)))
  13046. (goto-char beg)
  13047. (setq l1 (org-current-line))
  13048. (cl-loop for l from l1 to l2 do
  13049. (org-goto-line l)
  13050. (setq m (get-text-property (point) 'org-hd-marker))
  13051. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13052. (and agendap m))
  13053. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13054. pos (if agendap m (point)))
  13055. (with-current-buffer buf
  13056. (save-excursion
  13057. (save-restriction
  13058. (goto-char pos)
  13059. (setq cnt (1+ cnt))
  13060. (org-toggle-tag tag (if off 'off 'on))
  13061. (setq newhead (org-get-heading)))))
  13062. (and agendap (org-agenda-change-all-lines newhead m))))
  13063. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13064. (defun org-tags-completion-function (string _predicate &optional flag)
  13065. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13066. (confirm (lambda (x) (stringp (car x)))))
  13067. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13068. (setq s1 (match-string 1 string)
  13069. s2 (match-string 2 string))
  13070. (setq s1 "" s2 string))
  13071. (cond
  13072. ((eq flag nil)
  13073. ;; try completion
  13074. (setq rtn (try-completion s2 ctable confirm))
  13075. (when (stringp rtn)
  13076. (setq rtn
  13077. (concat s1 s2 (substring rtn (length s2))
  13078. (if (and org-add-colon-after-tag-completion
  13079. (assoc rtn ctable))
  13080. ":" ""))))
  13081. rtn)
  13082. ((eq flag t)
  13083. ;; all-completions
  13084. (all-completions s2 ctable confirm))
  13085. ((eq flag 'lambda)
  13086. ;; exact match?
  13087. (assoc s2 ctable)))))
  13088. (defun org-fast-tag-insert (kwd tags face &optional end)
  13089. "Insert KDW, and the TAGS, the latter with face FACE.
  13090. Also insert END."
  13091. (insert (format "%-12s" (concat kwd ":"))
  13092. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13093. (or end "")))
  13094. (defun org-fast-tag-show-exit (flag)
  13095. (save-excursion
  13096. (org-goto-line 3)
  13097. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13098. (replace-match ""))
  13099. (when flag
  13100. (end-of-line 1)
  13101. (org-move-to-column (- (window-width) 19) t)
  13102. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13103. (defun org-set-current-tags-overlay (current prefix)
  13104. "Add an overlay to CURRENT tag with PREFIX."
  13105. (let ((s (org-make-tag-string current)))
  13106. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13107. (org-overlay-display org-tags-overlay (concat prefix s))))
  13108. (defvar org-last-tag-selection-key nil)
  13109. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13110. "Fast tag selection with single keys.
  13111. CURRENT is the current list of tags in the headline, INHERITED is the
  13112. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13113. possibly with grouping information. TODO-TABLE is a similar table with
  13114. TODO keywords, should these have keys assigned to them.
  13115. If the keys are nil, a-z are automatically assigned.
  13116. Returns the new tags string, or nil to not change the current settings."
  13117. (let* ((fulltable (append table todo-table))
  13118. (maxlen (apply 'max (mapcar
  13119. (lambda (x)
  13120. (if (stringp (car x)) (string-width (car x)) 0))
  13121. fulltable)))
  13122. (buf (current-buffer))
  13123. (expert (eq org-fast-tag-selection-single-key 'expert))
  13124. (buffer-tags nil)
  13125. (fwidth (+ maxlen 3 1 3))
  13126. (ncol (/ (- (window-width) 4) fwidth))
  13127. (i-face 'org-done)
  13128. (c-face 'org-todo)
  13129. tg cnt e c char c1 c2 ntable tbl rtn
  13130. ov-start ov-end ov-prefix
  13131. (exit-after-next org-fast-tag-selection-single-key)
  13132. (done-keywords org-done-keywords)
  13133. groups ingroup intaggroup)
  13134. (save-excursion
  13135. (beginning-of-line)
  13136. (if (looking-at org-tag-line-re)
  13137. (setq ov-start (match-beginning 1)
  13138. ov-end (match-end 1)
  13139. ov-prefix "")
  13140. (setq ov-start (1- (point-at-eol))
  13141. ov-end (1+ ov-start))
  13142. (skip-chars-forward "^\n\r")
  13143. (setq ov-prefix
  13144. (concat
  13145. (buffer-substring (1- (point)) (point))
  13146. (if (> (current-column) org-tags-column)
  13147. " "
  13148. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13149. (move-overlay org-tags-overlay ov-start ov-end)
  13150. (save-window-excursion
  13151. (if expert
  13152. (set-buffer (get-buffer-create " *Org tags*"))
  13153. (delete-other-windows)
  13154. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13155. (org-switch-to-buffer-other-window " *Org tags*"))
  13156. (erase-buffer)
  13157. (setq-local org-done-keywords done-keywords)
  13158. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13159. (org-fast-tag-insert "Current" current c-face "\n\n")
  13160. (org-fast-tag-show-exit exit-after-next)
  13161. (org-set-current-tags-overlay current ov-prefix)
  13162. (setq tbl fulltable char ?a cnt 0)
  13163. (while (setq e (pop tbl))
  13164. (cond
  13165. ((eq (car e) :startgroup)
  13166. (push '() groups) (setq ingroup t)
  13167. (unless (zerop cnt)
  13168. (setq cnt 0)
  13169. (insert "\n"))
  13170. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13171. ((eq (car e) :endgroup)
  13172. (setq ingroup nil cnt 0)
  13173. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13174. ((eq (car e) :startgrouptag)
  13175. (setq intaggroup t)
  13176. (unless (zerop cnt)
  13177. (setq cnt 0)
  13178. (insert "\n"))
  13179. (insert "[ "))
  13180. ((eq (car e) :endgrouptag)
  13181. (setq intaggroup nil cnt 0)
  13182. (insert "]\n"))
  13183. ((equal e '(:newline))
  13184. (unless (zerop cnt)
  13185. (setq cnt 0)
  13186. (insert "\n")
  13187. (setq e (car tbl))
  13188. (while (equal (car tbl) '(:newline))
  13189. (insert "\n")
  13190. (setq tbl (cdr tbl)))))
  13191. ((equal e '(:grouptags)) (insert " : "))
  13192. (t
  13193. (setq tg (copy-sequence (car e)) c2 nil)
  13194. (if (cdr e)
  13195. (setq c (cdr e))
  13196. ;; automatically assign a character.
  13197. (setq c1 (string-to-char
  13198. (downcase (substring
  13199. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13200. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13201. (while (or (rassoc char ntable) (rassoc char table))
  13202. (setq char (1+ char)))
  13203. (setq c2 c1))
  13204. (setq c (or c2 char)))
  13205. (when ingroup (push tg (car groups)))
  13206. (setq tg (org-add-props tg nil 'face
  13207. (cond
  13208. ((not (assoc tg table))
  13209. (org-get-todo-face tg))
  13210. ((member tg current) c-face)
  13211. ((member tg inherited) i-face))))
  13212. (when (equal (caar tbl) :grouptags)
  13213. (org-add-props tg nil 'face 'org-tag-group))
  13214. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13215. (insert "[" c "] " tg (make-string
  13216. (- fwidth 4 (length tg)) ?\ ))
  13217. (push (cons tg c) ntable)
  13218. (when (= (cl-incf cnt) ncol)
  13219. (insert "\n")
  13220. (when (or ingroup intaggroup) (insert " "))
  13221. (setq cnt 0)))))
  13222. (setq ntable (nreverse ntable))
  13223. (insert "\n")
  13224. (goto-char (point-min))
  13225. (unless expert (org-fit-window-to-buffer))
  13226. (setq rtn
  13227. (catch 'exit
  13228. (while t
  13229. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  13230. (if (not groups) "no " "")
  13231. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13232. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13233. (setq org-last-tag-selection-key c)
  13234. (cond
  13235. ((= c ?\r) (throw 'exit t))
  13236. ((= c ?!)
  13237. (setq groups (not groups))
  13238. (goto-char (point-min))
  13239. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13240. ((= c ?\C-c)
  13241. (if (not expert)
  13242. (org-fast-tag-show-exit
  13243. (setq exit-after-next (not exit-after-next)))
  13244. (setq expert nil)
  13245. (delete-other-windows)
  13246. (set-window-buffer (split-window-vertically) " *Org tags*")
  13247. (org-switch-to-buffer-other-window " *Org tags*")
  13248. (org-fit-window-to-buffer)))
  13249. ((or (= c ?\C-g)
  13250. (and (= c ?q) (not (rassoc c ntable))))
  13251. (delete-overlay org-tags-overlay)
  13252. (setq quit-flag t))
  13253. ((= c ?\ )
  13254. (setq current nil)
  13255. (when exit-after-next (setq exit-after-next 'now)))
  13256. ((= c ?\t)
  13257. (condition-case nil
  13258. (setq tg (completing-read
  13259. "Tag: "
  13260. (or buffer-tags
  13261. (with-current-buffer buf
  13262. (setq buffer-tags
  13263. (org-get-buffer-tags))))))
  13264. (quit (setq tg "")))
  13265. (when (string-match "\\S-" tg)
  13266. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13267. (if (member tg current)
  13268. (setq current (delete tg current))
  13269. (push tg current)))
  13270. (when exit-after-next (setq exit-after-next 'now)))
  13271. ((setq e (rassoc c todo-table) tg (car e))
  13272. (with-current-buffer buf
  13273. (save-excursion (org-todo tg)))
  13274. (when exit-after-next (setq exit-after-next 'now)))
  13275. ((setq e (rassoc c ntable) tg (car e))
  13276. (if (member tg current)
  13277. (setq current (delete tg current))
  13278. (cl-loop for g in groups do
  13279. (when (member tg g)
  13280. (dolist (x g) (setq current (delete x current)))))
  13281. (push tg current))
  13282. (when exit-after-next (setq exit-after-next 'now))))
  13283. ;; Create a sorted list
  13284. (setq current
  13285. (sort current
  13286. (lambda (a b)
  13287. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13288. (when (eq exit-after-next 'now) (throw 'exit t))
  13289. (goto-char (point-min))
  13290. (beginning-of-line 2)
  13291. (delete-region (point) (point-at-eol))
  13292. (org-fast-tag-insert "Current" current c-face)
  13293. (org-set-current-tags-overlay current ov-prefix)
  13294. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  13295. (while (re-search-forward tag-re nil t)
  13296. (let ((tag (match-string 1)))
  13297. (add-text-properties
  13298. (match-beginning 1) (match-end 1)
  13299. (list 'face
  13300. (cond
  13301. ((member tag current) c-face)
  13302. ((member tag inherited) i-face)
  13303. (t (get-text-property (match-beginning 1) '
  13304. face))))))))
  13305. (goto-char (point-min)))))
  13306. (delete-overlay org-tags-overlay)
  13307. (if rtn
  13308. (mapconcat 'identity current ":")
  13309. nil))))
  13310. (defun org-make-tag-string (tags)
  13311. "Return string associated to TAGS.
  13312. TAGS is a list of strings."
  13313. (if (null tags) ""
  13314. (format ":%s:" (mapconcat #'identity tags ":"))))
  13315. (defun org--get-local-tags ()
  13316. "Return list of tags for the current headline.
  13317. Assume point is at the beginning of the headline."
  13318. (and (looking-at org-tag-line-re)
  13319. (split-string (match-string-no-properties 2) ":" t)))
  13320. (defun org-get-tags (&optional pos local)
  13321. "Get the list of tags specified in the current headline.
  13322. When argument POS is non-nil, retrieve tags for headline at POS.
  13323. Accoring to `org-use-tags-inheritance', tags may be inherited
  13324. from parent headlines, and from the whole document, through
  13325. `org-file-tags'. However, when optional argument LOCAL is
  13326. non-nil, only return tags really specified in the considered
  13327. headline.
  13328. Inherited tags have the `inherited' text property."
  13329. (if (and org-trust-scanner-tags
  13330. (or (not pos) (eq pos (point)))
  13331. (not local))
  13332. org-scanner-tags
  13333. (org-with-point-at (or pos (point))
  13334. (unless (org-before-first-heading-p)
  13335. (org-back-to-heading t)
  13336. (let ((tags (org--get-local-tags)))
  13337. (if (or local (not org-use-tag-inheritance)) tags
  13338. (while (org-up-heading-safe)
  13339. (setq tags (append (mapcar #'org-add-prop-inherited
  13340. (org--get-local-tags))
  13341. tags)))
  13342. (org-remove-uninherited-tags
  13343. (delete-dups (append org-file-tags tags)))))))))
  13344. (defun org-get-buffer-tags ()
  13345. "Get a table of all tags used in the buffer, for completion."
  13346. (org-with-point-at 1
  13347. (let (tags)
  13348. (while (re-search-forward org-tag-line-re nil t)
  13349. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  13350. tags)))
  13351. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  13352. ;;;; The mapping API
  13353. (defvar org-agenda-skip-comment-trees)
  13354. (defvar org-agenda-skip-function)
  13355. (defun org-map-entries (func &optional match scope &rest skip)
  13356. "Call FUNC at each headline selected by MATCH in SCOPE.
  13357. FUNC is a function or a lisp form. The function will be called without
  13358. arguments, with the cursor positioned at the beginning of the headline.
  13359. The return values of all calls to the function will be collected and
  13360. returned as a list.
  13361. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13362. does not need to preserve point. After evaluation, the cursor will be
  13363. moved to the end of the line (presumably of the headline of the
  13364. processed entry) and search continues from there. Under some
  13365. circumstances, this may not produce the wanted results. For example,
  13366. if you have removed (e.g. archived) the current (sub)tree it could
  13367. mean that the next entry will be skipped entirely. In such cases, you
  13368. can specify the position from where search should continue by making
  13369. FUNC set the variable `org-map-continue-from' to the desired buffer
  13370. position.
  13371. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13372. Only headlines that are matched by this query will be considered during
  13373. the iteration. When MATCH is nil or t, all headlines will be
  13374. visited by the iteration.
  13375. SCOPE determines the scope of this command. It can be any of:
  13376. nil The current buffer, respecting the restriction if any
  13377. tree The subtree started with the entry at point
  13378. region The entries within the active region, if any
  13379. region-start-level
  13380. The entries within the active region, but only those at
  13381. the same level than the first one.
  13382. file The current buffer, without restriction
  13383. file-with-archives
  13384. The current buffer, and any archives associated with it
  13385. agenda All agenda files
  13386. agenda-with-archives
  13387. All agenda files with any archive files associated with them
  13388. \(file1 file2 ...)
  13389. If this is a list, all files in the list will be scanned
  13390. The remaining args are treated as settings for the skipping facilities of
  13391. the scanner. The following items can be given here:
  13392. archive skip trees with the archive tag
  13393. comment skip trees with the COMMENT keyword
  13394. function or Emacs Lisp form:
  13395. will be used as value for `org-agenda-skip-function', so
  13396. whenever the function returns a position, FUNC will not be
  13397. called for that entry and search will continue from the
  13398. position returned
  13399. If your function needs to retrieve the tags including inherited tags
  13400. at the *current* entry, you can use the value of the variable
  13401. `org-scanner-tags' which will be much faster than getting the value
  13402. with `org-get-tags'. If your function gets properties with
  13403. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  13404. to t around the call to `org-entry-properties' to get the same speedup.
  13405. Note that if your function moves around to retrieve tags and properties at
  13406. a *different* entry, you cannot use these techniques."
  13407. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  13408. (not (org-region-active-p)))
  13409. (let* ((org-agenda-archives-mode nil) ; just to make sure
  13410. (org-agenda-skip-archived-trees (memq 'archive skip))
  13411. (org-agenda-skip-comment-trees (memq 'comment skip))
  13412. (org-agenda-skip-function
  13413. (car (org-delete-all '(comment archive) skip)))
  13414. (org-tags-match-list-sublevels t)
  13415. (start-level (eq scope 'region-start-level))
  13416. matcher res
  13417. org-todo-keywords-for-agenda
  13418. org-done-keywords-for-agenda
  13419. org-todo-keyword-alist-for-agenda
  13420. org-tag-alist-for-agenda
  13421. org--matcher-tags-todo-only)
  13422. (cond
  13423. ((eq match t) (setq matcher t))
  13424. ((eq match nil) (setq matcher t))
  13425. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  13426. (save-excursion
  13427. (save-restriction
  13428. (cond ((eq scope 'tree)
  13429. (org-back-to-heading t)
  13430. (org-narrow-to-subtree)
  13431. (setq scope nil))
  13432. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  13433. (org-region-active-p))
  13434. ;; If needed, set start-level to a string like "2"
  13435. (when start-level
  13436. (save-excursion
  13437. (goto-char (region-beginning))
  13438. (unless (org-at-heading-p) (outline-next-heading))
  13439. (setq start-level (org-current-level))))
  13440. (narrow-to-region (region-beginning)
  13441. (save-excursion
  13442. (goto-char (region-end))
  13443. (unless (and (bolp) (org-at-heading-p))
  13444. (outline-next-heading))
  13445. (point)))
  13446. (setq scope nil)))
  13447. (if (not scope)
  13448. (progn
  13449. (org-agenda-prepare-buffers
  13450. (and buffer-file-name (list buffer-file-name)))
  13451. (setq res
  13452. (org-scan-tags
  13453. func matcher org--matcher-tags-todo-only start-level)))
  13454. ;; Get the right scope
  13455. (cond
  13456. ((and scope (listp scope) (symbolp (car scope)))
  13457. (setq scope (eval scope)))
  13458. ((eq scope 'agenda)
  13459. (setq scope (org-agenda-files t)))
  13460. ((eq scope 'agenda-with-archives)
  13461. (setq scope (org-agenda-files t))
  13462. (setq scope (org-add-archive-files scope)))
  13463. ((eq scope 'file)
  13464. (setq scope (and buffer-file-name (list buffer-file-name))))
  13465. ((eq scope 'file-with-archives)
  13466. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  13467. (org-agenda-prepare-buffers scope)
  13468. (dolist (file scope)
  13469. (with-current-buffer (org-find-base-buffer-visiting file)
  13470. (org-with-wide-buffer
  13471. (goto-char (point-min))
  13472. (setq res
  13473. (append
  13474. res
  13475. (org-scan-tags
  13476. func matcher org--matcher-tags-todo-only)))))))))
  13477. res)))
  13478. ;;; Properties API
  13479. (defconst org-special-properties
  13480. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  13481. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  13482. "The special properties valid in Org mode.
  13483. These are properties that are not defined in the property drawer,
  13484. but in some other way.")
  13485. (defconst org-default-properties
  13486. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  13487. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  13488. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  13489. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  13490. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  13491. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  13492. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  13493. "Some properties that are used by Org mode for various purposes.
  13494. Being in this list makes sure that they are offered for completion.")
  13495. (defun org--valid-property-p (property)
  13496. "Non nil when string PROPERTY is a valid property name."
  13497. (not
  13498. (or (equal property "")
  13499. (string-match-p "\\s-" property))))
  13500. (defun org--update-property-plist (key val props)
  13501. "Associate KEY to VAL in alist PROPS.
  13502. Modifications are made by side-effect. Return new alist."
  13503. (let* ((appending (string= (substring key -1) "+"))
  13504. (key (if appending (substring key 0 -1) key))
  13505. (old (assoc-string key props t)))
  13506. (if (not old) (cons (cons key val) props)
  13507. (setcdr old (if appending (concat (cdr old) " " val) val))
  13508. props)))
  13509. (defun org-get-property-block (&optional beg force)
  13510. "Return the (beg . end) range of the body of the property drawer.
  13511. BEG is the beginning of the current subtree, or of the part
  13512. before the first headline. If it is not given, it will be found.
  13513. If the drawer does not exist, create it if FORCE is non-nil, or
  13514. return nil."
  13515. (org-with-wide-buffer
  13516. (when beg (goto-char beg))
  13517. (unless (org-before-first-heading-p)
  13518. (let ((beg (cond (beg)
  13519. ((or (not (featurep 'org-inlinetask))
  13520. (org-inlinetask-in-task-p))
  13521. (org-back-to-heading t))
  13522. (t (org-with-limited-levels (org-back-to-heading t))))))
  13523. (forward-line)
  13524. (when (looking-at-p org-planning-line-re) (forward-line))
  13525. (cond ((looking-at org-property-drawer-re)
  13526. (forward-line)
  13527. (cons (point) (progn (goto-char (match-end 0))
  13528. (line-beginning-position))))
  13529. (force
  13530. (goto-char beg)
  13531. (org-insert-property-drawer)
  13532. (let ((pos (save-excursion (search-forward ":END:")
  13533. (line-beginning-position))))
  13534. (cons pos pos))))))))
  13535. (defun org-at-property-p ()
  13536. "Non-nil when point is inside a property drawer.
  13537. See `org-property-re' for match data, if applicable."
  13538. (save-excursion
  13539. (beginning-of-line)
  13540. (and (looking-at org-property-re)
  13541. (let ((property-drawer (save-match-data (org-get-property-block))))
  13542. (and property-drawer
  13543. (>= (point) (car property-drawer))
  13544. (< (point) (cdr property-drawer)))))))
  13545. (defun org-property-action ()
  13546. "Do an action on properties."
  13547. (interactive)
  13548. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  13549. (let ((c (read-char-exclusive)))
  13550. (cl-case c
  13551. (?s (call-interactively #'org-set-property))
  13552. (?d (call-interactively #'org-delete-property))
  13553. (?D (call-interactively #'org-delete-property-globally))
  13554. (?c (call-interactively #'org-compute-property-at-point))
  13555. (otherwise (user-error "No such property action %c" c)))))
  13556. (defun org-inc-effort ()
  13557. "Increment the value of the effort property in the current entry."
  13558. (interactive)
  13559. (org-set-effort t))
  13560. (defvar org-clock-effort) ; Defined in org-clock.el.
  13561. (defvar org-clock-current-task) ; Defined in org-clock.el.
  13562. (defun org-set-effort (&optional increment value)
  13563. "Set the effort property of the current entry.
  13564. If INCREMENT is non-nil, set the property to the next allowed
  13565. value. Otherwise, if optional argument VALUE is provided, use
  13566. it. Eventually, prompt for the new value if none of the previous
  13567. variables is set."
  13568. (interactive "P")
  13569. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  13570. (current (org-entry-get nil org-effort-property))
  13571. (value
  13572. (cond
  13573. (increment
  13574. (unless allowed (user-error "Allowed effort values are not set"))
  13575. (or (cl-caadr (member (list current) allowed))
  13576. (user-error "Unknown value %S among allowed values" current)))
  13577. (value
  13578. (if (stringp value) value
  13579. (error "Invalid effort value: %S" value)))
  13580. (t
  13581. (let ((must-match
  13582. (and allowed
  13583. (not (get-text-property 0 'org-unrestricted
  13584. (caar allowed))))))
  13585. (completing-read "Effort: " allowed nil must-match))))))
  13586. (unless (equal current value)
  13587. (org-entry-put nil org-effort-property value))
  13588. (org-refresh-property '((effort . identity)
  13589. (effort-minutes . org-duration-to-minutes))
  13590. value)
  13591. (when (equal (org-get-heading t t t t)
  13592. (bound-and-true-p org-clock-current-task))
  13593. (setq org-clock-effort (org-get-at-bol 'effort))
  13594. (org-clock-update-mode-line))
  13595. (message "%s is now %s" org-effort-property value)))
  13596. (defun org-entry-properties (&optional pom which)
  13597. "Get all properties of the current entry.
  13598. When POM is a buffer position, get all properties from the entry
  13599. there instead.
  13600. This includes the TODO keyword, the tags, time strings for
  13601. deadline, scheduled, and clocking, and any additional properties
  13602. defined in the entry.
  13603. If WHICH is nil or `all', get all properties. If WHICH is
  13604. `special' or `standard', only get that subclass. If WHICH is
  13605. a string, only get that property.
  13606. Return value is an alist. Keys are properties, as upcased
  13607. strings."
  13608. (org-with-point-at pom
  13609. (when (and (derived-mode-p 'org-mode)
  13610. (ignore-errors (org-back-to-heading t)))
  13611. (catch 'exit
  13612. (let* ((beg (point))
  13613. (specific (and (stringp which) (upcase which)))
  13614. (which (cond ((not specific) which)
  13615. ((member specific org-special-properties) 'special)
  13616. (t 'standard)))
  13617. props)
  13618. ;; Get the special properties, like TODO and TAGS.
  13619. (when (memq which '(nil all special))
  13620. (when (or (not specific) (string= specific "CLOCKSUM"))
  13621. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  13622. (when clocksum
  13623. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  13624. props)))
  13625. (when specific (throw 'exit props)))
  13626. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  13627. (let ((clocksumt (get-text-property (point)
  13628. :org-clock-minutes-today)))
  13629. (when clocksumt
  13630. (push (cons "CLOCKSUM_T"
  13631. (org-duration-from-minutes clocksumt))
  13632. props)))
  13633. (when specific (throw 'exit props)))
  13634. (when (or (not specific) (string= specific "ITEM"))
  13635. (let ((case-fold-search nil))
  13636. (when (looking-at org-complex-heading-regexp)
  13637. (push (cons "ITEM"
  13638. (let ((title (match-string-no-properties 4)))
  13639. (if (org-string-nw-p title)
  13640. (org-remove-tabs title)
  13641. "")))
  13642. props)))
  13643. (when specific (throw 'exit props)))
  13644. (when (or (not specific) (string= specific "TODO"))
  13645. (let ((case-fold-search nil))
  13646. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  13647. (push (cons "TODO" (match-string-no-properties 2)) props)))
  13648. (when specific (throw 'exit props)))
  13649. (when (or (not specific) (string= specific "PRIORITY"))
  13650. (push (cons "PRIORITY"
  13651. (if (looking-at org-priority-regexp)
  13652. (match-string-no-properties 2)
  13653. (char-to-string org-default-priority)))
  13654. props)
  13655. (when specific (throw 'exit props)))
  13656. (when (or (not specific) (string= specific "FILE"))
  13657. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  13658. props)
  13659. (when specific (throw 'exit props)))
  13660. (when (or (not specific) (string= specific "TAGS"))
  13661. (let ((tags (org-get-tags nil t)))
  13662. (when tags
  13663. (push (cons "TAGS" (org-make-tag-string tags))
  13664. props)))
  13665. (when specific (throw 'exit props)))
  13666. (when (or (not specific) (string= specific "ALLTAGS"))
  13667. (let ((tags (org-get-tags)))
  13668. (when tags
  13669. (push (cons "ALLTAGS" (org-make-tag-string tags))
  13670. props)))
  13671. (when specific (throw 'exit props)))
  13672. (when (or (not specific) (string= specific "BLOCKED"))
  13673. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  13674. (when specific (throw 'exit props)))
  13675. (when (or (not specific)
  13676. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  13677. (forward-line)
  13678. (when (looking-at-p org-planning-line-re)
  13679. (end-of-line)
  13680. (let ((bol (line-beginning-position))
  13681. ;; Backward compatibility: time keywords used to
  13682. ;; be configurable (before 8.3). Make sure we
  13683. ;; get the correct keyword.
  13684. (key-assoc `(("CLOSED" . ,org-closed-string)
  13685. ("DEADLINE" . ,org-deadline-string)
  13686. ("SCHEDULED" . ,org-scheduled-string))))
  13687. (dolist (pair (if specific (list (assoc specific key-assoc))
  13688. key-assoc))
  13689. (save-excursion
  13690. (when (search-backward (cdr pair) bol t)
  13691. (goto-char (match-end 0))
  13692. (skip-chars-forward " \t")
  13693. (and (looking-at org-ts-regexp-both)
  13694. (push (cons (car pair)
  13695. (match-string-no-properties 0))
  13696. props)))))))
  13697. (when specific (throw 'exit props)))
  13698. (when (or (not specific)
  13699. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  13700. (let ((find-ts
  13701. (lambda (end ts)
  13702. ;; Fix next time-stamp before END. TS is the
  13703. ;; list of time-stamps found so far.
  13704. (let ((ts ts)
  13705. (regexp (cond
  13706. ((string= specific "TIMESTAMP")
  13707. org-ts-regexp)
  13708. ((string= specific "TIMESTAMP_IA")
  13709. org-ts-regexp-inactive)
  13710. ((assoc "TIMESTAMP_IA" ts)
  13711. org-ts-regexp)
  13712. ((assoc "TIMESTAMP" ts)
  13713. org-ts-regexp-inactive)
  13714. (t org-ts-regexp-both))))
  13715. (catch 'next
  13716. (while (re-search-forward regexp end t)
  13717. (backward-char)
  13718. (let ((object (org-element-context)))
  13719. ;; Accept to match timestamps in node
  13720. ;; properties, too.
  13721. (when (memq (org-element-type object)
  13722. '(node-property timestamp))
  13723. (let ((type
  13724. (org-element-property :type object)))
  13725. (cond
  13726. ((and (memq type '(active active-range))
  13727. (not (equal specific "TIMESTAMP_IA")))
  13728. (unless (assoc "TIMESTAMP" ts)
  13729. (push (cons "TIMESTAMP"
  13730. (org-element-property
  13731. :raw-value object))
  13732. ts)
  13733. (when specific (throw 'exit ts))))
  13734. ((and (memq type '(inactive inactive-range))
  13735. (not (string= specific "TIMESTAMP")))
  13736. (unless (assoc "TIMESTAMP_IA" ts)
  13737. (push (cons "TIMESTAMP_IA"
  13738. (org-element-property
  13739. :raw-value object))
  13740. ts)
  13741. (when specific (throw 'exit ts))))))
  13742. ;; Both timestamp types are found,
  13743. ;; move to next part.
  13744. (when (= (length ts) 2) (throw 'next ts)))))
  13745. ts)))))
  13746. (goto-char beg)
  13747. ;; First look for timestamps within headline.
  13748. (let ((ts (funcall find-ts (line-end-position) nil)))
  13749. (if (= (length ts) 2) (setq props (nconc ts props))
  13750. ;; Then find timestamps in the section, skipping
  13751. ;; planning line.
  13752. (let ((end (save-excursion (outline-next-heading))))
  13753. (forward-line)
  13754. (when (looking-at-p org-planning-line-re) (forward-line))
  13755. (setq props (nconc (funcall find-ts end ts) props))))))))
  13756. ;; Get the standard properties, like :PROP:.
  13757. (when (memq which '(nil all standard))
  13758. ;; If we are looking after a specific property, delegate
  13759. ;; to `org-entry-get', which is faster. However, make an
  13760. ;; exception for "CATEGORY", since it can be also set
  13761. ;; through keywords (i.e. #+CATEGORY).
  13762. (if (and specific (not (equal specific "CATEGORY")))
  13763. (let ((value (org-entry-get beg specific nil t)))
  13764. (throw 'exit (and value (list (cons specific value)))))
  13765. (let ((range (org-get-property-block beg)))
  13766. (when range
  13767. (let ((end (cdr range)) seen-base)
  13768. (goto-char (car range))
  13769. ;; Unlike to `org--update-property-plist', we
  13770. ;; handle the case where base values is found
  13771. ;; after its extension. We also forbid standard
  13772. ;; properties to be named as special properties.
  13773. (while (re-search-forward org-property-re end t)
  13774. (let* ((key (upcase (match-string-no-properties 2)))
  13775. (extendp (string-match-p "\\+\\'" key))
  13776. (key-base (if extendp (substring key 0 -1) key))
  13777. (value (match-string-no-properties 3)))
  13778. (cond
  13779. ((member-ignore-case key-base org-special-properties))
  13780. (extendp
  13781. (setq props
  13782. (org--update-property-plist key value props)))
  13783. ((member key seen-base))
  13784. (t (push key seen-base)
  13785. (let ((p (assoc-string key props t)))
  13786. (if p (setcdr p (concat value " " (cdr p)))
  13787. (push (cons key value) props))))))))))))
  13788. (unless (assoc "CATEGORY" props)
  13789. (push (cons "CATEGORY" (org-get-category beg)) props)
  13790. (when (string= specific "CATEGORY") (throw 'exit props)))
  13791. ;; Return value.
  13792. props)))))
  13793. (defun org--property-local-values (property literal-nil)
  13794. "Return value for PROPERTY in current entry.
  13795. Value is a list whose car is the base value for PROPERTY and cdr
  13796. a list of accumulated values. Return nil if neither is found in
  13797. the entry. Also return nil when PROPERTY is set to \"nil\",
  13798. unless LITERAL-NIL is non-nil."
  13799. (let ((range (org-get-property-block)))
  13800. (when range
  13801. (goto-char (car range))
  13802. (let* ((case-fold-search t)
  13803. (end (cdr range))
  13804. (value
  13805. ;; Base value.
  13806. (save-excursion
  13807. (let ((v (and (re-search-forward
  13808. (org-re-property property nil t) end t)
  13809. (match-string-no-properties 3))))
  13810. (list (if literal-nil v (org-not-nil v)))))))
  13811. ;; Find additional values.
  13812. (let* ((property+ (org-re-property (concat property "+") nil t)))
  13813. (while (re-search-forward property+ end t)
  13814. (push (match-string-no-properties 3) value)))
  13815. ;; Return final values.
  13816. (and (not (equal value '(nil))) (nreverse value))))))
  13817. (defun org--property-global-value (property literal-nil)
  13818. "Return value for PROPERTY in current buffer.
  13819. Return value is a string. Return nil if property is not set
  13820. globally. Also return nil when PROPERTY is set to \"nil\",
  13821. unless LITERAL-NIL is non-nil."
  13822. (let ((global
  13823. (cdr (or (assoc-string property org-file-properties t)
  13824. (assoc-string property org-global-properties t)
  13825. (assoc-string property org-global-properties-fixed t)))))
  13826. (if literal-nil global (org-not-nil global))))
  13827. (defun org-entry-get (pom property &optional inherit literal-nil)
  13828. "Get value of PROPERTY for entry or content at point-or-marker POM.
  13829. If INHERIT is non-nil and the entry does not have the property,
  13830. then also check higher levels of the hierarchy. If INHERIT is
  13831. the symbol `selective', use inheritance only if the setting in
  13832. `org-use-property-inheritance' selects PROPERTY for inheritance.
  13833. If the property is present but empty, the return value is the
  13834. empty string. If the property is not present at all, nil is
  13835. returned. In any other case, return the value as a string.
  13836. Search is case-insensitive.
  13837. If LITERAL-NIL is set, return the string value \"nil\" as
  13838. a string, do not interpret it as the list atom nil. This is used
  13839. for inheritance when a \"nil\" value can supersede a non-nil
  13840. value higher up the hierarchy."
  13841. (org-with-point-at pom
  13842. (cond
  13843. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  13844. ;; We need a special property. Use `org-entry-properties' to
  13845. ;; retrieve it, but specify the wanted property.
  13846. (cdr (assoc-string property (org-entry-properties nil property))))
  13847. ((and inherit
  13848. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  13849. (org-entry-get-with-inheritance property literal-nil))
  13850. (t
  13851. (let* ((local (org--property-local-values property literal-nil))
  13852. (value (and local (mapconcat #'identity (delq nil local) " "))))
  13853. (if literal-nil value (org-not-nil value)))))))
  13854. (defun org-property-or-variable-value (var &optional inherit)
  13855. "Check if there is a property fixing the value of VAR.
  13856. If yes, return this value. If not, return the current value of the variable."
  13857. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  13858. (if (and prop (stringp prop) (string-match "\\S-" prop))
  13859. (read prop)
  13860. (symbol-value var))))
  13861. (defun org-entry-delete (pom property)
  13862. "Delete PROPERTY from entry at point-or-marker POM.
  13863. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  13864. non-nil when a property was removed."
  13865. (org-with-point-at pom
  13866. (pcase (org-get-property-block)
  13867. (`(,begin . ,origin)
  13868. (let* ((end (copy-marker origin))
  13869. (re (org-re-property
  13870. (concat (regexp-quote property) "\\+?") t t)))
  13871. (goto-char begin)
  13872. (while (re-search-forward re end t)
  13873. (delete-region (match-beginning 0) (line-beginning-position 2)))
  13874. ;; If drawer is empty, remove it altogether.
  13875. (when (= begin end)
  13876. (delete-region (line-beginning-position 0)
  13877. (line-beginning-position 2)))
  13878. ;; Return non-nil if some property was removed.
  13879. (prog1 (/= end origin) (set-marker end nil))))
  13880. (_ nil))))
  13881. ;; Multi-values properties are properties that contain multiple values
  13882. ;; These values are assumed to be single words, separated by whitespace.
  13883. (defun org-entry-add-to-multivalued-property (pom property value)
  13884. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  13885. (let* ((old (org-entry-get pom property))
  13886. (values (and old (split-string old))))
  13887. (setq value (org-entry-protect-space value))
  13888. (unless (member value values)
  13889. (setq values (append values (list value)))
  13890. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13891. (defun org-entry-remove-from-multivalued-property (pom property value)
  13892. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  13893. (let* ((old (org-entry-get pom property))
  13894. (values (and old (split-string old))))
  13895. (setq value (org-entry-protect-space value))
  13896. (when (member value values)
  13897. (setq values (delete value values))
  13898. (org-entry-put pom property (mapconcat #'identity values " ")))))
  13899. (defun org-entry-member-in-multivalued-property (pom property value)
  13900. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  13901. (let* ((old (org-entry-get pom property))
  13902. (values (and old (split-string old))))
  13903. (setq value (org-entry-protect-space value))
  13904. (member value values)))
  13905. (defun org-entry-get-multivalued-property (pom property)
  13906. "Return a list of values in a multivalued property."
  13907. (let* ((value (org-entry-get pom property))
  13908. (values (and value (split-string value))))
  13909. (mapcar #'org-entry-restore-space values)))
  13910. (defun org-entry-put-multivalued-property (pom property &rest values)
  13911. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  13912. VALUES should be a list of strings. Spaces will be protected."
  13913. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  13914. (let* ((value (org-entry-get pom property))
  13915. (values (and value (split-string value))))
  13916. (mapcar #'org-entry-restore-space values)))
  13917. (defun org-entry-protect-space (s)
  13918. "Protect spaces and newline in string S."
  13919. (while (string-match " " s)
  13920. (setq s (replace-match "%20" t t s)))
  13921. (while (string-match "\n" s)
  13922. (setq s (replace-match "%0A" t t s)))
  13923. s)
  13924. (defun org-entry-restore-space (s)
  13925. "Restore spaces and newline in string S."
  13926. (while (string-match "%20" s)
  13927. (setq s (replace-match " " t t s)))
  13928. (while (string-match "%0A" s)
  13929. (setq s (replace-match "\n" t t s)))
  13930. s)
  13931. (defvar org-entry-property-inherited-from (make-marker)
  13932. "Marker pointing to the entry from where a property was inherited.
  13933. Each call to `org-entry-get-with-inheritance' will set this marker to the
  13934. location of the entry where the inheritance search matched. If there was
  13935. no match, the marker will point nowhere.
  13936. Note that also `org-entry-get' calls this function, if the INHERIT flag
  13937. is set.")
  13938. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  13939. "Get PROPERTY of entry or content at point, search higher levels if needed.
  13940. The search will stop at the first ancestor which has the property defined.
  13941. If the value found is \"nil\", return nil to show that the property
  13942. should be considered as undefined (this is the meaning of nil here).
  13943. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  13944. (move-marker org-entry-property-inherited-from nil)
  13945. (org-with-wide-buffer
  13946. (let (value)
  13947. (catch 'exit
  13948. (while t
  13949. (let ((v (org--property-local-values property literal-nil)))
  13950. (when v
  13951. (setq value
  13952. (concat (mapconcat #'identity (delq nil v) " ")
  13953. (and value " ")
  13954. value)))
  13955. (cond
  13956. ((car v)
  13957. (org-back-to-heading t)
  13958. (move-marker org-entry-property-inherited-from (point))
  13959. (throw 'exit nil))
  13960. ((org-up-heading-safe))
  13961. (t
  13962. (let ((global (org--property-global-value property literal-nil)))
  13963. (cond ((not global))
  13964. (value (setq value (concat global " " value)))
  13965. (t (setq value global))))
  13966. (throw 'exit nil))))))
  13967. (if literal-nil value (org-not-nil value)))))
  13968. (defvar org-property-changed-functions nil
  13969. "Hook called when the value of a property has changed.
  13970. Each hook function should accept two arguments, the name of the property
  13971. and the new value.")
  13972. (defun org-entry-put (pom property value)
  13973. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  13974. If the value is nil, it is converted to the empty string. If it
  13975. is not a string, an error is raised. Also raise an error on
  13976. invalid property names.
  13977. PROPERTY can be any regular property (see
  13978. `org-special-properties'). It can also be \"TODO\",
  13979. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  13980. For the last two properties, VALUE may have any of the special
  13981. values \"earlier\" and \"later\". The function then increases or
  13982. decreases scheduled or deadline date by one day."
  13983. (cond ((null value) (setq value ""))
  13984. ((not (stringp value)) (error "Properties values should be strings"))
  13985. ((not (org--valid-property-p property))
  13986. (user-error "Invalid property name: \"%s\"" property)))
  13987. (org-with-point-at pom
  13988. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  13989. (org-back-to-heading t)
  13990. (org-with-limited-levels (org-back-to-heading t)))
  13991. (let ((beg (point)))
  13992. (cond
  13993. ((equal property "TODO")
  13994. (cond ((not (org-string-nw-p value)) (setq value 'none))
  13995. ((not (member value org-todo-keywords-1))
  13996. (user-error "\"%s\" is not a valid TODO state" value)))
  13997. (org-todo value)
  13998. (org-set-tags nil 'align))
  13999. ((equal property "PRIORITY")
  14000. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14001. (org-set-tags nil 'align))
  14002. ((equal property "SCHEDULED")
  14003. (forward-line)
  14004. (if (and (looking-at-p org-planning-line-re)
  14005. (re-search-forward
  14006. org-scheduled-time-regexp (line-end-position) t))
  14007. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14008. ((string= value "later") (org-timestamp-change 1 'day))
  14009. ((string= value "") (org-schedule '(4)))
  14010. (t (org-schedule nil value)))
  14011. (if (member value '("earlier" "later" ""))
  14012. (call-interactively #'org-schedule)
  14013. (org-schedule nil value))))
  14014. ((equal property "DEADLINE")
  14015. (forward-line)
  14016. (if (and (looking-at-p org-planning-line-re)
  14017. (re-search-forward
  14018. org-deadline-time-regexp (line-end-position) t))
  14019. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14020. ((string= value "later") (org-timestamp-change 1 'day))
  14021. ((string= value "") (org-deadline '(4)))
  14022. (t (org-deadline nil value)))
  14023. (if (member value '("earlier" "later" ""))
  14024. (call-interactively #'org-deadline)
  14025. (org-deadline nil value))))
  14026. ((member property org-special-properties)
  14027. (error "The %s property cannot be set with `org-entry-put'" property))
  14028. (t
  14029. (let* ((range (org-get-property-block beg 'force))
  14030. (end (cdr range))
  14031. (case-fold-search t))
  14032. (goto-char (car range))
  14033. (if (re-search-forward (org-re-property property nil t) end t)
  14034. (progn (delete-region (match-beginning 0) (match-end 0))
  14035. (goto-char (match-beginning 0)))
  14036. (goto-char end)
  14037. (insert "\n")
  14038. (backward-char))
  14039. (insert ":" property ":")
  14040. (when value (insert " " value))
  14041. (org-indent-line)))))
  14042. (run-hook-with-args 'org-property-changed-functions property value)))
  14043. (defun org-buffer-property-keys (&optional specials defaults columns)
  14044. "Get all property keys in the current buffer.
  14045. When SPECIALS is non-nil, also list the special properties that
  14046. reflect things like tags and TODO state.
  14047. When DEFAULTS is non-nil, also include properties that has
  14048. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14049. DESCRIPTION, LOCATION, and LOGGING and others.
  14050. When COLUMNS in non-nil, also include property names given in
  14051. COLUMN formats in the current buffer."
  14052. (let ((case-fold-search t)
  14053. (props (append
  14054. (and specials org-special-properties)
  14055. (and defaults (cons org-effort-property org-default-properties))
  14056. nil)))
  14057. (org-with-wide-buffer
  14058. (goto-char (point-min))
  14059. (while (re-search-forward org-property-start-re nil t)
  14060. (catch :skip
  14061. (let ((range (org-get-property-block)))
  14062. (unless range (throw :skip nil))
  14063. (goto-char (car range))
  14064. (let ((begin (car range))
  14065. (end (cdr range)))
  14066. ;; Make sure that found property block is not located
  14067. ;; before current point, as it would generate an infloop.
  14068. ;; It can happen, for example, in the following
  14069. ;; situation:
  14070. ;;
  14071. ;; * Headline
  14072. ;; :PROPERTIES:
  14073. ;; ...
  14074. ;; :END:
  14075. ;; *************** Inlinetask
  14076. ;; #+BEGIN_EXAMPLE
  14077. ;; :PROPERTIES:
  14078. ;; #+END_EXAMPLE
  14079. ;;
  14080. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  14081. (while (< (point) end)
  14082. (let ((p (progn (looking-at org-property-re)
  14083. (match-string-no-properties 2))))
  14084. ;; Only add true property name, not extension symbol.
  14085. (push (if (not (string-match-p "\\+\\'" p)) p
  14086. (substring p 0 -1))
  14087. props))
  14088. (forward-line))))
  14089. (outline-next-heading)))
  14090. (when columns
  14091. (goto-char (point-min))
  14092. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14093. (let ((element (org-element-at-point)))
  14094. (when (memq (org-element-type element) '(keyword node-property))
  14095. (let ((value (org-element-property :value element))
  14096. (start 0))
  14097. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  14098. \\(?:{[^}]+}\\)?"
  14099. value start)
  14100. (setq start (match-end 0))
  14101. (let ((p (match-string-no-properties 1 value)))
  14102. (unless (member-ignore-case p org-special-properties)
  14103. (push p props))))))))))
  14104. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14105. (defun org-property-values (key)
  14106. "List all non-nil values of property KEY in current buffer."
  14107. (org-with-wide-buffer
  14108. (goto-char (point-min))
  14109. (let ((case-fold-search t)
  14110. (re (org-re-property key))
  14111. values)
  14112. (while (re-search-forward re nil t)
  14113. (push (org-entry-get (point) key) values))
  14114. (delete-dups values))))
  14115. (defun org-insert-property-drawer ()
  14116. "Insert a property drawer into the current entry."
  14117. (org-with-wide-buffer
  14118. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14119. (org-back-to-heading t)
  14120. (org-with-limited-levels (org-back-to-heading t)))
  14121. (forward-line)
  14122. (when (looking-at-p org-planning-line-re) (forward-line))
  14123. (unless (looking-at-p org-property-drawer-re)
  14124. ;; Make sure we start editing a line from current entry, not from
  14125. ;; next one. It prevents extending text properties or overlays
  14126. ;; belonging to the latter.
  14127. (when (bolp) (backward-char))
  14128. (let ((begin (1+ (point)))
  14129. (inhibit-read-only t))
  14130. (insert "\n:PROPERTIES:\n:END:")
  14131. (when (eobp) (insert "\n"))
  14132. (org-indent-region begin (point))))))
  14133. (defun org-insert-drawer (&optional arg drawer)
  14134. "Insert a drawer at point.
  14135. When optional argument ARG is non-nil, insert a property drawer.
  14136. Optional argument DRAWER, when non-nil, is a string representing
  14137. drawer's name. Otherwise, the user is prompted for a name.
  14138. If a region is active, insert the drawer around that region
  14139. instead.
  14140. Point is left between drawer's boundaries."
  14141. (interactive "P")
  14142. (let* ((drawer (if arg "PROPERTIES"
  14143. (or drawer (read-from-minibuffer "Drawer: ")))))
  14144. (cond
  14145. ;; With C-u, fall back on `org-insert-property-drawer'
  14146. (arg (org-insert-property-drawer))
  14147. ;; Check validity of suggested drawer's name.
  14148. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14149. (user-error "Invalid drawer name"))
  14150. ;; With an active region, insert a drawer at point.
  14151. ((not (org-region-active-p))
  14152. (progn
  14153. (unless (bolp) (insert "\n"))
  14154. (insert (format ":%s:\n\n:END:\n" drawer))
  14155. (forward-line -2)))
  14156. ;; Otherwise, insert the drawer at point
  14157. (t
  14158. (let ((rbeg (region-beginning))
  14159. (rend (copy-marker (region-end))))
  14160. (unwind-protect
  14161. (progn
  14162. (goto-char rbeg)
  14163. (beginning-of-line)
  14164. (when (save-excursion
  14165. (re-search-forward org-outline-regexp-bol rend t))
  14166. (user-error "Drawers cannot contain headlines"))
  14167. ;; Position point at the beginning of the first
  14168. ;; non-blank line in region. Insert drawer's opening
  14169. ;; there, then indent it.
  14170. (org-skip-whitespace)
  14171. (beginning-of-line)
  14172. (insert ":" drawer ":\n")
  14173. (forward-line -1)
  14174. (indent-for-tab-command)
  14175. ;; Move point to the beginning of the first blank line
  14176. ;; after the last non-blank line in region. Insert
  14177. ;; drawer's closing, then indent it.
  14178. (goto-char rend)
  14179. (skip-chars-backward " \r\t\n")
  14180. (insert "\n:END:")
  14181. (deactivate-mark t)
  14182. (indent-for-tab-command)
  14183. (unless (eolp) (insert "\n")))
  14184. ;; Clear marker, whatever the outcome of insertion is.
  14185. (set-marker rend nil)))))))
  14186. (defvar org-property-set-functions-alist nil
  14187. "Property set function alist.
  14188. Each entry should have the following format:
  14189. (PROPERTY . READ-FUNCTION)
  14190. The read function will be called with the same argument as
  14191. `org-completing-read'.")
  14192. (defun org-set-property-function (property)
  14193. "Get the function that should be used to set PROPERTY.
  14194. This is computed according to `org-property-set-functions-alist'."
  14195. (or (cdr (assoc property org-property-set-functions-alist))
  14196. 'org-completing-read))
  14197. (defun org-read-property-value (property)
  14198. "Read PROPERTY value from user."
  14199. (let* ((completion-ignore-case t)
  14200. (allowed (org-property-get-allowed-values nil property 'table))
  14201. (cur (org-entry-get nil property))
  14202. (prompt (concat property " value"
  14203. (if (and cur (string-match "\\S-" cur))
  14204. (concat " [" cur "]") "") ": "))
  14205. (set-function (org-set-property-function property))
  14206. (val (if allowed
  14207. (funcall set-function prompt allowed nil
  14208. (not (get-text-property 0 'org-unrestricted
  14209. (caar allowed))))
  14210. (funcall set-function prompt
  14211. (mapcar 'list (org-property-values property))
  14212. nil nil "" nil cur))))
  14213. (org-trim val)))
  14214. (defvar org-last-set-property nil)
  14215. (defvar org-last-set-property-value nil)
  14216. (defun org-read-property-name ()
  14217. "Read a property name."
  14218. (let ((completion-ignore-case t)
  14219. (default-prop (or (and (org-at-property-p)
  14220. (match-string-no-properties 2))
  14221. org-last-set-property)))
  14222. (org-completing-read
  14223. (concat "Property"
  14224. (if default-prop (concat " [" default-prop "]") "")
  14225. ": ")
  14226. (mapcar #'list (org-buffer-property-keys nil t t))
  14227. nil nil nil nil default-prop)))
  14228. (defun org-set-property-and-value (use-last)
  14229. "Allow to set [PROPERTY]: [value] direction from prompt.
  14230. When use-default, don't even ask, just use the last
  14231. \"[PROPERTY]: [value]\" string from the history."
  14232. (interactive "P")
  14233. (let* ((completion-ignore-case t)
  14234. (pv (or (and use-last org-last-set-property-value)
  14235. (org-completing-read
  14236. "Enter a \"[Property]: [value]\" pair: "
  14237. nil nil nil nil nil
  14238. org-last-set-property-value)))
  14239. prop val)
  14240. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14241. (setq prop (match-string 1 pv)
  14242. val (match-string 2 pv))
  14243. (org-set-property prop val))))
  14244. (defun org-set-property (property value)
  14245. "In the current entry, set PROPERTY to VALUE.
  14246. When called interactively, this will prompt for a property name, offering
  14247. completion on existing and default properties. And then it will prompt
  14248. for a value, offering completion either on allowed values (via an inherited
  14249. xxx_ALL property) or on existing values in other instances of this property
  14250. in the current file.
  14251. Throw an error when trying to set a property with an invalid name."
  14252. (interactive (list nil nil))
  14253. (let ((property (or property (org-read-property-name))))
  14254. ;; `org-entry-put' also makes the following check, but this one
  14255. ;; avoids polluting `org-last-set-property' and
  14256. ;; `org-last-set-property-value' needlessly.
  14257. (unless (org--valid-property-p property)
  14258. (user-error "Invalid property name: \"%s\"" property))
  14259. (let ((value (or value (org-read-property-value property)))
  14260. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14261. (setq org-last-set-property property)
  14262. (setq org-last-set-property-value (concat property ": " value))
  14263. ;; Possibly postprocess the inserted value:
  14264. (when fn (setq value (funcall fn value)))
  14265. (unless (equal (org-entry-get nil property) value)
  14266. (org-entry-put nil property value)))))
  14267. (defun org-find-property (property &optional value)
  14268. "Find first entry in buffer that sets PROPERTY.
  14269. When optional argument VALUE is non-nil, only consider an entry
  14270. if it contains PROPERTY set to this value. If PROPERTY should be
  14271. explicitly set to nil, use string \"nil\" for VALUE.
  14272. Return position where the entry begins, or nil if there is no
  14273. such entry. If narrowing is in effect, only search the visible
  14274. part of the buffer."
  14275. (save-excursion
  14276. (goto-char (point-min))
  14277. (let ((case-fold-search t)
  14278. (re (org-re-property property nil (not value) value)))
  14279. (catch 'exit
  14280. (while (re-search-forward re nil t)
  14281. (when (if value (org-at-property-p)
  14282. (org-entry-get (point) property nil t))
  14283. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14284. (defun org-delete-property (property)
  14285. "In the current entry, delete PROPERTY."
  14286. (interactive
  14287. (let* ((completion-ignore-case t)
  14288. (cat (org-entry-get (point) "CATEGORY"))
  14289. (props0 (org-entry-properties nil 'standard))
  14290. (props (if cat props0
  14291. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14292. (prop (if (< 1 (length props))
  14293. (completing-read "Property: " props nil t)
  14294. (caar props))))
  14295. (list prop)))
  14296. (if (not property)
  14297. (message "No property to delete in this entry")
  14298. (org-entry-delete nil property)
  14299. (message "Property \"%s\" deleted" property)))
  14300. (defun org-delete-property-globally (property)
  14301. "Remove PROPERTY globally, from all entries.
  14302. This function ignores narrowing, if any."
  14303. (interactive
  14304. (let* ((completion-ignore-case t)
  14305. (prop (completing-read
  14306. "Globally remove property: "
  14307. (mapcar #'list (org-buffer-property-keys)))))
  14308. (list prop)))
  14309. (org-with-wide-buffer
  14310. (goto-char (point-min))
  14311. (let ((count 0)
  14312. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14313. (while (re-search-forward re nil t)
  14314. (when (org-entry-delete (point) property) (cl-incf count)))
  14315. (message "Property \"%s\" removed from %d entries" property count))))
  14316. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14317. (defun org-compute-property-at-point ()
  14318. "Compute the property at point.
  14319. This looks for an enclosing column format, extracts the operator and
  14320. then applies it to the property in the column format's scope."
  14321. (interactive)
  14322. (unless (org-at-property-p)
  14323. (user-error "Not at a property"))
  14324. (let ((prop (match-string-no-properties 2)))
  14325. (org-columns-get-format-and-top-level)
  14326. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14327. (user-error "No operator defined for property %s" prop))
  14328. (org-columns-compute prop)))
  14329. (defvar org-property-allowed-value-functions nil
  14330. "Hook for functions supplying allowed values for a specific property.
  14331. The functions must take a single argument, the name of the property, and
  14332. return a flat list of allowed values. If \":ETC\" is one of
  14333. the values, this means that these values are intended as defaults for
  14334. completion, but that other values should be allowed too.
  14335. The functions must return nil if they are not responsible for this
  14336. property.")
  14337. (defun org-property-get-allowed-values (pom property &optional table)
  14338. "Get allowed values for the property PROPERTY.
  14339. When TABLE is non-nil, return an alist that can directly be used for
  14340. completion."
  14341. (let (vals)
  14342. (cond
  14343. ((equal property "TODO")
  14344. (setq vals (org-with-point-at pom
  14345. (append org-todo-keywords-1 '("")))))
  14346. ((equal property "PRIORITY")
  14347. (let ((n org-lowest-priority))
  14348. (while (>= n org-highest-priority)
  14349. (push (char-to-string n) vals)
  14350. (setq n (1- n)))))
  14351. ((equal property "CATEGORY"))
  14352. ((member property org-special-properties))
  14353. ((setq vals (run-hook-with-args-until-success
  14354. 'org-property-allowed-value-functions property)))
  14355. (t
  14356. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14357. (when (and vals (string-match "\\S-" vals))
  14358. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14359. (setq vals (mapcar (lambda (x)
  14360. (cond ((stringp x) x)
  14361. ((numberp x) (number-to-string x))
  14362. ((symbolp x) (symbol-name x))
  14363. (t "???")))
  14364. vals)))))
  14365. (when (member ":ETC" vals)
  14366. (setq vals (remove ":ETC" vals))
  14367. (org-add-props (car vals) '(org-unrestricted t)))
  14368. (if table (mapcar 'list vals) vals)))
  14369. (defun org-property-previous-allowed-value (&optional _previous)
  14370. "Switch to the next allowed value for this property."
  14371. (interactive)
  14372. (org-property-next-allowed-value t))
  14373. (defun org-property-next-allowed-value (&optional previous)
  14374. "Switch to the next allowed value for this property."
  14375. (interactive)
  14376. (unless (org-at-property-p)
  14377. (user-error "Not at a property"))
  14378. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14379. (key (match-string 2))
  14380. (value (match-string 3))
  14381. (allowed (or (org-property-get-allowed-values (point) key)
  14382. (and (member value '("[ ]" "[-]" "[X]"))
  14383. '("[ ]" "[X]"))))
  14384. (heading (save-match-data (nth 4 (org-heading-components))))
  14385. nval)
  14386. (unless allowed
  14387. (user-error "Allowed values for this property have not been defined"))
  14388. (when previous (setq allowed (reverse allowed)))
  14389. (when (member value allowed)
  14390. (setq nval (car (cdr (member value allowed)))))
  14391. (setq nval (or nval (car allowed)))
  14392. (when (equal nval value)
  14393. (user-error "Only one allowed value for this property"))
  14394. (org-at-property-p)
  14395. (replace-match (concat " :" key ": " nval) t t)
  14396. (org-indent-line)
  14397. (beginning-of-line 1)
  14398. (skip-chars-forward " \t")
  14399. (when (equal prop org-effort-property)
  14400. (org-refresh-property
  14401. '((effort . identity)
  14402. (effort-minutes . org-duration-to-minutes))
  14403. nval)
  14404. (when (string= org-clock-current-task heading)
  14405. (setq org-clock-effort nval)
  14406. (org-clock-update-mode-line)))
  14407. (run-hook-with-args 'org-property-changed-functions key nval)))
  14408. (defun org-find-olp (path &optional this-buffer)
  14409. "Return a marker pointing to the entry at outline path OLP.
  14410. If anything goes wrong, throw an error.
  14411. You can wrap this call to catch the error like this:
  14412. (condition-case msg
  14413. (org-mobile-locate-entry (match-string 4))
  14414. (error (nth 1 msg)))
  14415. The return value will then be either a string with the error message,
  14416. or a marker if everything is OK.
  14417. If THIS-BUFFER is set, the outline path does not contain a file,
  14418. only headings."
  14419. (let* ((file (if this-buffer buffer-file-name (pop path)))
  14420. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  14421. (level 1)
  14422. (lmin 1)
  14423. (lmax 1)
  14424. end found flevel)
  14425. (unless buffer (error "File not found :%s" file))
  14426. (with-current-buffer buffer
  14427. (unless (derived-mode-p 'org-mode)
  14428. (error "Buffer %s needs to be in Org mode" buffer))
  14429. (org-with-wide-buffer
  14430. (goto-char (point-min))
  14431. (dolist (heading path)
  14432. (let ((re (format org-complex-heading-regexp-format
  14433. (regexp-quote heading)))
  14434. (cnt 0))
  14435. (while (re-search-forward re end t)
  14436. (setq level (- (match-end 1) (match-beginning 1)))
  14437. (when (and (>= level lmin) (<= level lmax))
  14438. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  14439. (when (= cnt 0)
  14440. (error "Heading not found on level %d: %s" lmax heading))
  14441. (when (> cnt 1)
  14442. (error "Heading not unique on level %d: %s" lmax heading))
  14443. (goto-char found)
  14444. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  14445. (setq end (save-excursion (org-end-of-subtree t t)))))
  14446. (when (org-at-heading-p)
  14447. (point-marker))))))
  14448. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  14449. "Find node HEADING in BUFFER.
  14450. Return a marker to the heading if it was found, or nil if not.
  14451. If POS-ONLY is set, return just the position instead of a marker.
  14452. The heading text must match exact, but it may have a TODO keyword,
  14453. a priority cookie and tags in the standard locations."
  14454. (with-current-buffer (or buffer (current-buffer))
  14455. (org-with-wide-buffer
  14456. (goto-char (point-min))
  14457. (let (case-fold-search)
  14458. (when (re-search-forward
  14459. (format org-complex-heading-regexp-format
  14460. (regexp-quote heading)) nil t)
  14461. (if pos-only
  14462. (match-beginning 0)
  14463. (move-marker (make-marker) (match-beginning 0))))))))
  14464. (defun org-find-exact-heading-in-directory (heading &optional dir)
  14465. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  14466. When the target headline is found, return a marker to this location."
  14467. (let ((files (directory-files (or dir default-directory)
  14468. t "\\`[^.#].*\\.org\\'"))
  14469. visiting m buffer)
  14470. (catch 'found
  14471. (dolist (file files)
  14472. (message "trying %s" file)
  14473. (setq visiting (org-find-base-buffer-visiting file))
  14474. (setq buffer (or visiting (find-file-noselect file)))
  14475. (setq m (org-find-exact-headline-in-buffer
  14476. heading buffer))
  14477. (when (and (not m) (not visiting)) (kill-buffer buffer))
  14478. (and m (throw 'found m))))))
  14479. (defun org-find-entry-with-id (ident)
  14480. "Locate the entry that contains the ID property with exact value IDENT.
  14481. IDENT can be a string, a symbol or a number, this function will search for
  14482. the string representation of it.
  14483. Return the position where this entry starts, or nil if there is no such entry."
  14484. (interactive "sID: ")
  14485. (let ((id (cond
  14486. ((stringp ident) ident)
  14487. ((symbolp ident) (symbol-name ident))
  14488. ((numberp ident) (number-to-string ident))
  14489. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  14490. (org-with-wide-buffer (org-find-property "ID" id))))
  14491. ;;;; Timestamps
  14492. (defvar org-last-changed-timestamp nil)
  14493. (defvar org-last-inserted-timestamp nil
  14494. "The last time stamp inserted with `org-insert-time-stamp'.")
  14495. (defun org-time-stamp (arg &optional inactive)
  14496. "Prompt for a date/time and insert a time stamp.
  14497. If the user specifies a time like HH:MM or if this command is
  14498. called with at least one prefix argument, the time stamp contains
  14499. the date and the time. Otherwise, only the date is included.
  14500. All parts of a date not specified by the user are filled in from
  14501. the timestamp at point, if any, or the current date/time
  14502. otherwise.
  14503. If there is already a timestamp at the cursor, it is replaced.
  14504. With two universal prefix arguments, insert an active timestamp
  14505. with the current time without prompting the user.
  14506. When called from lisp, the timestamp is inactive if INACTIVE is
  14507. non-nil."
  14508. (interactive "P")
  14509. (let* ((ts (cond
  14510. ((org-at-date-range-p t)
  14511. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  14512. ((org-at-timestamp-p 'lax) (match-string 0))))
  14513. ;; Default time is either the timestamp at point or today.
  14514. ;; When entering a range, only the range start is considered.
  14515. (default-time (if (not ts) (current-time)
  14516. (apply #'encode-time (org-parse-time-string ts))))
  14517. (default-input (and ts (org-get-compact-tod ts)))
  14518. (repeater (and ts
  14519. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  14520. (match-string 0 ts)))
  14521. org-time-was-given
  14522. org-end-time-was-given
  14523. (time
  14524. (and (if (equal arg '(16)) (current-time)
  14525. ;; Preserve `this-command' and `last-command'.
  14526. (let ((this-command this-command)
  14527. (last-command last-command))
  14528. (org-read-date
  14529. arg 'totime nil nil default-time default-input
  14530. inactive))))))
  14531. (cond
  14532. ((and ts
  14533. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  14534. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  14535. (insert "--")
  14536. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  14537. (ts
  14538. ;; Make sure we're on a timestamp. When in the middle of a date
  14539. ;; range, move arbitrarily to range end.
  14540. (unless (org-at-timestamp-p 'lax)
  14541. (skip-chars-forward "-")
  14542. (org-at-timestamp-p 'lax))
  14543. (replace-match "")
  14544. (setq org-last-changed-timestamp
  14545. (org-insert-time-stamp
  14546. time (or org-time-was-given arg)
  14547. inactive nil nil (list org-end-time-was-given)))
  14548. (when repeater
  14549. (backward-char)
  14550. (insert " " repeater)
  14551. (setq org-last-changed-timestamp
  14552. (concat (substring org-last-inserted-timestamp 0 -1)
  14553. " " repeater ">")))
  14554. (message "Timestamp updated"))
  14555. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  14556. (t (org-insert-time-stamp
  14557. time (or org-time-was-given arg) inactive nil nil
  14558. (list org-end-time-was-given))))))
  14559. ;; FIXME: can we use this for something else, like computing time differences?
  14560. (defun org-get-compact-tod (s)
  14561. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  14562. (let* ((t1 (match-string 1 s))
  14563. (h1 (string-to-number (match-string 2 s)))
  14564. (m1 (string-to-number (match-string 3 s)))
  14565. (t2 (and (match-end 4) (match-string 5 s)))
  14566. (h2 (and t2 (string-to-number (match-string 6 s))))
  14567. (m2 (and t2 (string-to-number (match-string 7 s))))
  14568. dh dm)
  14569. (if (not t2)
  14570. t1
  14571. (setq dh (- h2 h1) dm (- m2 m1))
  14572. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  14573. (concat t1 "+" (number-to-string dh)
  14574. (and (/= 0 dm) (format ":%02d" dm)))))))
  14575. (defun org-time-stamp-inactive (&optional arg)
  14576. "Insert an inactive time stamp.
  14577. An inactive time stamp is enclosed in square brackets instead of angle
  14578. brackets. It is inactive in the sense that it does not trigger agenda entries,
  14579. does not link to the calendar and cannot be changed with the S-cursor keys.
  14580. So these are more for recording a certain time/date.
  14581. If the user specifies a time like HH:MM or if this command is called with
  14582. at least one prefix argument, the time stamp contains the date and the time.
  14583. Otherwise, only the date is included.
  14584. When called with two universal prefix arguments, insert an active time stamp
  14585. with the current time without prompting the user."
  14586. (interactive "P")
  14587. (org-time-stamp arg 'inactive))
  14588. (defvar org-date-ovl (make-overlay 1 1))
  14589. (overlay-put org-date-ovl 'face 'org-date-selected)
  14590. (delete-overlay org-date-ovl)
  14591. (defvar org-ans1) ; dynamically scoped parameter
  14592. (defvar org-ans2) ; dynamically scoped parameter
  14593. (defvar org-plain-time-of-day-regexp) ; defined below
  14594. (defvar org-overriding-default-time nil) ; dynamically scoped
  14595. (defvar org-read-date-overlay nil)
  14596. (defvar org-dcst nil) ; dynamically scoped
  14597. (defvar org-read-date-history nil)
  14598. (defvar org-read-date-final-answer nil)
  14599. (defvar org-read-date-analyze-futurep nil)
  14600. (defvar org-read-date-analyze-forced-year nil)
  14601. (defvar org-read-date-inactive)
  14602. (defvar org-read-date-minibuffer-local-map
  14603. (let* ((map (make-sparse-keymap)))
  14604. (set-keymap-parent map minibuffer-local-map)
  14605. (org-defkey map (kbd ".")
  14606. (lambda () (interactive)
  14607. ;; Are we at the beginning of the prompt?
  14608. (if (looking-back "^[^:]+: "
  14609. (let ((inhibit-field-text-motion t))
  14610. (line-beginning-position)))
  14611. (org-eval-in-calendar '(calendar-goto-today))
  14612. (insert "."))))
  14613. (org-defkey map (kbd "C-.")
  14614. (lambda () (interactive)
  14615. (org-eval-in-calendar '(calendar-goto-today))))
  14616. (org-defkey map (kbd "M-S-<left>")
  14617. (lambda () (interactive)
  14618. (org-eval-in-calendar '(calendar-backward-month 1))))
  14619. (org-defkey map (kbd "ESC S-<left>")
  14620. (lambda () (interactive)
  14621. (org-eval-in-calendar '(calendar-backward-month 1))))
  14622. (org-defkey map (kbd "M-S-<right>")
  14623. (lambda () (interactive)
  14624. (org-eval-in-calendar '(calendar-forward-month 1))))
  14625. (org-defkey map (kbd "ESC S-<right>")
  14626. (lambda () (interactive)
  14627. (org-eval-in-calendar '(calendar-forward-month 1))))
  14628. (org-defkey map (kbd "M-S-<up>")
  14629. (lambda () (interactive)
  14630. (org-eval-in-calendar '(calendar-backward-year 1))))
  14631. (org-defkey map (kbd "ESC S-<up>")
  14632. (lambda () (interactive)
  14633. (org-eval-in-calendar '(calendar-backward-year 1))))
  14634. (org-defkey map (kbd "M-S-<down>")
  14635. (lambda () (interactive)
  14636. (org-eval-in-calendar '(calendar-forward-year 1))))
  14637. (org-defkey map (kbd "ESC S-<down>")
  14638. (lambda () (interactive)
  14639. (org-eval-in-calendar '(calendar-forward-year 1))))
  14640. (org-defkey map (kbd "S-<up>")
  14641. (lambda () (interactive)
  14642. (org-eval-in-calendar '(calendar-backward-week 1))))
  14643. (org-defkey map (kbd "S-<down>")
  14644. (lambda () (interactive)
  14645. (org-eval-in-calendar '(calendar-forward-week 1))))
  14646. (org-defkey map (kbd "S-<left>")
  14647. (lambda () (interactive)
  14648. (org-eval-in-calendar '(calendar-backward-day 1))))
  14649. (org-defkey map (kbd "S-<right>")
  14650. (lambda () (interactive)
  14651. (org-eval-in-calendar '(calendar-forward-day 1))))
  14652. (org-defkey map (kbd "!")
  14653. (lambda () (interactive)
  14654. (org-eval-in-calendar '(diary-view-entries))
  14655. (message "")))
  14656. (org-defkey map (kbd ">")
  14657. (lambda () (interactive)
  14658. (org-eval-in-calendar '(calendar-scroll-left 1))))
  14659. (org-defkey map (kbd "<")
  14660. (lambda () (interactive)
  14661. (org-eval-in-calendar '(calendar-scroll-right 1))))
  14662. (org-defkey map (kbd "C-v")
  14663. (lambda () (interactive)
  14664. (org-eval-in-calendar
  14665. '(calendar-scroll-left-three-months 1))))
  14666. (org-defkey map (kbd "M-v")
  14667. (lambda () (interactive)
  14668. (org-eval-in-calendar
  14669. '(calendar-scroll-right-three-months 1))))
  14670. map)
  14671. "Keymap for minibuffer commands when using `org-read-date'.")
  14672. (defvar org-def)
  14673. (defvar org-defdecode)
  14674. (defvar org-with-time)
  14675. (defvar calendar-setup) ; Dynamically scoped.
  14676. (defun org-read-date (&optional with-time to-time from-string prompt
  14677. default-time default-input inactive)
  14678. "Read a date, possibly a time, and make things smooth for the user.
  14679. The prompt will suggest to enter an ISO date, but you can also enter anything
  14680. which will at least partially be understood by `parse-time-string'.
  14681. Unrecognized parts of the date will default to the current day, month, year,
  14682. hour and minute. If this command is called to replace a timestamp at point,
  14683. or to enter the second timestamp of a range, the default time is taken
  14684. from the existing stamp. Furthermore, the command prefers the future,
  14685. so if you are giving a date where the year is not given, and the day-month
  14686. combination is already past in the current year, it will assume you
  14687. mean next year. For details, see the manual. A few examples:
  14688. 3-2-5 --> 2003-02-05
  14689. feb 15 --> currentyear-02-15
  14690. 2/15 --> currentyear-02-15
  14691. sep 12 9 --> 2009-09-12
  14692. 12:45 --> today 12:45
  14693. 22 sept 0:34 --> currentyear-09-22 0:34
  14694. 12 --> currentyear-currentmonth-12
  14695. Fri --> nearest Friday after today
  14696. -Tue --> last Tuesday
  14697. etc.
  14698. Furthermore you can specify a relative date by giving, as the *first* thing
  14699. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  14700. change in days weeks, months, years.
  14701. With a single plus or minus, the date is relative to today. With a double
  14702. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  14703. +4d --> four days from today
  14704. +4 --> same as above
  14705. +2w --> two weeks from today
  14706. ++5 --> five days from default date
  14707. The function understands only English month and weekday abbreviations.
  14708. While prompting, a calendar is popped up - you can also select the
  14709. date with the mouse (button 1). The calendar shows a period of three
  14710. months. To scroll it to other months, use the keys `>' and `<'.
  14711. If you don't like the calendar, turn it off with
  14712. (setq org-read-date-popup-calendar nil)
  14713. With optional argument TO-TIME, the date will immediately be converted
  14714. to an internal time.
  14715. With an optional argument WITH-TIME, the prompt will suggest to
  14716. also insert a time. Note that when WITH-TIME is not set, you can
  14717. still enter a time, and this function will inform the calling routine
  14718. about this change. The calling routine may then choose to change the
  14719. format used to insert the time stamp into the buffer to include the time.
  14720. With optional argument FROM-STRING, read from this string instead from
  14721. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  14722. the time/date that is used for everything that is not specified by the
  14723. user."
  14724. (require 'parse-time)
  14725. (let* ((org-with-time with-time)
  14726. (org-time-stamp-rounding-minutes
  14727. (if (equal org-with-time '(16))
  14728. '(0 0)
  14729. org-time-stamp-rounding-minutes))
  14730. (org-dcst org-display-custom-times)
  14731. (ct (org-current-time))
  14732. (org-def (or org-overriding-default-time default-time ct))
  14733. (org-defdecode (decode-time org-def))
  14734. (cur-frame (selected-frame))
  14735. (mouse-autoselect-window nil) ; Don't let the mouse jump
  14736. (calendar-setup
  14737. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  14738. (calendar-move-hook nil)
  14739. (calendar-view-diary-initially-flag nil)
  14740. (calendar-view-holidays-initially-flag nil)
  14741. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  14742. ;; Rationalize `org-def' and `org-defdecode', if required.
  14743. (when (< (nth 2 org-defdecode) org-extend-today-until)
  14744. (setf (nth 2 org-defdecode) -1)
  14745. (setf (nth 1 org-defdecode) 59)
  14746. (setq org-def (apply #'encode-time org-defdecode))
  14747. (setq org-defdecode (decode-time org-def)))
  14748. (let* ((timestr (format-time-string
  14749. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  14750. org-def))
  14751. (prompt (concat (if prompt (concat prompt " ") "")
  14752. (format "Date+time [%s]: " timestr))))
  14753. (cond
  14754. (from-string (setq ans from-string))
  14755. (org-read-date-popup-calendar
  14756. (save-excursion
  14757. (save-window-excursion
  14758. (calendar)
  14759. (when (eq calendar-setup 'calendar-only)
  14760. (setq cal-frame
  14761. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  14762. (select-frame cal-frame))
  14763. (org-eval-in-calendar '(setq cursor-type nil) t)
  14764. (unwind-protect
  14765. (progn
  14766. (calendar-forward-day (- (time-to-days org-def)
  14767. (calendar-absolute-from-gregorian
  14768. (calendar-current-date))))
  14769. (org-eval-in-calendar nil t)
  14770. (let* ((old-map (current-local-map))
  14771. (map (copy-keymap calendar-mode-map))
  14772. (minibuffer-local-map
  14773. (copy-keymap org-read-date-minibuffer-local-map)))
  14774. (org-defkey map (kbd "RET") 'org-calendar-select)
  14775. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  14776. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  14777. (unwind-protect
  14778. (progn
  14779. (use-local-map map)
  14780. (setq org-read-date-inactive inactive)
  14781. (add-hook 'post-command-hook 'org-read-date-display)
  14782. (setq org-ans0
  14783. (read-string prompt
  14784. default-input
  14785. 'org-read-date-history
  14786. nil))
  14787. ;; org-ans0: from prompt
  14788. ;; org-ans1: from mouse click
  14789. ;; org-ans2: from calendar motion
  14790. (setq ans
  14791. (concat org-ans0 " " (or org-ans1 org-ans2))))
  14792. (remove-hook 'post-command-hook 'org-read-date-display)
  14793. (use-local-map old-map)
  14794. (when org-read-date-overlay
  14795. (delete-overlay org-read-date-overlay)
  14796. (setq org-read-date-overlay nil)))))
  14797. (bury-buffer "*Calendar*")
  14798. (when cal-frame
  14799. (delete-frame cal-frame)
  14800. (select-frame-set-input-focus cur-frame))))))
  14801. (t ; Naked prompt only
  14802. (unwind-protect
  14803. (setq ans (read-string prompt default-input
  14804. 'org-read-date-history timestr))
  14805. (when org-read-date-overlay
  14806. (delete-overlay org-read-date-overlay)
  14807. (setq org-read-date-overlay nil))))))
  14808. (setq final (org-read-date-analyze ans org-def org-defdecode))
  14809. (when org-read-date-analyze-forced-year
  14810. (message "Year was forced into %s"
  14811. (if org-read-date-force-compatible-dates
  14812. "compatible range (1970-2037)"
  14813. "range representable on this machine"))
  14814. (ding))
  14815. ;; One round trip to get rid of 34th of August and stuff like that....
  14816. (setq final (decode-time (apply 'encode-time final)))
  14817. (setq org-read-date-final-answer ans)
  14818. (if to-time
  14819. (apply 'encode-time final)
  14820. (if (and (boundp 'org-time-was-given) org-time-was-given)
  14821. (format "%04d-%02d-%02d %02d:%02d"
  14822. (nth 5 final) (nth 4 final) (nth 3 final)
  14823. (nth 2 final) (nth 1 final))
  14824. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  14825. (defun org-read-date-display ()
  14826. "Display the current date prompt interpretation in the minibuffer."
  14827. (when org-read-date-display-live
  14828. (when org-read-date-overlay
  14829. (delete-overlay org-read-date-overlay))
  14830. (when (minibufferp (current-buffer))
  14831. (save-excursion
  14832. (end-of-line 1)
  14833. (while (not (equal (buffer-substring
  14834. (max (point-min) (- (point) 4)) (point))
  14835. " "))
  14836. (insert " ")))
  14837. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  14838. " " (or org-ans1 org-ans2)))
  14839. (org-end-time-was-given nil)
  14840. (f (org-read-date-analyze ans org-def org-defdecode))
  14841. (fmts (if org-dcst
  14842. org-time-stamp-custom-formats
  14843. org-time-stamp-formats))
  14844. (fmt (if (or org-with-time
  14845. (and (boundp 'org-time-was-given) org-time-was-given))
  14846. (cdr fmts)
  14847. (car fmts)))
  14848. (txt (format-time-string fmt (apply 'encode-time f)))
  14849. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  14850. (txt (concat "=> " txt)))
  14851. (when (and org-end-time-was-given
  14852. (string-match org-plain-time-of-day-regexp txt))
  14853. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  14854. org-end-time-was-given
  14855. (substring txt (match-end 0)))))
  14856. (when org-read-date-analyze-futurep
  14857. (setq txt (concat txt " (=>F)")))
  14858. (setq org-read-date-overlay
  14859. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  14860. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  14861. (defun org-read-date-analyze (ans def defdecode)
  14862. "Analyze the combined answer of the date prompt."
  14863. ;; FIXME: cleanup and comment
  14864. ;; Pass `current-time' result to `decode-time' (instead of calling
  14865. ;; without arguments) so that only `current-time' has to be
  14866. ;; overridden in tests.
  14867. (let ((org-def def)
  14868. (org-defdecode defdecode)
  14869. (nowdecode (decode-time (current-time)))
  14870. delta deltan deltaw deltadef year month day
  14871. hour minute second wday pm h2 m2 tl wday1
  14872. iso-year iso-weekday iso-week iso-date futurep kill-year)
  14873. (setq org-read-date-analyze-futurep nil
  14874. org-read-date-analyze-forced-year nil)
  14875. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  14876. (setq ans "+0"))
  14877. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  14878. (setq ans (replace-match "" t t ans)
  14879. deltan (car delta)
  14880. deltaw (nth 1 delta)
  14881. deltadef (nth 2 delta)))
  14882. ;; Check if there is an iso week date in there. If yes, store the
  14883. ;; info and postpone interpreting it until the rest of the parsing
  14884. ;; is done.
  14885. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  14886. (setq iso-year (when (match-end 1)
  14887. (org-small-year-to-year
  14888. (string-to-number (match-string 1 ans))))
  14889. iso-weekday (when (match-end 3)
  14890. (string-to-number (match-string 3 ans)))
  14891. iso-week (string-to-number (match-string 2 ans)))
  14892. (setq ans (replace-match "" t t ans)))
  14893. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  14894. (when (string-match
  14895. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  14896. (setq year (if (match-end 2)
  14897. (string-to-number (match-string 2 ans))
  14898. (progn (setq kill-year t)
  14899. (string-to-number (format-time-string "%Y"))))
  14900. month (string-to-number (match-string 3 ans))
  14901. day (string-to-number (match-string 4 ans)))
  14902. (setq year (org-small-year-to-year year))
  14903. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14904. t nil ans)))
  14905. ;; Help matching dotted european dates
  14906. (when (string-match
  14907. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  14908. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  14909. (setq kill-year t)
  14910. (string-to-number (format-time-string "%Y")))
  14911. day (string-to-number (match-string 1 ans))
  14912. month (string-to-number (match-string 2 ans))
  14913. ans (replace-match (format "%04d-%02d-%02d" year month day)
  14914. t nil ans)))
  14915. ;; Help matching american dates, like 5/30 or 5/30/7
  14916. (when (string-match
  14917. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  14918. (setq year (if (match-end 4)
  14919. (string-to-number (match-string 4 ans))
  14920. (progn (setq kill-year t)
  14921. (string-to-number (format-time-string "%Y"))))
  14922. month (string-to-number (match-string 1 ans))
  14923. day (string-to-number (match-string 2 ans)))
  14924. (setq year (org-small-year-to-year year))
  14925. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  14926. t nil ans)))
  14927. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  14928. ;; If there is a time with am/pm, and *no* time without it, we convert
  14929. ;; so that matching will be successful.
  14930. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  14931. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  14932. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  14933. (setq hour (string-to-number (match-string 1 ans))
  14934. minute (if (match-end 3)
  14935. (string-to-number (match-string 3 ans))
  14936. 0)
  14937. pm (equal ?p
  14938. (string-to-char (downcase (match-string 4 ans)))))
  14939. (if (and (= hour 12) (not pm))
  14940. (setq hour 0)
  14941. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  14942. (setq ans (replace-match (format "%02d:%02d" hour minute)
  14943. t t ans))))
  14944. ;; Check if a time range is given as a duration
  14945. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  14946. (setq hour (string-to-number (match-string 1 ans))
  14947. h2 (+ hour (string-to-number (match-string 3 ans)))
  14948. minute (string-to-number (match-string 2 ans))
  14949. m2 (+ minute (if (match-end 5) (string-to-number
  14950. (match-string 5 ans))0)))
  14951. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  14952. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  14953. t t ans)))
  14954. ;; Check if there is a time range
  14955. (when (boundp 'org-end-time-was-given)
  14956. (setq org-time-was-given nil)
  14957. (when (and (string-match org-plain-time-of-day-regexp ans)
  14958. (match-end 8))
  14959. (setq org-end-time-was-given (match-string 8 ans))
  14960. (setq ans (concat (substring ans 0 (match-beginning 7))
  14961. (substring ans (match-end 7))))))
  14962. (setq tl (parse-time-string ans)
  14963. day (or (nth 3 tl) (nth 3 org-defdecode))
  14964. month
  14965. (cond ((nth 4 tl))
  14966. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  14967. ;; Day was specified. Make sure DAY+MONTH
  14968. ;; combination happens in the future.
  14969. ((nth 3 tl)
  14970. (setq futurep t)
  14971. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  14972. (nth 4 nowdecode)))
  14973. (t (nth 4 org-defdecode)))
  14974. year
  14975. (cond ((and (not kill-year) (nth 5 tl)))
  14976. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  14977. ;; Month was guessed in the future and is at least
  14978. ;; equal to NOWDECODE's. Fix year accordingly.
  14979. (futurep
  14980. (if (or (> month (nth 4 nowdecode))
  14981. (>= day (nth 3 nowdecode)))
  14982. (nth 5 nowdecode)
  14983. (1+ (nth 5 nowdecode))))
  14984. ;; Month was specified. Make sure MONTH+YEAR
  14985. ;; combination happens in the future.
  14986. ((nth 4 tl)
  14987. (setq futurep t)
  14988. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  14989. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  14990. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  14991. (t (nth 5 nowdecode))))
  14992. (t (nth 5 org-defdecode)))
  14993. hour (or (nth 2 tl) (nth 2 org-defdecode))
  14994. minute (or (nth 1 tl) (nth 1 org-defdecode))
  14995. second (or (nth 0 tl) 0)
  14996. wday (nth 6 tl))
  14997. (when (and (eq org-read-date-prefer-future 'time)
  14998. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  14999. (equal day (nth 3 nowdecode))
  15000. (equal month (nth 4 nowdecode))
  15001. (equal year (nth 5 nowdecode))
  15002. (nth 2 tl)
  15003. (or (< (nth 2 tl) (nth 2 nowdecode))
  15004. (and (= (nth 2 tl) (nth 2 nowdecode))
  15005. (nth 1 tl)
  15006. (< (nth 1 tl) (nth 1 nowdecode)))))
  15007. (setq day (1+ day)
  15008. futurep t))
  15009. ;; Special date definitions below
  15010. (cond
  15011. (iso-week
  15012. ;; There was an iso week
  15013. (require 'cal-iso)
  15014. (setq futurep nil)
  15015. (setq year (or iso-year year)
  15016. day (or iso-weekday wday 1)
  15017. wday nil ; to make sure that the trigger below does not match
  15018. iso-date (calendar-gregorian-from-absolute
  15019. (calendar-iso-to-absolute
  15020. (list iso-week day year))))
  15021. ; FIXME: Should we also push ISO weeks into the future?
  15022. ; (when (and org-read-date-prefer-future
  15023. ; (not iso-year)
  15024. ; (< (calendar-absolute-from-gregorian iso-date)
  15025. ; (time-to-days (current-time))))
  15026. ; (setq year (1+ year)
  15027. ; iso-date (calendar-gregorian-from-absolute
  15028. ; (calendar-iso-to-absolute
  15029. ; (list iso-week day year)))))
  15030. (setq month (car iso-date)
  15031. year (nth 2 iso-date)
  15032. day (nth 1 iso-date)))
  15033. (deltan
  15034. (setq futurep nil)
  15035. (unless deltadef
  15036. ;; Pass `current-time' result to `decode-time' (instead of
  15037. ;; calling without arguments) so that only `current-time' has
  15038. ;; to be overridden in tests.
  15039. (let ((now (decode-time (current-time))))
  15040. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15041. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15042. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15043. ((equal deltaw "m") (setq month (+ month deltan)))
  15044. ((equal deltaw "y") (setq year (+ year deltan)))))
  15045. ((and wday (not (nth 3 tl)))
  15046. ;; Weekday was given, but no day, so pick that day in the week
  15047. ;; on or after the derived date.
  15048. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15049. (unless (equal wday wday1)
  15050. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15051. (when (and (boundp 'org-time-was-given)
  15052. (nth 2 tl))
  15053. (setq org-time-was-given t))
  15054. (when (< year 100) (setq year (+ 2000 year)))
  15055. ;; Check of the date is representable
  15056. (if org-read-date-force-compatible-dates
  15057. (progn
  15058. (when (< year 1970)
  15059. (setq year 1970 org-read-date-analyze-forced-year t))
  15060. (when (> year 2037)
  15061. (setq year 2037 org-read-date-analyze-forced-year t)))
  15062. (condition-case nil
  15063. (ignore (encode-time second minute hour day month year))
  15064. (error
  15065. (setq year (nth 5 org-defdecode))
  15066. (setq org-read-date-analyze-forced-year t))))
  15067. (setq org-read-date-analyze-futurep futurep)
  15068. (list second minute hour day month year)))
  15069. (defvar parse-time-weekdays)
  15070. (defun org-read-date-get-relative (s today default)
  15071. "Check string S for special relative date string.
  15072. TODAY and DEFAULT are internal times, for today and for a default.
  15073. Return shift list (N what def-flag)
  15074. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15075. N is the number of WHATs to shift.
  15076. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15077. the DEFAULT date rather than TODAY."
  15078. (require 'parse-time)
  15079. (when (and
  15080. (string-match
  15081. (concat
  15082. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15083. "\\([0-9]+\\)?"
  15084. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15085. "\\([ \t]\\|$\\)") s)
  15086. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15087. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15088. (string-to-char (substring (match-string 1 s) -1))
  15089. ?+))
  15090. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15091. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15092. (what (if (match-end 3) (match-string 3 s) "d"))
  15093. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15094. (date (if rel default today))
  15095. (wday (nth 6 (decode-time date)))
  15096. delta)
  15097. (if wday1
  15098. (progn
  15099. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15100. (when (= delta 0) (setq delta 7))
  15101. (when (= dir ?-)
  15102. (setq delta (- delta 7))
  15103. (when (= delta 0) (setq delta -7)))
  15104. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15105. (list delta "d" rel))
  15106. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15107. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15108. "Turn a user-specified date into the internal representation.
  15109. The internal representation needed by the calendar is (month day year).
  15110. This is a wrapper to handle the brain-dead convention in calendar that
  15111. user function argument order change dependent on argument order."
  15112. (pcase calendar-date-style
  15113. (`american (list arg1 arg2 arg3))
  15114. (`european (list arg2 arg1 arg3))
  15115. (`iso (list arg2 arg3 arg1))))
  15116. (defun org-eval-in-calendar (form &optional keepdate)
  15117. "Eval FORM in the calendar window and return to current window.
  15118. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15119. (let ((sf (selected-frame))
  15120. (sw (selected-window)))
  15121. (select-window (get-buffer-window "*Calendar*" t))
  15122. (eval form)
  15123. (when (and (not keepdate) (calendar-cursor-to-date))
  15124. (let* ((date (calendar-cursor-to-date))
  15125. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15126. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15127. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15128. (select-window sw)
  15129. (select-frame-set-input-focus sf)))
  15130. (defun org-calendar-select ()
  15131. "Return to `org-read-date' with the date currently selected.
  15132. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15133. (interactive)
  15134. (when (calendar-cursor-to-date)
  15135. (let* ((date (calendar-cursor-to-date))
  15136. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15137. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15138. (when (active-minibuffer-window) (exit-minibuffer))))
  15139. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15140. "Insert a date stamp for the date given by the internal TIME.
  15141. See `format-time-string' for the format of TIME.
  15142. WITH-HM means use the stamp format that includes the time of the day.
  15143. INACTIVE means use square brackets instead of angular ones, so that the
  15144. stamp will not contribute to the agenda.
  15145. PRE and POST are optional strings to be inserted before and after the
  15146. stamp.
  15147. The command returns the inserted time stamp."
  15148. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15149. stamp)
  15150. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15151. (insert-before-markers (or pre ""))
  15152. (when (listp extra)
  15153. (setq extra (car extra))
  15154. (if (and (stringp extra)
  15155. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15156. (setq extra (format "-%02d:%02d"
  15157. (string-to-number (match-string 1 extra))
  15158. (string-to-number (match-string 2 extra))))
  15159. (setq extra nil)))
  15160. (when extra
  15161. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15162. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15163. (insert-before-markers (or post ""))
  15164. (setq org-last-inserted-timestamp stamp)))
  15165. (defun org-toggle-time-stamp-overlays ()
  15166. "Toggle the use of custom time stamp formats."
  15167. (interactive)
  15168. (setq org-display-custom-times (not org-display-custom-times))
  15169. (unless org-display-custom-times
  15170. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15171. (while (setq p (next-single-property-change p 'display))
  15172. (when (and (get-text-property p 'display)
  15173. (eq (get-text-property p 'face) 'org-date))
  15174. (remove-text-properties
  15175. p (setq p (next-single-property-change p 'display))
  15176. '(display t))))
  15177. (set-buffer-modified-p bmp)))
  15178. (org-restart-font-lock)
  15179. (setq org-table-may-need-update t)
  15180. (if org-display-custom-times
  15181. (message "Time stamps are overlaid with custom format")
  15182. (message "Time stamp overlays removed")))
  15183. (defun org-display-custom-time (beg end)
  15184. "Overlay modified time stamp format over timestamp between BEG and END."
  15185. (let* ((ts (buffer-substring beg end))
  15186. t1 with-hm tf time str (off 0))
  15187. (save-match-data
  15188. (setq t1 (org-parse-time-string ts t))
  15189. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15190. (setq off (- (match-end 0) (match-beginning 0)))))
  15191. (setq end (- end off))
  15192. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  15193. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15194. time (org-fix-decoded-time t1)
  15195. str (org-add-props
  15196. (format-time-string
  15197. (substring tf 1 -1) (apply 'encode-time time))
  15198. nil 'mouse-face 'highlight))
  15199. (put-text-property beg end 'display str)))
  15200. (defun org-fix-decoded-time (time)
  15201. "Set 0 instead of nil for the first 6 elements of time.
  15202. Don't touch the rest."
  15203. (let ((n 0))
  15204. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15205. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15206. "Difference between TIMESTAMP-STRING and now in days.
  15207. If SECONDS is non-nil, return the difference in seconds."
  15208. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15209. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15210. (funcall fdiff (current-time)))))
  15211. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15212. "Is the time in TIMESTAMP-STRING close to the current date?"
  15213. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15214. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15215. (not (org-entry-is-done-p))))
  15216. (defun org-get-wdays (ts &optional delay zero-delay)
  15217. "Get the deadline lead time appropriate for timestring TS.
  15218. When DELAY is non-nil, get the delay time for scheduled items
  15219. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15220. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15221. don't try to find the delay cookie in the scheduled timestamp."
  15222. (let ((tv (if delay org-scheduled-delay-days
  15223. org-deadline-warning-days)))
  15224. (cond
  15225. ((or (and delay (< tv 0))
  15226. (and delay zero-delay (<= tv 0))
  15227. (and (not delay) (<= tv 0)))
  15228. ;; Enforce this value no matter what
  15229. (- tv))
  15230. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15231. ;; lead time is specified.
  15232. (floor (* (string-to-number (match-string 1 ts))
  15233. (cdr (assoc (match-string 2 ts)
  15234. '(("d" . 1) ("w" . 7)
  15235. ("m" . 30.4) ("y" . 365.25)
  15236. ("h" . 0.041667)))))))
  15237. ;; go for the default.
  15238. (t tv))))
  15239. (defun org-calendar-select-mouse (ev)
  15240. "Return to `org-read-date' with the date currently selected.
  15241. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15242. (interactive "e")
  15243. (mouse-set-point ev)
  15244. (when (calendar-cursor-to-date)
  15245. (let* ((date (calendar-cursor-to-date))
  15246. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15247. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15248. (when (active-minibuffer-window) (exit-minibuffer))))
  15249. (defun org-check-deadlines (ndays)
  15250. "Check if there are any deadlines due or past due.
  15251. A deadline is considered due if it happens within `org-deadline-warning-days'
  15252. days from today's date. If the deadline appears in an entry marked DONE,
  15253. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15254. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15255. are shown."
  15256. (interactive "P")
  15257. (let* ((org-warn-days
  15258. (cond
  15259. ((equal ndays '(4)) 100000)
  15260. (ndays (prefix-numeric-value ndays))
  15261. (t (abs org-deadline-warning-days))))
  15262. (case-fold-search nil)
  15263. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15264. (callback
  15265. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15266. (message "%d deadlines past-due or due within %d days"
  15267. (org-occur regexp nil callback)
  15268. org-warn-days)))
  15269. (defsubst org-re-timestamp (type)
  15270. "Return a regexp for timestamp TYPE.
  15271. Allowed values for TYPE are:
  15272. all: all timestamps
  15273. active: only active timestamps (<...>)
  15274. inactive: only inactive timestamps ([...])
  15275. scheduled: only scheduled timestamps
  15276. deadline: only deadline timestamps
  15277. closed: only closed time-stamps
  15278. When TYPE is nil, fall back on returning a regexp that matches
  15279. both scheduled and deadline timestamps."
  15280. (cl-case type
  15281. (all org-ts-regexp-both)
  15282. (active org-ts-regexp)
  15283. (inactive org-ts-regexp-inactive)
  15284. (scheduled org-scheduled-time-regexp)
  15285. (deadline org-deadline-time-regexp)
  15286. (closed org-closed-time-regexp)
  15287. (otherwise
  15288. (concat "\\<"
  15289. (regexp-opt (list org-deadline-string org-scheduled-string))
  15290. " *<\\([^>]+\\)>"))))
  15291. (defun org-check-before-date (d)
  15292. "Check if there are deadlines or scheduled entries before date D."
  15293. (interactive (list (org-read-date)))
  15294. (let* ((case-fold-search nil)
  15295. (regexp (org-re-timestamp org-ts-type))
  15296. (ts-type org-ts-type)
  15297. (callback
  15298. (lambda ()
  15299. (let ((match (match-string 1)))
  15300. (and (if (memq ts-type '(active inactive all))
  15301. (eq (org-element-type (save-excursion
  15302. (backward-char)
  15303. (org-element-context)))
  15304. 'timestamp)
  15305. (org-at-planning-p))
  15306. (time-less-p
  15307. (org-time-string-to-time match)
  15308. (org-time-string-to-time d)))))))
  15309. (message "%d entries before %s"
  15310. (org-occur regexp nil callback)
  15311. d)))
  15312. (defun org-check-after-date (d)
  15313. "Check if there are deadlines or scheduled entries after date D."
  15314. (interactive (list (org-read-date)))
  15315. (let* ((case-fold-search nil)
  15316. (regexp (org-re-timestamp org-ts-type))
  15317. (ts-type org-ts-type)
  15318. (callback
  15319. (lambda ()
  15320. (let ((match (match-string 1)))
  15321. (and (if (memq ts-type '(active inactive all))
  15322. (eq (org-element-type (save-excursion
  15323. (backward-char)
  15324. (org-element-context)))
  15325. 'timestamp)
  15326. (org-at-planning-p))
  15327. (not (time-less-p
  15328. (org-time-string-to-time match)
  15329. (org-time-string-to-time d))))))))
  15330. (message "%d entries after %s"
  15331. (org-occur regexp nil callback)
  15332. d)))
  15333. (defun org-check-dates-range (start-date end-date)
  15334. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15335. (interactive (list (org-read-date nil nil nil "Range starts")
  15336. (org-read-date nil nil nil "Range end")))
  15337. (let ((case-fold-search nil)
  15338. (regexp (org-re-timestamp org-ts-type))
  15339. (callback
  15340. (let ((type org-ts-type))
  15341. (lambda ()
  15342. (let ((match (match-string 1)))
  15343. (and
  15344. (if (memq type '(active inactive all))
  15345. (eq (org-element-type (save-excursion
  15346. (backward-char)
  15347. (org-element-context)))
  15348. 'timestamp)
  15349. (org-at-planning-p))
  15350. (not (time-less-p
  15351. (org-time-string-to-time match)
  15352. (org-time-string-to-time start-date)))
  15353. (time-less-p
  15354. (org-time-string-to-time match)
  15355. (org-time-string-to-time end-date))))))))
  15356. (message "%d entries between %s and %s"
  15357. (org-occur regexp nil callback) start-date end-date)))
  15358. (defun org-evaluate-time-range (&optional to-buffer)
  15359. "Evaluate a time range by computing the difference between start and end.
  15360. Normally the result is just printed in the echo area, but with prefix arg
  15361. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15362. If the time range is actually in a table, the result is inserted into the
  15363. next column.
  15364. For time difference computation, a year is assumed to be exactly 365
  15365. days in order to avoid rounding problems."
  15366. (interactive "P")
  15367. (or
  15368. (org-clock-update-time-maybe)
  15369. (save-excursion
  15370. (unless (org-at-date-range-p t)
  15371. (goto-char (point-at-bol))
  15372. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15373. (unless (org-at-date-range-p t)
  15374. (user-error "Not at a time-stamp range, and none found in current line")))
  15375. (let* ((ts1 (match-string 1))
  15376. (ts2 (match-string 2))
  15377. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15378. (match-end (match-end 0))
  15379. (time1 (org-time-string-to-time ts1))
  15380. (time2 (org-time-string-to-time ts2))
  15381. (t1 (float-time time1))
  15382. (t2 (float-time time2))
  15383. (diff (abs (- t2 t1)))
  15384. (negative (< (- t2 t1) 0))
  15385. ;; (ys (floor (* 365 24 60 60)))
  15386. (ds (* 24 60 60))
  15387. (hs (* 60 60))
  15388. (fy "%dy %dd %02d:%02d")
  15389. (fy1 "%dy %dd")
  15390. (fd "%dd %02d:%02d")
  15391. (fd1 "%dd")
  15392. (fh "%02d:%02d")
  15393. y d h m align)
  15394. (if havetime
  15395. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15396. y 0
  15397. d (floor (/ diff ds)) diff (mod diff ds)
  15398. h (floor (/ diff hs)) diff (mod diff hs)
  15399. m (floor (/ diff 60)))
  15400. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15401. y 0
  15402. d (floor (+ (/ diff ds) 0.5))
  15403. h 0 m 0))
  15404. (if (not to-buffer)
  15405. (message "%s" (org-make-tdiff-string y d h m))
  15406. (if (org-at-table-p)
  15407. (progn
  15408. (goto-char match-end)
  15409. (setq align t)
  15410. (and (looking-at " *|") (goto-char (match-end 0))))
  15411. (goto-char match-end))
  15412. (when (looking-at
  15413. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  15414. (replace-match ""))
  15415. (when negative (insert " -"))
  15416. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  15417. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  15418. (insert " " (format fh h m))))
  15419. (when align (org-table-align))
  15420. (message "Time difference inserted")))))
  15421. (defun org-make-tdiff-string (y d h m)
  15422. (let ((fmt "")
  15423. (l nil))
  15424. (when (> y 0)
  15425. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  15426. (push y l))
  15427. (when (> d 0)
  15428. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  15429. (push d l))
  15430. (when (> h 0)
  15431. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  15432. (push h l))
  15433. (when (> m 0)
  15434. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  15435. (push m l))
  15436. (apply 'format fmt (nreverse l))))
  15437. (defun org-time-string-to-time (s)
  15438. "Convert timestamp string S into internal time."
  15439. (apply #'encode-time (org-parse-time-string s)))
  15440. (defun org-time-string-to-seconds (s)
  15441. "Convert a timestamp string S into a number of seconds."
  15442. (float-time (org-time-string-to-time s)))
  15443. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  15444. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  15445. "Convert time stamp S to an absolute day number.
  15446. If DAYNR in non-nil, and there is a specifier for a cyclic time
  15447. stamp, get the closest date to DAYNR. If PREFER is
  15448. `past' (respectively `future') return a date past (respectively
  15449. after) or equal to DAYNR.
  15450. POS is the location of time stamp S, as a buffer position in
  15451. BUFFER.
  15452. Diary sexp timestamps are matched against DAYNR, when non-nil.
  15453. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  15454. signaled."
  15455. (cond
  15456. ((string-match "\\`%%\\((.*)\\)" s)
  15457. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  15458. ;; only able to match individual dates. If it fails, raise an
  15459. ;; error.
  15460. (if (and daynr
  15461. (org-diary-sexp-entry
  15462. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  15463. daynr
  15464. (signal 'org-diary-sexp-no-match (list s))))
  15465. (daynr (org-closest-date s daynr prefer))
  15466. (t (time-to-days
  15467. (condition-case errdata
  15468. (apply #'encode-time (org-parse-time-string s))
  15469. (error (error "Bad timestamp `%s'%s\nError was: %s"
  15470. s
  15471. (if (not (and buffer pos)) ""
  15472. (format-message " at %d in buffer `%s'" pos buffer))
  15473. (cdr errdata))))))))
  15474. (defun org-days-to-iso-week (days)
  15475. "Return the iso week number."
  15476. (require 'cal-iso)
  15477. (car (calendar-iso-from-absolute days)))
  15478. (defun org-small-year-to-year (year)
  15479. "Convert 2-digit years into 4-digit years.
  15480. YEAR is expanded into one of the 30 next years, if possible, or
  15481. into a past one. Any year larger than 99 is returned unchanged."
  15482. (if (>= year 100) year
  15483. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  15484. (century (/ current 100))
  15485. (offset (- year (% current 100))))
  15486. (cond ((> offset 30) (+ (* (1- century) 100) year))
  15487. ((> offset -70) (+ (* century 100) year))
  15488. (t (+ (* (1+ century) 100) year))))))
  15489. (defun org-time-from-absolute (d)
  15490. "Return the time corresponding to date D.
  15491. D may be an absolute day number, or a calendar-type list (month day year)."
  15492. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  15493. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  15494. (defvar org-agenda-current-date)
  15495. (defun org-calendar-holiday ()
  15496. "List of holidays, for Diary display in Org mode."
  15497. (require 'holidays)
  15498. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  15499. (and hl (mapconcat #'identity hl "; "))))
  15500. (defun org-diary-sexp-entry (sexp entry d)
  15501. "Process a SEXP diary ENTRY for date D."
  15502. (require 'diary-lib)
  15503. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  15504. ;; dynamically.
  15505. (let* ((sexp `(let ((entry ,entry)
  15506. (date ',d))
  15507. ,(car (read-from-string sexp))))
  15508. (result (if calendar-debug-sexp (eval sexp)
  15509. (condition-case nil
  15510. (eval sexp)
  15511. (error
  15512. (beep)
  15513. (message "Bad sexp at line %d in %s: %s"
  15514. (org-current-line)
  15515. (buffer-file-name) sexp)
  15516. (sleep-for 2))))))
  15517. (cond ((stringp result) (split-string result "; "))
  15518. ((and (consp result)
  15519. (not (consp (cdr result)))
  15520. (stringp (cdr result))) (cdr result))
  15521. ((and (consp result)
  15522. (stringp (car result))) result)
  15523. (result entry))))
  15524. (defun org-diary-to-ical-string (frombuf)
  15525. "Get iCalendar entries from diary entries in buffer FROMBUF.
  15526. This uses the icalendar.el library."
  15527. (let* ((tmpdir temporary-file-directory)
  15528. (tmpfile (make-temp-name
  15529. (expand-file-name "orgics" tmpdir)))
  15530. buf rtn b e)
  15531. (with-current-buffer frombuf
  15532. (icalendar-export-region (point-min) (point-max) tmpfile)
  15533. (setq buf (find-buffer-visiting tmpfile))
  15534. (set-buffer buf)
  15535. (goto-char (point-min))
  15536. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  15537. (setq b (match-beginning 0)))
  15538. (goto-char (point-max))
  15539. (when (re-search-backward "^END:VEVENT" nil t)
  15540. (setq e (match-end 0)))
  15541. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  15542. (kill-buffer buf)
  15543. (delete-file tmpfile)
  15544. rtn))
  15545. (defun org-closest-date (start current prefer)
  15546. "Return closest date to CURRENT starting from START.
  15547. CURRENT and START are both time stamps.
  15548. When PREFER is `past', return a date that is either CURRENT or
  15549. past. When PREFER is `future', return a date that is either
  15550. CURRENT or future.
  15551. Only time stamps with a repeater are modified. Any other time
  15552. stamp stay unchanged. In any case, return value is an absolute
  15553. day number."
  15554. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  15555. ;; No repeater. Do not shift time stamp.
  15556. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15557. (let ((value (string-to-number (match-string 1 start)))
  15558. (type (match-string 2 start)))
  15559. (if (= 0 value)
  15560. ;; Repeater with a 0-value is considered as void.
  15561. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  15562. (let* ((base (org-date-to-gregorian start))
  15563. (target (org-date-to-gregorian current))
  15564. (sday (calendar-absolute-from-gregorian base))
  15565. (cday (calendar-absolute-from-gregorian target))
  15566. n1 n2)
  15567. ;; If START is already past CURRENT, just return START.
  15568. (if (<= cday sday) sday
  15569. ;; Compute closest date before (N1) and closest date past
  15570. ;; (N2) CURRENT.
  15571. (pcase type
  15572. ("h"
  15573. (let ((missing-hours
  15574. (mod (+ (- (* 24 (- cday sday))
  15575. (nth 2 (org-parse-time-string start)))
  15576. org-extend-today-until)
  15577. value)))
  15578. (setf n1 (if (= missing-hours 0) cday
  15579. (- cday (1+ (/ missing-hours 24)))))
  15580. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  15581. ((or "d" "w")
  15582. (let ((value (if (equal type "w") (* 7 value) value)))
  15583. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  15584. (setf n2 (+ n1 value))))
  15585. ("m"
  15586. (let* ((add-months
  15587. (lambda (d n)
  15588. ;; Add N months to gregorian date D, i.e.,
  15589. ;; a list (MONTH DAY YEAR). Return a valid
  15590. ;; gregorian date.
  15591. (let ((m (+ (nth 0 d) n)))
  15592. (list (mod m 12)
  15593. (nth 1 d)
  15594. (+ (/ m 12) (nth 2 d))))))
  15595. (months ; Complete months to TARGET.
  15596. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  15597. (- (nth 0 target) (nth 0 base))
  15598. ;; If START's day is greater than
  15599. ;; TARGET's, remove incomplete month.
  15600. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  15601. value)
  15602. value))
  15603. (before (funcall add-months base months)))
  15604. (setf n1 (calendar-absolute-from-gregorian before))
  15605. (setf n2
  15606. (calendar-absolute-from-gregorian
  15607. (funcall add-months before value)))))
  15608. (_
  15609. (let* ((d (nth 1 base))
  15610. (m (nth 0 base))
  15611. (y (nth 2 base))
  15612. (years ; Complete years to TARGET.
  15613. (* (/ (- (nth 2 target)
  15614. y
  15615. ;; If START's month and day are
  15616. ;; greater than TARGET's, remove
  15617. ;; incomplete year.
  15618. (if (or (> (nth 0 target) m)
  15619. (and (= (nth 0 target) m)
  15620. (> (nth 1 target) d)))
  15621. 0
  15622. 1))
  15623. value)
  15624. value))
  15625. (before (list m d (+ y years))))
  15626. (setf n1 (calendar-absolute-from-gregorian before))
  15627. (setf n2 (calendar-absolute-from-gregorian
  15628. (list m d (+ (nth 2 before) value)))))))
  15629. ;; Handle PREFER parameter, if any.
  15630. (cond
  15631. ((eq prefer 'past) (if (= cday n2) n2 n1))
  15632. ((eq prefer 'future) (if (= cday n1) n1 n2))
  15633. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  15634. (defun org-date-to-gregorian (d)
  15635. "Turn any specification of date D into a Gregorian date for the calendar."
  15636. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  15637. ((and (listp d) (= (length d) 3)) d)
  15638. ((stringp d)
  15639. (let ((d (org-parse-time-string d)))
  15640. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  15641. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  15642. (defun org-parse-time-string (s &optional nodefault)
  15643. "Parse the standard Org time string.
  15644. This should be a lot faster than the normal `parse-time-string'.
  15645. If time is not given, defaults to 0:00. However, with optional
  15646. NODEFAULT, hour and minute fields will be nil if not given."
  15647. (cond ((string-match org-ts-regexp0 s)
  15648. (list 0
  15649. (when (or (match-beginning 8) (not nodefault))
  15650. (string-to-number (or (match-string 8 s) "0")))
  15651. (when (or (match-beginning 7) (not nodefault))
  15652. (string-to-number (or (match-string 7 s) "0")))
  15653. (string-to-number (match-string 4 s))
  15654. (string-to-number (match-string 3 s))
  15655. (string-to-number (match-string 2 s))
  15656. nil nil nil))
  15657. ((string-match "^<[^>]+>$" s)
  15658. ;; FIXME: `decode-time' needs to be called with ZONE as its
  15659. ;; second argument. However, this requires at least Emacs
  15660. ;; 25.1. We can do it when we switch to this version as our
  15661. ;; minimal requirement.
  15662. (decode-time (seconds-to-time (org-matcher-time s))))
  15663. (t (error "Not a standard Org time string: %s" s))))
  15664. (defun org-timestamp-up (&optional arg)
  15665. "Increase the date item at the cursor by one.
  15666. If the cursor is on the year, change the year. If it is on the month,
  15667. the day or the time, change that.
  15668. With prefix ARG, change by that many units."
  15669. (interactive "p")
  15670. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  15671. (defun org-timestamp-down (&optional arg)
  15672. "Decrease the date item at the cursor by one.
  15673. If the cursor is on the year, change the year. If it is on the month,
  15674. the day or the time, change that.
  15675. With prefix ARG, change by that many units."
  15676. (interactive "p")
  15677. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  15678. (defun org-timestamp-up-day (&optional arg)
  15679. "Increase the date in the time stamp by one day.
  15680. With prefix ARG, change that many days."
  15681. (interactive "p")
  15682. (if (and (not (org-at-timestamp-p 'lax))
  15683. (org-at-heading-p))
  15684. (org-todo 'up)
  15685. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  15686. (defun org-timestamp-down-day (&optional arg)
  15687. "Decrease the date in the time stamp by one day.
  15688. With prefix ARG, change that many days."
  15689. (interactive "p")
  15690. (if (and (not (org-at-timestamp-p 'lax))
  15691. (org-at-heading-p))
  15692. (org-todo 'down)
  15693. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  15694. (defun org-at-timestamp-p (&optional extended)
  15695. "Non-nil if point is inside a timestamp.
  15696. By default, the function only consider syntactically valid active
  15697. timestamps. However, the caller may have a broader definition
  15698. for timestamps. As a consequence, optional argument EXTENDED can
  15699. be set to the following values
  15700. `inactive'
  15701. Include also syntactically valid inactive timestamps.
  15702. `agenda'
  15703. Include timestamps allowed in Agenda, i.e., those in
  15704. properties drawers, planning lines and clock lines.
  15705. `lax'
  15706. Ignore context. The function matches any part of the
  15707. document looking like a timestamp. This includes comments,
  15708. example blocks...
  15709. For backward-compatibility with Org 9.0, every other non-nil
  15710. value is equivalent to `inactive'.
  15711. When at a timestamp, return the position of the point as a symbol
  15712. among `bracket', `after', `year', `month', `hour', `minute',
  15713. `day' or a number of character from the last know part of the
  15714. time stamp.
  15715. When matching, the match groups are the following:
  15716. group 1: year
  15717. group 2: month
  15718. group 3: day number
  15719. group 4: day name
  15720. group 5: hours, if any
  15721. group 6: minutes, if any"
  15722. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  15723. (pos (point))
  15724. (match?
  15725. (let ((boundaries (org-in-regexp regexp)))
  15726. (save-match-data
  15727. (cond ((null boundaries) nil)
  15728. ((eq extended 'lax) t)
  15729. (t
  15730. (or (and (eq extended 'agenda)
  15731. (or (org-at-planning-p)
  15732. (org-at-property-p)
  15733. (and (bound-and-true-p
  15734. org-agenda-include-inactive-timestamps)
  15735. (org-at-clock-log-p))))
  15736. (eq 'timestamp
  15737. (save-excursion
  15738. (when (= pos (cdr boundaries)) (forward-char -1))
  15739. (org-element-type (org-element-context)))))))))))
  15740. (cond
  15741. ((not match?) nil)
  15742. ((= pos (match-beginning 0)) 'bracket)
  15743. ;; Distinguish location right before the closing bracket from
  15744. ;; right after it.
  15745. ((= pos (1- (match-end 0))) 'bracket)
  15746. ((= pos (match-end 0)) 'after)
  15747. ((org-pos-in-match-range pos 2) 'year)
  15748. ((org-pos-in-match-range pos 3) 'month)
  15749. ((org-pos-in-match-range pos 7) 'hour)
  15750. ((org-pos-in-match-range pos 8) 'minute)
  15751. ((or (org-pos-in-match-range pos 4)
  15752. (org-pos-in-match-range pos 5)) 'day)
  15753. ((and (> pos (or (match-end 8) (match-end 5)))
  15754. (< pos (match-end 0)))
  15755. (- pos (or (match-end 8) (match-end 5))))
  15756. (t 'day))))
  15757. (defun org-toggle-timestamp-type ()
  15758. "Toggle the type (<active> or [inactive]) of a time stamp."
  15759. (interactive)
  15760. (when (org-at-timestamp-p 'lax)
  15761. (let ((beg (match-beginning 0)) (end (match-end 0))
  15762. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  15763. (save-excursion
  15764. (goto-char beg)
  15765. (while (re-search-forward "[][<>]" end t)
  15766. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  15767. t t)))
  15768. (message "Timestamp is now %sactive"
  15769. (if (equal (char-after beg) ?<) "" "in")))))
  15770. (defun org-at-clock-log-p ()
  15771. "Non-nil if point is on a clock log line."
  15772. (and (org-match-line org-clock-line-re)
  15773. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  15774. (defvar org-clock-history) ; defined in org-clock.el
  15775. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  15776. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  15777. "Change the date in the time stamp at point.
  15778. The date will be changed by N times WHAT. WHAT can be `day', `month',
  15779. `year', `minute', `second'. If WHAT is not given, the cursor position
  15780. in the timestamp determines what will be changed.
  15781. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  15782. (let ((origin (point))
  15783. (timestamp? (org-at-timestamp-p 'lax))
  15784. origin-cat
  15785. with-hm inactive
  15786. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  15787. extra rem
  15788. ts time time0 fixnext clrgx)
  15789. (unless timestamp? (user-error "Not at a timestamp"))
  15790. (if (and (not what) (eq timestamp? 'bracket))
  15791. (org-toggle-timestamp-type)
  15792. ;; Point isn't on brackets. Remember the part of the time-stamp
  15793. ;; the point was in. Indeed, size of time-stamps may change,
  15794. ;; but point must be kept in the same category nonetheless.
  15795. (setq origin-cat timestamp?)
  15796. (when (and (not what) (not (eq timestamp? 'day))
  15797. org-display-custom-times
  15798. (get-text-property (point) 'display)
  15799. (not (get-text-property (1- (point)) 'display)))
  15800. (setq timestamp? 'day))
  15801. (setq timestamp? (or what timestamp?)
  15802. inactive (= (char-after (match-beginning 0)) ?\[)
  15803. ts (match-string 0))
  15804. (replace-match "")
  15805. (when (string-match
  15806. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  15807. ts)
  15808. (setq extra (match-string 1 ts))
  15809. (when suppress-tmp-delay
  15810. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  15811. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  15812. (setq with-hm t))
  15813. (setq time0 (org-parse-time-string ts))
  15814. (when (and updown
  15815. (eq timestamp? 'minute)
  15816. (not current-prefix-arg))
  15817. ;; This looks like s-up and s-down. Change by one rounding step.
  15818. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  15819. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  15820. (setcar (cdr time0) (+ (nth 1 time0)
  15821. (if (> n 0) (- rem) (- dm rem))))))
  15822. (setq time
  15823. (apply #'encode-time
  15824. (or (car time0) 0)
  15825. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  15826. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  15827. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  15828. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  15829. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  15830. (nthcdr 6 time0)))
  15831. (when (and (memq timestamp? '(hour minute))
  15832. extra
  15833. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  15834. (setq extra (org-modify-ts-extra
  15835. extra
  15836. (if (eq timestamp? 'hour) 2 5)
  15837. n dm)))
  15838. (when (integerp timestamp?)
  15839. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  15840. (when (eq what 'calendar)
  15841. (let ((cal-date (org-get-date-from-calendar)))
  15842. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  15843. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  15844. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  15845. (setcar time0 (or (car time0) 0))
  15846. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  15847. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  15848. (setq time (apply 'encode-time time0))))
  15849. ;; Insert the new time-stamp, and ensure point stays in the same
  15850. ;; category as before (i.e. not after the last position in that
  15851. ;; category).
  15852. (let ((pos (point)))
  15853. ;; Stay before inserted string. `save-excursion' is of no use.
  15854. (setq org-last-changed-timestamp
  15855. (org-insert-time-stamp time with-hm inactive nil nil extra))
  15856. (goto-char pos))
  15857. (save-match-data
  15858. (looking-at org-ts-regexp3)
  15859. (goto-char
  15860. (pcase origin-cat
  15861. ;; `day' category ends before `hour' if any, or at the end
  15862. ;; of the day name.
  15863. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  15864. (`hour (min (match-end 7) origin))
  15865. (`minute (min (1- (match-end 8)) origin))
  15866. ((pred integerp) (min (1- (match-end 0)) origin))
  15867. ;; Point was right after the time-stamp. However, the
  15868. ;; time-stamp length might have changed, so refer to
  15869. ;; (match-end 0) instead.
  15870. (`after (match-end 0))
  15871. ;; `year' and `month' have both fixed size: point couldn't
  15872. ;; have moved into another part.
  15873. (_ origin))))
  15874. ;; Update clock if on a CLOCK line.
  15875. (org-clock-update-time-maybe)
  15876. ;; Maybe adjust the closest clock in `org-clock-history'
  15877. (when org-clock-adjust-closest
  15878. (if (not (and (org-at-clock-log-p)
  15879. (< 1 (length (delq nil (mapcar 'marker-position
  15880. org-clock-history))))))
  15881. (message "No clock to adjust")
  15882. (cond ((save-excursion ; fix previous clock?
  15883. (re-search-backward org-ts-regexp0 nil t)
  15884. (looking-back (concat org-clock-string " \\[")
  15885. (line-beginning-position)))
  15886. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  15887. ((save-excursion ; fix next clock?
  15888. (re-search-backward org-ts-regexp0 nil t)
  15889. (looking-at (concat org-ts-regexp0 "\\] =>")))
  15890. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  15891. (save-window-excursion
  15892. ;; Find closest clock to point, adjust the previous/next one in history
  15893. (let* ((p (save-excursion (org-back-to-heading t)))
  15894. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  15895. (clfixnth
  15896. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  15897. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  15898. (if (not clfixpos)
  15899. (message "No clock to adjust")
  15900. (save-excursion
  15901. (org-goto-marker-or-bmk clfixpos)
  15902. (org-show-subtree)
  15903. (when (re-search-forward clrgx nil t)
  15904. (goto-char (match-beginning 1))
  15905. (let (org-clock-adjust-closest)
  15906. (org-timestamp-change n timestamp? updown))
  15907. (message "Clock adjusted in %s for heading: %s"
  15908. (file-name-nondirectory (buffer-file-name))
  15909. (org-get-heading t t)))))))))
  15910. ;; Try to recenter the calendar window, if any.
  15911. (when (and org-calendar-follow-timestamp-change
  15912. (get-buffer-window "*Calendar*" t)
  15913. (memq timestamp? '(day month year)))
  15914. (org-recenter-calendar (time-to-days time))))))
  15915. (defun org-modify-ts-extra (s pos n dm)
  15916. "Change the different parts of the lead-time and repeat fields in timestamp."
  15917. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  15918. ng h m new rem)
  15919. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  15920. (cond
  15921. ((or (org-pos-in-match-range pos 2)
  15922. (org-pos-in-match-range pos 3))
  15923. (setq m (string-to-number (match-string 3 s))
  15924. h (string-to-number (match-string 2 s)))
  15925. (if (org-pos-in-match-range pos 2)
  15926. (setq h (+ h n))
  15927. (setq n (* dm (with-no-warnings (signum n))))
  15928. (unless (= 0 (setq rem (% m dm)))
  15929. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  15930. (setq m (+ m n)))
  15931. (when (< m 0) (setq m (+ m 60) h (1- h)))
  15932. (when (> m 59) (setq m (- m 60) h (1+ h)))
  15933. (setq h (mod h 24))
  15934. (setq ng 1 new (format "-%02d:%02d" h m)))
  15935. ((org-pos-in-match-range pos 6)
  15936. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  15937. ((org-pos-in-match-range pos 5)
  15938. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  15939. ((org-pos-in-match-range pos 9)
  15940. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  15941. ((org-pos-in-match-range pos 8)
  15942. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  15943. (when ng
  15944. (setq s (concat
  15945. (substring s 0 (match-beginning ng))
  15946. new
  15947. (substring s (match-end ng))))))
  15948. s))
  15949. (defun org-recenter-calendar (d)
  15950. "If the calendar is visible, recenter it to date D."
  15951. (let ((cwin (get-buffer-window "*Calendar*" t)))
  15952. (when cwin
  15953. (let ((calendar-move-hook nil))
  15954. (with-selected-window cwin
  15955. (calendar-goto-date
  15956. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  15957. (defun org-goto-calendar (&optional arg)
  15958. "Go to the Emacs calendar at the current date.
  15959. If there is a time stamp in the current line, go to that date.
  15960. A prefix ARG can be used to force the current date."
  15961. (interactive "P")
  15962. (let ((calendar-move-hook nil)
  15963. (calendar-view-holidays-initially-flag nil)
  15964. (calendar-view-diary-initially-flag nil)
  15965. diff)
  15966. (when (or (org-at-timestamp-p 'lax)
  15967. (org-match-line (concat ".*" org-ts-regexp)))
  15968. (let ((d1 (time-to-days (current-time)))
  15969. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  15970. (setq diff (- d2 d1))))
  15971. (calendar)
  15972. (calendar-goto-today)
  15973. (when (and diff (not arg)) (calendar-forward-day diff))))
  15974. (defun org-get-date-from-calendar ()
  15975. "Return a list (month day year) of date at point in calendar."
  15976. (with-current-buffer "*Calendar*"
  15977. (save-match-data
  15978. (calendar-cursor-to-date))))
  15979. (defun org-date-from-calendar ()
  15980. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  15981. If there is already a time stamp at the cursor position, update it."
  15982. (interactive)
  15983. (if (org-at-timestamp-p 'lax)
  15984. (org-timestamp-change 0 'calendar)
  15985. (let ((cal-date (org-get-date-from-calendar)))
  15986. (org-insert-time-stamp
  15987. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  15988. (defcustom org-effort-durations
  15989. `(("min" . 1)
  15990. ("h" . 60)
  15991. ("d" . ,(* 60 8))
  15992. ("w" . ,(* 60 8 5))
  15993. ("m" . ,(* 60 8 5 4))
  15994. ("y" . ,(* 60 8 5 40)))
  15995. "Conversion factor to minutes for an effort modifier.
  15996. Each entry has the form (MODIFIER . MINUTES).
  15997. In an effort string, a number followed by MODIFIER is multiplied
  15998. by the specified number of MINUTES to obtain an effort in
  15999. minutes.
  16000. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16001. effort string \"2hours\" is equivalent to 120 minutes."
  16002. :group 'org-agenda
  16003. :version "26.1"
  16004. :package-version '(Org . "8.3")
  16005. :type '(alist :key-type (string :tag "Modifier")
  16006. :value-type (number :tag "Minutes")))
  16007. (defcustom org-image-actual-width t
  16008. "Should we use the actual width of images when inlining them?
  16009. When set to t, always use the image width.
  16010. When set to a number, use imagemagick (when available) to set
  16011. the image's width to this value.
  16012. When set to a number in a list, try to get the width from any
  16013. #+ATTR.* keyword if it matches a width specification like
  16014. #+ATTR_HTML: :width 300px
  16015. and fall back on that number if none is found.
  16016. When set to nil, try to get the width from an #+ATTR.* keyword
  16017. and fall back on the original width if none is found.
  16018. This requires Emacs >= 24.1, build with imagemagick support."
  16019. :group 'org-appearance
  16020. :version "24.4"
  16021. :package-version '(Org . "8.0")
  16022. :type '(choice
  16023. (const :tag "Use the image width" t)
  16024. (integer :tag "Use a number of pixels")
  16025. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16026. (const :tag "Use #+ATTR* or don't resize" nil)))
  16027. (defcustom org-agenda-inhibit-startup nil
  16028. "Inhibit startup when preparing agenda buffers.
  16029. When this variable is t, the initialization of the Org agenda
  16030. buffers is inhibited: e.g. the visibility state is not set, the
  16031. tables are not re-aligned, etc."
  16032. :type 'boolean
  16033. :version "24.3"
  16034. :group 'org-agenda)
  16035. (defcustom org-agenda-ignore-properties nil
  16036. "Avoid updating text properties when building the agenda.
  16037. Properties are used to prepare buffers for effort estimates,
  16038. appointments, statistics and subtree-local categories.
  16039. If you don't use these in the agenda, you can add them to this
  16040. list and agenda building will be a bit faster.
  16041. The value is a list, with zero or more of the symbols `effort', `appt',
  16042. `stats' or `category'."
  16043. :type '(set :greedy t
  16044. (const effort)
  16045. (const appt)
  16046. (const stats)
  16047. (const category))
  16048. :version "26.1"
  16049. :package-version '(Org . "8.3")
  16050. :group 'org-agenda)
  16051. ;;;; Files
  16052. (defun org-save-all-org-buffers ()
  16053. "Save all Org buffers without user confirmation."
  16054. (interactive)
  16055. (message "Saving all Org buffers...")
  16056. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16057. (when (featurep 'org-id) (org-id-locations-save))
  16058. (message "Saving all Org buffers... done"))
  16059. (defun org-revert-all-org-buffers ()
  16060. "Revert all Org buffers.
  16061. Prompt for confirmation when there are unsaved changes.
  16062. Be sure you know what you are doing before letting this function
  16063. overwrite your changes.
  16064. This function is useful in a setup where one tracks Org files
  16065. with a version control system, to revert on one machine after pulling
  16066. changes from another. I believe the procedure must be like this:
  16067. 1. M-x org-save-all-org-buffers
  16068. 2. Pull changes from the other machine, resolve conflicts
  16069. 3. M-x org-revert-all-org-buffers"
  16070. (interactive)
  16071. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16072. (user-error "Abort"))
  16073. (save-excursion
  16074. (save-window-excursion
  16075. (dolist (b (buffer-list))
  16076. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16077. (with-current-buffer b buffer-file-name))
  16078. (pop-to-buffer-same-window b)
  16079. (revert-buffer t 'no-confirm)))
  16080. (when (and (featurep 'org-id) org-id-track-globally)
  16081. (org-id-locations-load)))))
  16082. ;;;; Agenda files
  16083. ;;;###autoload
  16084. (defun org-switchb (&optional arg)
  16085. "Switch between Org buffers.
  16086. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16087. With `\\[universal-argument] \\[universal-argument]' \
  16088. prefix, restrict available buffers to agenda files."
  16089. (interactive "P")
  16090. (let ((blist (org-buffer-list
  16091. (cond ((equal arg '(4)) 'files)
  16092. ((equal arg '(16)) 'agenda)))))
  16093. (pop-to-buffer-same-window
  16094. (completing-read "Org buffer: "
  16095. (mapcar #'list (mapcar #'buffer-name blist))
  16096. nil t))))
  16097. (defun org-buffer-list (&optional predicate exclude-tmp)
  16098. "Return a list of Org buffers.
  16099. PREDICATE can be `export', `files' or `agenda'.
  16100. export restrict the list to Export buffers.
  16101. files restrict the list to buffers visiting Org files.
  16102. agenda restrict the list to buffers visiting agenda files.
  16103. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16104. (let* ((bfn nil)
  16105. (agenda-files (and (eq predicate 'agenda)
  16106. (mapcar 'file-truename (org-agenda-files t))))
  16107. (filter
  16108. (cond
  16109. ((eq predicate 'files)
  16110. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16111. ((eq predicate 'export)
  16112. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16113. ((eq predicate 'agenda)
  16114. (lambda (b)
  16115. (with-current-buffer b
  16116. (and (derived-mode-p 'org-mode)
  16117. (setq bfn (buffer-file-name b))
  16118. (member (file-truename bfn) agenda-files)))))
  16119. (t (lambda (b) (with-current-buffer b
  16120. (or (derived-mode-p 'org-mode)
  16121. (string-match "\\*Org .*Export"
  16122. (buffer-name b)))))))))
  16123. (delq nil
  16124. (mapcar
  16125. (lambda(b)
  16126. (if (and (funcall filter b)
  16127. (or (not exclude-tmp)
  16128. (not (string-match "tmp" (buffer-name b)))))
  16129. b
  16130. nil))
  16131. (buffer-list)))))
  16132. (defun org-agenda-files (&optional unrestricted archives)
  16133. "Get the list of agenda files.
  16134. Optional UNRESTRICTED means return the full list even if a restriction
  16135. is currently in place.
  16136. When ARCHIVES is t, include all archive files that are really being
  16137. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16138. `org-agenda-archives-mode' is t."
  16139. (let ((files
  16140. (cond
  16141. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16142. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16143. ((listp org-agenda-files) org-agenda-files)
  16144. (t (error "Invalid value of `org-agenda-files'")))))
  16145. (setq files (apply 'append
  16146. (mapcar (lambda (f)
  16147. (if (file-directory-p f)
  16148. (directory-files
  16149. f t org-agenda-file-regexp)
  16150. (list f)))
  16151. files)))
  16152. (when org-agenda-skip-unavailable-files
  16153. (setq files (delq nil
  16154. (mapcar (function
  16155. (lambda (file)
  16156. (and (file-readable-p file) file)))
  16157. files))))
  16158. (when (or (eq archives t)
  16159. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16160. (setq files (org-add-archive-files files)))
  16161. files))
  16162. (defun org-agenda-file-p (&optional file)
  16163. "Return non-nil, if FILE is an agenda file.
  16164. If FILE is omitted, use the file associated with the current
  16165. buffer."
  16166. (let ((fname (or file (buffer-file-name))))
  16167. (and fname
  16168. (member (file-truename fname)
  16169. (mapcar #'file-truename (org-agenda-files t))))))
  16170. (defun org-edit-agenda-file-list ()
  16171. "Edit the list of agenda files.
  16172. Depending on setup, this either uses customize to edit the variable
  16173. `org-agenda-files', or it visits the file that is holding the list. In the
  16174. latter case, the buffer is set up in a way that saving it automatically kills
  16175. the buffer and restores the previous window configuration."
  16176. (interactive)
  16177. (if (stringp org-agenda-files)
  16178. (let ((cw (current-window-configuration)))
  16179. (find-file org-agenda-files)
  16180. (setq-local org-window-configuration cw)
  16181. (add-hook 'after-save-hook
  16182. (lambda ()
  16183. (set-window-configuration
  16184. (prog1 org-window-configuration
  16185. (kill-buffer (current-buffer))))
  16186. (org-install-agenda-files-menu)
  16187. (message "New agenda file list installed"))
  16188. nil 'local)
  16189. (message "%s" (substitute-command-keys
  16190. "Edit list and finish with \\[save-buffer]")))
  16191. (customize-variable 'org-agenda-files)))
  16192. (defun org-store-new-agenda-file-list (list)
  16193. "Set new value for the agenda file list and save it correctly."
  16194. (if (stringp org-agenda-files)
  16195. (let ((fe (org-read-agenda-file-list t)) b u)
  16196. (while (setq b (find-buffer-visiting org-agenda-files))
  16197. (kill-buffer b))
  16198. (with-temp-file org-agenda-files
  16199. (insert
  16200. (mapconcat
  16201. (lambda (f) ;; Keep un-expanded entries.
  16202. (if (setq u (assoc f fe))
  16203. (cdr u)
  16204. f))
  16205. list "\n")
  16206. "\n")))
  16207. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16208. (org-insert-mode-line-in-empty-file nil))
  16209. (setq org-agenda-files list)
  16210. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16211. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16212. "Read the list of agenda files from a file.
  16213. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16214. filenames, used by `org-store-new-agenda-file-list' to write back
  16215. un-expanded file names."
  16216. (when (file-directory-p org-agenda-files)
  16217. (error "`org-agenda-files' cannot be a single directory"))
  16218. (when (stringp org-agenda-files)
  16219. (with-temp-buffer
  16220. (insert-file-contents org-agenda-files)
  16221. (mapcar
  16222. (lambda (f)
  16223. (let ((e (expand-file-name (substitute-in-file-name f)
  16224. org-directory)))
  16225. (if pair-with-expansion
  16226. (cons e f)
  16227. e)))
  16228. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16229. ;;;###autoload
  16230. (defun org-cycle-agenda-files ()
  16231. "Cycle through the files in `org-agenda-files'.
  16232. If the current buffer visits an agenda file, find the next one in the list.
  16233. If the current buffer does not, find the first agenda file."
  16234. (interactive)
  16235. (let* ((fs (or (org-agenda-files t)
  16236. (user-error "No agenda files")))
  16237. (files (copy-sequence fs))
  16238. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16239. file)
  16240. (when tcf
  16241. (while (and (setq file (pop files))
  16242. (not (equal (file-truename file) tcf)))))
  16243. (find-file (car (or files fs)))
  16244. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16245. (defun org-agenda-file-to-front (&optional to-end)
  16246. "Move/add the current file to the top of the agenda file list.
  16247. If the file is not present in the list, it is added to the front. If it is
  16248. present, it is moved there. With optional argument TO-END, add/move to the
  16249. end of the list."
  16250. (interactive "P")
  16251. (let ((org-agenda-skip-unavailable-files nil)
  16252. (file-alist (mapcar (lambda (x)
  16253. (cons (file-truename x) x))
  16254. (org-agenda-files t)))
  16255. (ctf (file-truename
  16256. (or buffer-file-name
  16257. (user-error "Please save the current buffer to a file"))))
  16258. x had)
  16259. (setq x (assoc ctf file-alist) had x)
  16260. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16261. (if to-end
  16262. (setq file-alist (append (delq x file-alist) (list x)))
  16263. (setq file-alist (cons x (delq x file-alist))))
  16264. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16265. (org-install-agenda-files-menu)
  16266. (message "File %s to %s of agenda file list"
  16267. (if had "moved" "added") (if to-end "end" "front"))))
  16268. (defun org-remove-file (&optional file)
  16269. "Remove current file from the list of files in variable `org-agenda-files'.
  16270. These are the files which are being checked for agenda entries.
  16271. Optional argument FILE means use this file instead of the current."
  16272. (interactive)
  16273. (let* ((org-agenda-skip-unavailable-files nil)
  16274. (file (or file buffer-file-name
  16275. (user-error "Current buffer does not visit a file")))
  16276. (true-file (file-truename file))
  16277. (afile (abbreviate-file-name file))
  16278. (files (delq nil (mapcar
  16279. (lambda (x)
  16280. (unless (equal true-file
  16281. (file-truename x))
  16282. x))
  16283. (org-agenda-files t)))))
  16284. (if (not (= (length files) (length (org-agenda-files t))))
  16285. (progn
  16286. (org-store-new-agenda-file-list files)
  16287. (org-install-agenda-files-menu)
  16288. (message "Removed from Org Agenda list: %s" afile))
  16289. (message "File was not in list: %s (not removed)" afile))))
  16290. (defun org-file-menu-entry (file)
  16291. (vector file (list 'find-file file) t))
  16292. (defun org-check-agenda-file (file)
  16293. "Make sure FILE exists. If not, ask user what to do."
  16294. (unless (file-exists-p file)
  16295. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16296. (abbreviate-file-name file))
  16297. (let ((r (downcase (read-char-exclusive))))
  16298. (cond
  16299. ((equal r ?r)
  16300. (org-remove-file file)
  16301. (throw 'nextfile t))
  16302. (t (user-error "Abort"))))))
  16303. (defun org-get-agenda-file-buffer (file)
  16304. "Get an agenda buffer visiting FILE.
  16305. If the buffer needs to be created, add it to the list of buffers
  16306. which might be released later."
  16307. (let ((buf (org-find-base-buffer-visiting file)))
  16308. (if buf
  16309. buf ; just return it
  16310. ;; Make a new buffer and remember it
  16311. (setq buf (find-file-noselect file))
  16312. (when buf (push buf org-agenda-new-buffers))
  16313. buf)))
  16314. (defun org-release-buffers (blist)
  16315. "Release all buffers in list, asking the user for confirmation when needed.
  16316. When a buffer is unmodified, it is just killed. When modified, it is saved
  16317. \(if the user agrees) and then killed."
  16318. (let (file)
  16319. (dolist (buf blist)
  16320. (setq file (buffer-file-name buf))
  16321. (when (and (buffer-modified-p buf)
  16322. file
  16323. (y-or-n-p (format "Save file %s? " file)))
  16324. (with-current-buffer buf (save-buffer)))
  16325. (kill-buffer buf))))
  16326. (defun org-agenda-prepare-buffers (files)
  16327. "Create buffers for all agenda files, protect archived trees and comments."
  16328. (interactive)
  16329. (let ((pa '(:org-archived t))
  16330. (pc '(:org-comment t))
  16331. (pall '(:org-archived t :org-comment t))
  16332. (inhibit-read-only t)
  16333. (org-inhibit-startup org-agenda-inhibit-startup)
  16334. (rea (org-make-tag-string (list org-archive-tag)))
  16335. re pos)
  16336. (setq org-tag-alist-for-agenda nil
  16337. org-tag-groups-alist-for-agenda nil)
  16338. (save-excursion
  16339. (save-restriction
  16340. (dolist (file files)
  16341. (catch 'nextfile
  16342. (if (bufferp file)
  16343. (set-buffer file)
  16344. (org-check-agenda-file file)
  16345. (set-buffer (org-get-agenda-file-buffer file)))
  16346. (widen)
  16347. (org-set-regexps-and-options 'tags-only)
  16348. (setq pos (point))
  16349. (or (memq 'category org-agenda-ignore-properties)
  16350. (org-refresh-category-properties))
  16351. (or (memq 'stats org-agenda-ignore-properties)
  16352. (org-refresh-stats-properties))
  16353. (or (memq 'effort org-agenda-ignore-properties)
  16354. (org-refresh-effort-properties))
  16355. (or (memq 'appt org-agenda-ignore-properties)
  16356. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16357. (setq org-todo-keywords-for-agenda
  16358. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16359. (setq org-done-keywords-for-agenda
  16360. (append org-done-keywords-for-agenda org-done-keywords))
  16361. (setq org-todo-keyword-alist-for-agenda
  16362. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16363. (setq org-tag-alist-for-agenda
  16364. (org-tag-add-to-alist
  16365. org-tag-alist-for-agenda
  16366. org-current-tag-alist))
  16367. ;; Merge current file's tag groups into global
  16368. ;; `org-tag-groups-alist-for-agenda'.
  16369. (when org-group-tags
  16370. (dolist (alist org-tag-groups-alist)
  16371. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16372. (if old
  16373. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16374. (push alist org-tag-groups-alist-for-agenda)))))
  16375. (org-with-silent-modifications
  16376. (save-excursion
  16377. (remove-text-properties (point-min) (point-max) pall)
  16378. (when org-agenda-skip-archived-trees
  16379. (goto-char (point-min))
  16380. (while (re-search-forward rea nil t)
  16381. (when (org-at-heading-p t)
  16382. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16383. (goto-char (point-min))
  16384. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16385. (while (re-search-forward re nil t)
  16386. (when (save-match-data (org-in-commented-heading-p t))
  16387. (add-text-properties
  16388. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16389. (goto-char pos)))))
  16390. (setq org-todo-keywords-for-agenda
  16391. (org-uniquify org-todo-keywords-for-agenda))
  16392. (setq org-todo-keyword-alist-for-agenda
  16393. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16394. ;;;; CDLaTeX minor mode
  16395. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16396. "Keymap for the minor `org-cdlatex-mode'.")
  16397. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  16398. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  16399. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  16400. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  16401. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  16402. (defvar org-cdlatex-texmathp-advice-is-done nil
  16403. "Flag remembering if we have applied the advice to texmathp already.")
  16404. (define-minor-mode org-cdlatex-mode
  16405. "Toggle the minor `org-cdlatex-mode'.
  16406. This mode supports entering LaTeX environment and math in LaTeX fragments
  16407. in Org mode.
  16408. \\{org-cdlatex-mode-map}"
  16409. nil " OCDL" nil
  16410. (when org-cdlatex-mode
  16411. (require 'cdlatex)
  16412. (run-hooks 'cdlatex-mode-hook)
  16413. (cdlatex-compute-tables))
  16414. (unless org-cdlatex-texmathp-advice-is-done
  16415. (setq org-cdlatex-texmathp-advice-is-done t)
  16416. (defadvice texmathp (around org-math-always-on activate)
  16417. "Always return t in Org buffers.
  16418. This is because we want to insert math symbols without dollars even outside
  16419. the LaTeX math segments. If Org mode thinks that point is actually inside
  16420. an embedded LaTeX fragment, let `texmathp' do its job.
  16421. `\\[org-cdlatex-mode-map]'"
  16422. (interactive)
  16423. (let (p)
  16424. (cond
  16425. ((not (derived-mode-p 'org-mode)) ad-do-it)
  16426. ((eq this-command 'cdlatex-math-symbol)
  16427. (setq ad-return-value t
  16428. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  16429. (t
  16430. (let ((p (org-inside-LaTeX-fragment-p)))
  16431. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  16432. (setq ad-return-value t
  16433. texmathp-why '("Org mode embedded math" . 0))
  16434. (when p ad-do-it)))))))))
  16435. (defun turn-on-org-cdlatex ()
  16436. "Unconditionally turn on `org-cdlatex-mode'."
  16437. (org-cdlatex-mode 1))
  16438. (defun org-try-cdlatex-tab ()
  16439. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  16440. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  16441. - inside a LaTeX fragment, or
  16442. - after the first word in a line, where an abbreviation expansion could
  16443. insert a LaTeX environment."
  16444. (when org-cdlatex-mode
  16445. (cond
  16446. ;; Before any word on the line: No expansion possible.
  16447. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  16448. ;; Just after first word on the line: Expand it. Make sure it
  16449. ;; cannot happen on headlines, though.
  16450. ((save-excursion
  16451. (skip-chars-backward "a-zA-Z0-9*")
  16452. (skip-chars-backward " \t")
  16453. (and (bolp) (not (org-at-heading-p))))
  16454. (cdlatex-tab) t)
  16455. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  16456. (defun org-cdlatex-underscore-caret (&optional _arg)
  16457. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  16458. Revert to the normal definition outside of these fragments."
  16459. (interactive "P")
  16460. (if (org-inside-LaTeX-fragment-p)
  16461. (call-interactively 'cdlatex-sub-superscript)
  16462. (let (org-cdlatex-mode)
  16463. (call-interactively (key-binding (vector last-input-event))))))
  16464. (defun org-cdlatex-math-modify (&optional _arg)
  16465. "Execute `cdlatex-math-modify' in LaTeX fragments.
  16466. Revert to the normal definition outside of these fragments."
  16467. (interactive "P")
  16468. (if (org-inside-LaTeX-fragment-p)
  16469. (call-interactively 'cdlatex-math-modify)
  16470. (let (org-cdlatex-mode)
  16471. (call-interactively (key-binding (vector last-input-event))))))
  16472. (defun org-cdlatex-environment-indent (&optional environment item)
  16473. "Execute `cdlatex-environment' and indent the inserted environment.
  16474. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  16475. The inserted environment is indented to current indentation
  16476. unless point is at the beginning of the line, in which the
  16477. environment remains unintended."
  16478. (interactive)
  16479. ;; cdlatex-environment always return nil. Therefore, capture output
  16480. ;; first and determine if an environment was selected.
  16481. (let* ((beg (point-marker))
  16482. (end (copy-marker (point) t))
  16483. (inserted (progn
  16484. (ignore-errors (cdlatex-environment environment item))
  16485. (< beg end)))
  16486. ;; Figure out how many lines to move forward after the
  16487. ;; environment has been inserted.
  16488. (lines (when inserted
  16489. (save-excursion
  16490. (- (cl-loop while (< beg (point))
  16491. with x = 0
  16492. do (forward-line -1)
  16493. (cl-incf x)
  16494. finally return x)
  16495. (if (progn (goto-char beg)
  16496. (and (progn (skip-chars-forward " \t") (eolp))
  16497. (progn (skip-chars-backward " \t") (bolp))))
  16498. 1 0)))))
  16499. (env (org-trim (delete-and-extract-region beg end))))
  16500. (when inserted
  16501. ;; Get indentation of next line unless at column 0.
  16502. (let ((ind (if (bolp) 0
  16503. (save-excursion
  16504. (org-return-indent)
  16505. (prog1 (org-get-indentation)
  16506. (when (progn (skip-chars-forward " \t") (eolp))
  16507. (delete-region beg (point)))))))
  16508. (bol (progn (skip-chars-backward " \t") (bolp))))
  16509. ;; Insert a newline before environment unless at column zero
  16510. ;; to "escape" the current line. Insert a newline if
  16511. ;; something is one the same line as \end{ENVIRONMENT}.
  16512. (insert
  16513. (concat (unless bol "\n") env
  16514. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  16515. (unless (zerop ind)
  16516. (save-excursion
  16517. (goto-char beg)
  16518. (while (< (point) end)
  16519. (unless (eolp) (indent-line-to ind))
  16520. (forward-line))))
  16521. (goto-char beg)
  16522. (forward-line lines)
  16523. (indent-line-to ind)))
  16524. (set-marker beg nil)
  16525. (set-marker end nil)))
  16526. ;;;; LaTeX fragments
  16527. (defun org-inside-LaTeX-fragment-p ()
  16528. "Test if point is inside a LaTeX fragment.
  16529. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  16530. sequence appearing also before point.
  16531. Even though the matchers for math are configurable, this function assumes
  16532. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  16533. delimiters are skipped when they have been removed by customization.
  16534. The return value is nil, or a cons cell with the delimiter and the
  16535. position of this delimiter.
  16536. This function does a reasonably good job, but can locally be fooled by
  16537. for example currency specifications. For example it will assume being in
  16538. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  16539. fragments that are properly closed, but during editing, we have to live
  16540. with the uncertainty caused by missing closing delimiters. This function
  16541. looks only before point, not after."
  16542. (catch 'exit
  16543. (let ((pos (point))
  16544. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  16545. (lim (save-excursion (org-backward-paragraph) (point)))
  16546. dd-on str (start 0) m re)
  16547. (goto-char pos)
  16548. (when dodollar
  16549. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  16550. re (nth 1 (assoc "$" org-latex-regexps)))
  16551. (while (string-match re str start)
  16552. (cond
  16553. ((= (match-end 0) (length str))
  16554. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  16555. ((= (match-end 0) (- (length str) 5))
  16556. (throw 'exit nil))
  16557. (t (setq start (match-end 0))))))
  16558. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  16559. (goto-char pos)
  16560. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  16561. (and (match-beginning 2) (throw 'exit nil))
  16562. ;; count $$
  16563. (while (re-search-backward "\\$\\$" lim t)
  16564. (setq dd-on (not dd-on)))
  16565. (goto-char pos)
  16566. (when dd-on (cons "$$" m))))))
  16567. (defun org-inside-latex-macro-p ()
  16568. "Is point inside a LaTeX macro or its arguments?"
  16569. (save-match-data
  16570. (org-in-regexp
  16571. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  16572. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  16573. "Build an overlay between BEG and END using IMAGE file.
  16574. Argument IMAGETYPE is the extension of the displayed image,
  16575. as a string. It defaults to \"png\"."
  16576. (let ((ov (make-overlay beg end))
  16577. (imagetype (or (intern imagetype) 'png)))
  16578. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  16579. (overlay-put ov 'evaporate t)
  16580. (overlay-put ov
  16581. 'modification-hooks
  16582. (list (lambda (o _flag _beg _end &optional _l)
  16583. (delete-overlay o))))
  16584. (overlay-put ov
  16585. 'display
  16586. (list 'image :type imagetype :file image :ascent 'center))))
  16587. (defun org--list-latex-overlays (&optional beg end)
  16588. "List all Org LaTeX overlays in current buffer.
  16589. Limit to overlays between BEG and END when those are provided."
  16590. (cl-remove-if-not
  16591. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  16592. (overlays-in (or beg (point-min)) (or end (point-max)))))
  16593. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  16594. "Remove all overlays with LaTeX fragment images in current buffer.
  16595. When optional arguments BEG and END are non-nil, remove all
  16596. overlays between them instead. Return a non-nil value when some
  16597. overlays were removed, nil otherwise."
  16598. (let ((overlays (org--list-latex-overlays beg end)))
  16599. (mapc #'delete-overlay overlays)
  16600. overlays))
  16601. (defun org-toggle-latex-fragment (&optional arg)
  16602. "Preview the LaTeX fragment at point, or all locally or globally.
  16603. If the cursor is on a LaTeX fragment, create the image and overlay
  16604. it over the source code, if there is none. Remove it otherwise.
  16605. If there is no fragment at point, display all fragments in the
  16606. current section.
  16607. With prefix ARG, preview or clear image for all fragments in the
  16608. current subtree or in the whole buffer when used before the first
  16609. headline. With a prefix ARG `\\[universal-argument] \
  16610. \\[universal-argument]' preview or clear images
  16611. for all fragments in the buffer."
  16612. (interactive "P")
  16613. (when (display-graphic-p)
  16614. (catch 'exit
  16615. (save-excursion
  16616. (let (beg end msg)
  16617. (cond
  16618. ((or (equal arg '(16))
  16619. (and (equal arg '(4))
  16620. (org-with-limited-levels (org-before-first-heading-p))))
  16621. (if (org-remove-latex-fragment-image-overlays)
  16622. (progn (message "LaTeX fragments images removed from buffer")
  16623. (throw 'exit nil))
  16624. (setq msg "Creating images for buffer...")))
  16625. ((equal arg '(4))
  16626. (org-with-limited-levels (org-back-to-heading t))
  16627. (setq beg (point))
  16628. (setq end (progn (org-end-of-subtree t) (point)))
  16629. (if (org-remove-latex-fragment-image-overlays beg end)
  16630. (progn
  16631. (message "LaTeX fragment images removed from subtree")
  16632. (throw 'exit nil))
  16633. (setq msg "Creating images for subtree...")))
  16634. ((let ((datum (org-element-context)))
  16635. (when (memq (org-element-type datum)
  16636. '(latex-environment latex-fragment))
  16637. (setq beg (org-element-property :begin datum))
  16638. (setq end (org-element-property :end datum))
  16639. (if (org-remove-latex-fragment-image-overlays beg end)
  16640. (progn (message "LaTeX fragment image removed")
  16641. (throw 'exit nil))
  16642. (setq msg "Creating image...")))))
  16643. (t
  16644. (org-with-limited-levels
  16645. (setq beg (if (org-at-heading-p) (line-beginning-position)
  16646. (outline-previous-heading)
  16647. (point)))
  16648. (setq end (progn (outline-next-heading) (point)))
  16649. (if (org-remove-latex-fragment-image-overlays beg end)
  16650. (progn
  16651. (message "LaTeX fragment images removed from section")
  16652. (throw 'exit nil))
  16653. (setq msg "Creating images for section...")))))
  16654. (let ((file (buffer-file-name (buffer-base-buffer))))
  16655. (org-format-latex
  16656. (concat org-preview-latex-image-directory "org-ltximg")
  16657. beg end
  16658. ;; Emacs cannot overlay images from remote hosts. Create
  16659. ;; it in `temporary-file-directory' instead.
  16660. (if (or (not file) (file-remote-p file))
  16661. temporary-file-directory
  16662. default-directory)
  16663. 'overlays msg 'forbuffer org-preview-latex-default-process))
  16664. (message (concat msg "done")))))))
  16665. (defun org-format-latex
  16666. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  16667. "Replace LaTeX fragments with links to an image.
  16668. The function takes care of creating the replacement image.
  16669. Only consider fragments between BEG and END when those are
  16670. provided.
  16671. When optional argument OVERLAYS is non-nil, display the image on
  16672. top of the fragment instead of replacing it.
  16673. PROCESSING-TYPE is the conversion method to use, as a symbol.
  16674. Some of the options can be changed using the variable
  16675. `org-format-latex-options', which see."
  16676. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  16677. (unless (eq processing-type 'verbatim)
  16678. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  16679. (cnt 0)
  16680. checkdir-flag)
  16681. (goto-char (or beg (point-min)))
  16682. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  16683. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  16684. (overlay-recenter (or end (point-max))))
  16685. (while (re-search-forward math-regexp end t)
  16686. (unless (and overlays
  16687. (eq (get-char-property (point) 'org-overlay-type)
  16688. 'org-latex-overlay))
  16689. (let* ((context (org-element-context))
  16690. (type (org-element-type context)))
  16691. (when (memq type '(latex-environment latex-fragment))
  16692. (let ((block-type (eq type 'latex-environment))
  16693. (value (org-element-property :value context))
  16694. (beg (org-element-property :begin context))
  16695. (end (save-excursion
  16696. (goto-char (org-element-property :end context))
  16697. (skip-chars-backward " \r\t\n")
  16698. (point))))
  16699. (cond
  16700. ((eq processing-type 'mathjax)
  16701. ;; Prepare for MathJax processing.
  16702. (if (not (string-match "\\`\\$\\$?" value))
  16703. (goto-char end)
  16704. (delete-region beg end)
  16705. (if (string= (match-string 0 value) "$$")
  16706. (insert "\\[" (substring value 2 -2) "\\]")
  16707. (insert "\\(" (substring value 1 -1) "\\)"))))
  16708. ((assq processing-type org-preview-latex-process-alist)
  16709. ;; Process to an image.
  16710. (cl-incf cnt)
  16711. (goto-char beg)
  16712. (let* ((processing-info
  16713. (cdr (assq processing-type org-preview-latex-process-alist)))
  16714. (face (face-at-point))
  16715. ;; Get the colors from the face at point.
  16716. (fg
  16717. (let ((color (plist-get org-format-latex-options
  16718. :foreground)))
  16719. (if (and forbuffer (eq color 'auto))
  16720. (face-attribute face :foreground nil 'default)
  16721. color)))
  16722. (bg
  16723. (let ((color (plist-get org-format-latex-options
  16724. :background)))
  16725. (if (and forbuffer (eq color 'auto))
  16726. (face-attribute face :background nil 'default)
  16727. color)))
  16728. (hash (sha1 (prin1-to-string
  16729. (list org-format-latex-header
  16730. org-latex-default-packages-alist
  16731. org-latex-packages-alist
  16732. org-format-latex-options
  16733. forbuffer value fg bg))))
  16734. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  16735. (absprefix (expand-file-name prefix dir))
  16736. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  16737. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  16738. (sep (and block-type "\n\n"))
  16739. (link (concat sep "[[file:" linkfile "]]" sep))
  16740. (options
  16741. (org-combine-plists
  16742. org-format-latex-options
  16743. `(:foreground ,fg :background ,bg))))
  16744. (when msg (message msg cnt))
  16745. (unless checkdir-flag ; Ensure the directory exists.
  16746. (setq checkdir-flag t)
  16747. (let ((todir (file-name-directory absprefix)))
  16748. (unless (file-directory-p todir)
  16749. (make-directory todir t))))
  16750. (unless (file-exists-p movefile)
  16751. (org-create-formula-image
  16752. value movefile options forbuffer processing-type))
  16753. (if overlays
  16754. (progn
  16755. (dolist (o (overlays-in beg end))
  16756. (when (eq (overlay-get o 'org-overlay-type)
  16757. 'org-latex-overlay)
  16758. (delete-overlay o)))
  16759. (org--format-latex-make-overlay beg end movefile imagetype)
  16760. (goto-char end))
  16761. (delete-region beg end)
  16762. (insert
  16763. (org-add-props link
  16764. (list 'org-latex-src
  16765. (replace-regexp-in-string "\"" "" value)
  16766. 'org-latex-src-embed-type
  16767. (if block-type 'paragraph 'character)))))))
  16768. ((eq processing-type 'mathml)
  16769. ;; Process to MathML.
  16770. (unless (org-format-latex-mathml-available-p)
  16771. (user-error "LaTeX to MathML converter not configured"))
  16772. (cl-incf cnt)
  16773. (when msg (message msg cnt))
  16774. (goto-char beg)
  16775. (delete-region beg end)
  16776. (insert (org-format-latex-as-mathml
  16777. value block-type prefix dir)))
  16778. (t
  16779. (error "Unknown conversion process %s for LaTeX fragments"
  16780. processing-type)))))))))))
  16781. (defun org-create-math-formula (latex-frag &optional mathml-file)
  16782. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  16783. Use `org-latex-to-mathml-convert-command'. If the conversion is
  16784. sucessful, return the portion between \"<math...> </math>\"
  16785. elements otherwise return nil. When MATHML-FILE is specified,
  16786. write the results in to that file. When invoked as an
  16787. interactive command, prompt for LATEX-FRAG, with initial value
  16788. set to the current active region and echo the results for user
  16789. inspection."
  16790. (interactive (list (let ((frag (when (org-region-active-p)
  16791. (buffer-substring-no-properties
  16792. (region-beginning) (region-end)))))
  16793. (read-string "LaTeX Fragment: " frag nil frag))))
  16794. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  16795. (let* ((tmp-in-file
  16796. (let ((file (file-relative-name
  16797. (make-temp-name (expand-file-name "ltxmathml-in")))))
  16798. (write-region latex-frag nil file)
  16799. file))
  16800. (tmp-out-file (file-relative-name
  16801. (make-temp-name (expand-file-name "ltxmathml-out"))))
  16802. (cmd (format-spec
  16803. org-latex-to-mathml-convert-command
  16804. `((?j . ,(and org-latex-to-mathml-jar-file
  16805. (shell-quote-argument
  16806. (expand-file-name
  16807. org-latex-to-mathml-jar-file))))
  16808. (?I . ,(shell-quote-argument tmp-in-file))
  16809. (?i . ,latex-frag)
  16810. (?o . ,(shell-quote-argument tmp-out-file)))))
  16811. mathml shell-command-output)
  16812. (when (called-interactively-p 'any)
  16813. (unless (org-format-latex-mathml-available-p)
  16814. (user-error "LaTeX to MathML converter not configured")))
  16815. (message "Running %s" cmd)
  16816. (setq shell-command-output (shell-command-to-string cmd))
  16817. (setq mathml
  16818. (when (file-readable-p tmp-out-file)
  16819. (with-current-buffer (find-file-noselect tmp-out-file t)
  16820. (goto-char (point-min))
  16821. (when (re-search-forward
  16822. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  16823. (regexp-quote
  16824. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  16825. nil t)
  16826. (prog1 (match-string 0) (kill-buffer))))))
  16827. (cond
  16828. (mathml
  16829. (setq mathml
  16830. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  16831. (when mathml-file
  16832. (write-region mathml nil mathml-file))
  16833. (when (called-interactively-p 'any)
  16834. (message mathml)))
  16835. ((message "LaTeX to MathML conversion failed")
  16836. (message shell-command-output)))
  16837. (delete-file tmp-in-file)
  16838. (when (file-exists-p tmp-out-file)
  16839. (delete-file tmp-out-file))
  16840. mathml))
  16841. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  16842. prefix &optional dir)
  16843. "Use `org-create-math-formula' but check local cache first."
  16844. (let* ((absprefix (expand-file-name prefix dir))
  16845. (print-length nil) (print-level nil)
  16846. (formula-id (concat
  16847. "formula-"
  16848. (sha1
  16849. (prin1-to-string
  16850. (list latex-frag
  16851. org-latex-to-mathml-convert-command)))))
  16852. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  16853. (formula-cache-dir (file-name-directory formula-cache)))
  16854. (unless (file-directory-p formula-cache-dir)
  16855. (make-directory formula-cache-dir t))
  16856. (unless (file-exists-p formula-cache)
  16857. (org-create-math-formula latex-frag formula-cache))
  16858. (if (file-exists-p formula-cache)
  16859. ;; Successful conversion. Return the link to MathML file.
  16860. (org-add-props
  16861. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  16862. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  16863. 'org-latex-src-embed-type (if latex-frag-type
  16864. 'paragraph 'character)))
  16865. ;; Failed conversion. Return the LaTeX fragment verbatim
  16866. latex-frag)))
  16867. (defun org--get-display-dpi ()
  16868. "Get the DPI of the display.
  16869. The function assumes that the display has the same pixel width in
  16870. the horizontal and vertical directions."
  16871. (if (display-graphic-p)
  16872. (round (/ (display-pixel-height)
  16873. (/ (display-mm-height) 25.4)))
  16874. (error "Attempt to calculate the dpi of a non-graphic display")))
  16875. (defun org-create-formula-image
  16876. (string tofile options buffer &optional processing-type)
  16877. "Create an image from LaTeX source using external processes.
  16878. The LaTeX STRING is saved to a temporary LaTeX file, then
  16879. converted to an image file by process PROCESSING-TYPE defined in
  16880. `org-preview-latex-process-alist'. A nil value defaults to
  16881. `org-preview-latex-default-process'.
  16882. The generated image file is eventually moved to TOFILE.
  16883. The OPTIONS argument controls the size, foreground color and
  16884. background color of the generated image.
  16885. When BUFFER non-nil, this function is used for LaTeX previewing.
  16886. Otherwise, it is used to deal with LaTeX snippets showed in
  16887. a HTML file."
  16888. (let* ((processing-type (or processing-type
  16889. org-preview-latex-default-process))
  16890. (processing-info
  16891. (cdr (assq processing-type org-preview-latex-process-alist)))
  16892. (programs (plist-get processing-info :programs))
  16893. (error-message (or (plist-get processing-info :message) ""))
  16894. (use-xcolor (plist-get processing-info :use-xcolor))
  16895. (image-input-type (plist-get processing-info :image-input-type))
  16896. (image-output-type (plist-get processing-info :image-output-type))
  16897. (post-clean (or (plist-get processing-info :post-clean)
  16898. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  16899. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  16900. (latex-header
  16901. (or (plist-get processing-info :latex-header)
  16902. (org-latex-make-preamble
  16903. (org-export-get-environment (org-export-get-backend 'latex))
  16904. org-format-latex-header
  16905. 'snippet)))
  16906. (latex-compiler (plist-get processing-info :latex-compiler))
  16907. (image-converter (plist-get processing-info :image-converter))
  16908. (tmpdir temporary-file-directory)
  16909. (texfilebase (make-temp-name
  16910. (expand-file-name "orgtex" tmpdir)))
  16911. (texfile (concat texfilebase ".tex"))
  16912. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  16913. '(1.0 . 1.0)))
  16914. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  16915. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  16916. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  16917. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  16918. "Black"))
  16919. (bg (or (plist-get options (if buffer :background :html-background))
  16920. "Transparent"))
  16921. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  16922. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  16923. (dolist (program programs)
  16924. (org-check-external-command program error-message))
  16925. (if use-xcolor
  16926. (progn (if (eq fg 'default)
  16927. (setq fg (org-latex-color :foreground))
  16928. (setq fg (org-latex-color-format fg)))
  16929. (if (eq bg 'default)
  16930. (setq bg (org-latex-color :background))
  16931. (setq bg (org-latex-color-format
  16932. (if (string= bg "Transparent") "white" bg))))
  16933. (with-temp-file texfile
  16934. (insert latex-header)
  16935. (insert "\n\\begin{document}\n"
  16936. "\\definecolor{fg}{rgb}{" fg "}\n"
  16937. "\\definecolor{bg}{rgb}{" bg "}\n"
  16938. "\n\\pagecolor{bg}\n"
  16939. "\n{\\color{fg}\n"
  16940. string
  16941. "\n}\n"
  16942. "\n\\end{document}\n")))
  16943. (if (eq fg 'default)
  16944. (setq fg (org-dvipng-color :foreground))
  16945. (unless (string= fg "Transparent")
  16946. (setq fg (org-dvipng-color-format fg))))
  16947. (if (eq bg 'default)
  16948. (setq bg (org-dvipng-color :background))
  16949. (unless (string= bg "Transparent")
  16950. (setq bg (org-dvipng-color-format bg))))
  16951. (with-temp-file texfile
  16952. (insert latex-header)
  16953. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  16954. (let* ((err-msg (format "Please adjust `%s' part of \
  16955. `org-preview-latex-process-alist'."
  16956. processing-type))
  16957. (image-input-file
  16958. (org-compile-file
  16959. texfile latex-compiler image-input-type err-msg log-buf))
  16960. (image-output-file
  16961. (org-compile-file
  16962. image-input-file image-converter image-output-type err-msg log-buf
  16963. `((?F . ,(shell-quote-argument fg))
  16964. (?B . ,(shell-quote-argument bg))
  16965. (?D . ,(shell-quote-argument (format "%s" dpi)))
  16966. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  16967. (copy-file image-output-file tofile 'replace)
  16968. (dolist (e post-clean)
  16969. (when (file-exists-p (concat texfilebase e))
  16970. (delete-file (concat texfilebase e))))
  16971. image-output-file)))
  16972. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  16973. "Fill a LaTeX header template TPL.
  16974. In the template, the following place holders will be recognized:
  16975. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  16976. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  16977. [PACKAGES] \\usepackage statements for PKG
  16978. [NO-PACKAGES] do not include PKG
  16979. [EXTRA] the string EXTRA
  16980. [NO-EXTRA] do not include EXTRA
  16981. For backward compatibility, if both the positive and the negative place
  16982. holder is missing, the positive one (without the \"NO-\") will be
  16983. assumed to be present at the end of the template.
  16984. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  16985. EXTRA is a string.
  16986. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  16987. (let (rpl (end ""))
  16988. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  16989. (setq rpl (if (or (match-end 1) (not def-pkg))
  16990. "" (org-latex-packages-to-string def-pkg snippets-p t))
  16991. tpl (replace-match rpl t t tpl))
  16992. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  16993. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  16994. (setq rpl (if (or (match-end 1) (not pkg))
  16995. "" (org-latex-packages-to-string pkg snippets-p t))
  16996. tpl (replace-match rpl t t tpl))
  16997. (when pkg (setq end
  16998. (concat end "\n"
  16999. (org-latex-packages-to-string pkg snippets-p)))))
  17000. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17001. (setq rpl (if (or (match-end 1) (not extra))
  17002. "" (concat extra "\n"))
  17003. tpl (replace-match rpl t t tpl))
  17004. (when (and extra (string-match "\\S-" extra))
  17005. (setq end (concat end "\n" extra))))
  17006. (if (string-match "\\S-" end)
  17007. (concat tpl "\n" end)
  17008. tpl)))
  17009. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17010. "Turn an alist of packages into a string with the \\usepackage macros."
  17011. (setq pkg (mapconcat (lambda(p)
  17012. (cond
  17013. ((stringp p) p)
  17014. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17015. (format "%% Package %s omitted" (cadr p)))
  17016. ((equal "" (car p))
  17017. (format "\\usepackage{%s}" (cadr p)))
  17018. (t
  17019. (format "\\usepackage[%s]{%s}"
  17020. (car p) (cadr p)))))
  17021. pkg
  17022. "\n"))
  17023. (if newline (concat pkg "\n") pkg))
  17024. (defun org-dvipng-color (attr)
  17025. "Return a RGB color specification for dvipng."
  17026. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17027. (defun org-dvipng-color-format (color-name)
  17028. "Convert COLOR-NAME to a RGB color value for dvipng."
  17029. (apply #'format "rgb %s %s %s"
  17030. (mapcar 'org-normalize-color
  17031. (color-values color-name))))
  17032. (defun org-latex-color (attr)
  17033. "Return a RGB color for the LaTeX color package."
  17034. (org-latex-color-format (face-attribute 'default attr nil)))
  17035. (defun org-latex-color-format (color-name)
  17036. "Convert COLOR-NAME to a RGB color value."
  17037. (apply #'format "%s,%s,%s"
  17038. (mapcar 'org-normalize-color
  17039. (color-values color-name))))
  17040. (defun org-normalize-color (value)
  17041. "Return string to be used as color value for an RGB component."
  17042. (format "%g" (/ value 65535.0)))
  17043. ;; Image display
  17044. (defvar-local org-inline-image-overlays nil)
  17045. (defun org-toggle-inline-images (&optional include-linked)
  17046. "Toggle the display of inline images.
  17047. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17048. (interactive "P")
  17049. (if org-inline-image-overlays
  17050. (progn
  17051. (org-remove-inline-images)
  17052. (when (called-interactively-p 'interactive)
  17053. (message "Inline image display turned off")))
  17054. (org-display-inline-images include-linked)
  17055. (when (called-interactively-p 'interactive)
  17056. (message (if org-inline-image-overlays
  17057. (format "%d images displayed inline"
  17058. (length org-inline-image-overlays))
  17059. "No images to display inline")))))
  17060. (defun org-redisplay-inline-images ()
  17061. "Refresh the display of inline images."
  17062. (interactive)
  17063. (if (not org-inline-image-overlays)
  17064. (org-toggle-inline-images)
  17065. (org-toggle-inline-images)
  17066. (org-toggle-inline-images)))
  17067. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17068. "Display inline images.
  17069. An inline image is a link which follows either of these
  17070. conventions:
  17071. 1. Its path is a file with an extension matching return value
  17072. from `image-file-name-regexp' and it has no contents.
  17073. 2. Its description consists in a single link of the previous
  17074. type.
  17075. When optional argument INCLUDE-LINKED is non-nil, also links with
  17076. a text description part will be inlined. This can be nice for
  17077. a quick look at those images, but it does not reflect what
  17078. exported files will look like.
  17079. When optional argument REFRESH is non-nil, refresh existing
  17080. images between BEG and END. This will create new image displays
  17081. only if necessary. BEG and END default to the buffer
  17082. boundaries."
  17083. (interactive "P")
  17084. (when (display-graphic-p)
  17085. (unless refresh
  17086. (org-remove-inline-images)
  17087. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17088. (org-with-wide-buffer
  17089. (goto-char (or beg (point-min)))
  17090. (let* ((case-fold-search t)
  17091. (file-extension-re (image-file-name-regexp))
  17092. (link-abbrevs (mapcar #'car
  17093. (append org-link-abbrev-alist-local
  17094. org-link-abbrev-alist)))
  17095. ;; Check absolute, relative file names and explicit
  17096. ;; "file:" links. Also check link abbreviations since
  17097. ;; some might expand to "file" links.
  17098. (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
  17099. (if (not link-abbrevs) ""
  17100. (format "\\|\\(?:%s:\\)"
  17101. (regexp-opt link-abbrevs))))))
  17102. (while (re-search-forward file-types-re end t)
  17103. (let ((link (save-match-data (org-element-context))))
  17104. ;; Check if we're at an inline image, i.e., an image file
  17105. ;; link without a description (unless INCLUDE-LINKED is
  17106. ;; non-nil).
  17107. (when (and (equal "file" (org-element-property :type link))
  17108. (or include-linked
  17109. (null (org-element-contents link)))
  17110. (string-match-p file-extension-re
  17111. (org-element-property :path link)))
  17112. (let ((file (expand-file-name
  17113. (org-link-unescape
  17114. (org-element-property :path link)))))
  17115. (when (file-exists-p file)
  17116. (let ((width
  17117. ;; Apply `org-image-actual-width' specifications.
  17118. (cond
  17119. ((not (image-type-available-p 'imagemagick)) nil)
  17120. ((eq org-image-actual-width t) nil)
  17121. ((listp org-image-actual-width)
  17122. (or
  17123. ;; First try to find a width among
  17124. ;; attributes associated to the paragraph
  17125. ;; containing link.
  17126. (let ((paragraph
  17127. (let ((e link))
  17128. (while (and (setq e (org-element-property
  17129. :parent e))
  17130. (not (eq (org-element-type e)
  17131. 'paragraph))))
  17132. e)))
  17133. (when paragraph
  17134. (save-excursion
  17135. (goto-char (org-element-property :begin paragraph))
  17136. (when
  17137. (re-search-forward
  17138. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17139. (org-element-property
  17140. :post-affiliated paragraph)
  17141. t)
  17142. (string-to-number (match-string 1))))))
  17143. ;; Otherwise, fall-back to provided number.
  17144. (car org-image-actual-width)))
  17145. ((numberp org-image-actual-width)
  17146. org-image-actual-width)))
  17147. (old (get-char-property-and-overlay
  17148. (org-element-property :begin link)
  17149. 'org-image-overlay)))
  17150. (if (and (car-safe old) refresh)
  17151. (image-refresh (overlay-get (cdr old) 'display))
  17152. (let ((image (create-image file
  17153. (and width 'imagemagick)
  17154. nil
  17155. :width width)))
  17156. (when image
  17157. (let ((ov (make-overlay
  17158. (org-element-property :begin link)
  17159. (progn
  17160. (goto-char
  17161. (org-element-property :end link))
  17162. (skip-chars-backward " \t")
  17163. (point)))))
  17164. (overlay-put ov 'display image)
  17165. (overlay-put ov 'face 'default)
  17166. (overlay-put ov 'org-image-overlay t)
  17167. (overlay-put
  17168. ov 'modification-hooks
  17169. (list 'org-display-inline-remove-overlay))
  17170. (push ov org-inline-image-overlays)))))))))))))))
  17171. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17172. "Remove inline-display overlay if a corresponding region is modified."
  17173. (let ((inhibit-modification-hooks t))
  17174. (when (and ov after)
  17175. (delete ov org-inline-image-overlays)
  17176. (delete-overlay ov))))
  17177. (defun org-remove-inline-images ()
  17178. "Remove inline display of images."
  17179. (interactive)
  17180. (mapc #'delete-overlay org-inline-image-overlays)
  17181. (setq org-inline-image-overlays nil))
  17182. ;;; Key bindings
  17183. (defun org-remap (map &rest commands)
  17184. "In MAP, remap the functions given in COMMANDS.
  17185. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  17186. (let (new old)
  17187. (while commands
  17188. (setq old (pop commands) new (pop commands))
  17189. (org-defkey map (vector 'remap old) new))))
  17190. ;;;; Outline functions that can be remapped in Org
  17191. (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
  17192. (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
  17193. (define-key org-mode-map [remap outline-forward-same-level]
  17194. #'org-forward-heading-same-level)
  17195. (define-key org-mode-map [remap outline-backward-same-level]
  17196. #'org-backward-heading-same-level)
  17197. (define-key org-mode-map [remap outline-show-branches]
  17198. #'org-kill-note-or-show-branches)
  17199. (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
  17200. (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
  17201. (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
  17202. (define-key org-mode-map [remap outline-next-visible-heading]
  17203. #'org-next-visible-heading)
  17204. (define-key org-mode-map [remap outline-previous-visible-heading]
  17205. #'org-previous-visible-heading)
  17206. (define-key org-mode-map [remap show-children] #'org-show-children)
  17207. ;;;; Make `C-c C-x' a prefix key
  17208. (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
  17209. ;;;; TAB key with modifiers
  17210. (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
  17211. (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
  17212. (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
  17213. (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
  17214. (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
  17215. (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
  17216. (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
  17217. (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
  17218. ;;;; RET key with modifiers
  17219. (org-defkey org-mode-map (kbd "S-<return>") #'org-table-copy-down)
  17220. (org-defkey org-mode-map (kbd "M-S-<return>") #'org-insert-todo-heading)
  17221. (org-defkey org-mode-map (kbd "ESC S-<return>") #'org-insert-todo-heading)
  17222. (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
  17223. (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
  17224. ;;;; Cursor keys with modifiers
  17225. (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
  17226. (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
  17227. (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
  17228. (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
  17229. (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
  17230. (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
  17231. (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
  17232. (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
  17233. (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
  17234. (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
  17235. (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
  17236. (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
  17237. (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
  17238. (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
  17239. (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
  17240. (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
  17241. (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
  17242. (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
  17243. (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
  17244. (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
  17245. (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
  17246. (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
  17247. (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
  17248. (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
  17249. (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
  17250. ;;;; Babel keys
  17251. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  17252. (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
  17253. (define-key org-babel-map key def))
  17254. ;;;; Extra keys for TTY access.
  17255. ;; We only set them when really needed because otherwise the
  17256. ;; menus don't show the simple keys
  17257. (when (or org-use-extra-keys (not window-system))
  17258. (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
  17259. (org-defkey org-mode-map (kbd "C-c C-x m") #'org-meta-return)
  17260. (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
  17261. (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
  17262. (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
  17263. (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
  17264. (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
  17265. (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
  17266. (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
  17267. (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
  17268. (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
  17269. (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
  17270. (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
  17271. (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
  17272. (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
  17273. (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
  17274. (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
  17275. (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
  17276. (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
  17277. (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
  17278. (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
  17279. ;;;; Narrow map
  17280. (org-defkey narrow-map "s" #'org-narrow-to-subtree)
  17281. (org-defkey narrow-map "b" #'org-narrow-to-block)
  17282. (org-defkey narrow-map "e" #'org-narrow-to-element)
  17283. ;;;; Remap usual Emacs bindings
  17284. (org-remap org-mode-map
  17285. 'self-insert-command 'org-self-insert-command
  17286. 'delete-char 'org-delete-char
  17287. 'delete-backward-char 'org-delete-backward-char
  17288. 'kill-line 'org-kill-line
  17289. 'open-line 'org-open-line
  17290. 'yank 'org-yank
  17291. 'comment-dwim 'org-comment-dwim
  17292. 'move-beginning-of-line 'org-beginning-of-line
  17293. 'move-end-of-line 'org-end-of-line
  17294. 'forward-paragraph 'org-forward-paragraph
  17295. 'backward-paragraph 'org-backward-paragraph
  17296. 'backward-sentence 'org-backward-sentence
  17297. 'forward-sentence 'org-forward-sentence
  17298. 'fill-paragraph 'org-fill-paragraph
  17299. 'delete-indentation 'org-delete-indentation
  17300. 'transpose-words 'org-transpose-words)
  17301. ;;;; All the other keys
  17302. (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
  17303. (org-defkey org-mode-map (kbd "C-c C-a") #'org-show-all)
  17304. (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
  17305. (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
  17306. (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
  17307. (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
  17308. (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
  17309. (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
  17310. (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
  17311. (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
  17312. (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
  17313. (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
  17314. (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
  17315. (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
  17316. (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
  17317. (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
  17318. (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
  17319. (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
  17320. (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
  17321. (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
  17322. (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
  17323. (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
  17324. (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
  17325. (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
  17326. (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
  17327. (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
  17328. (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
  17329. (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
  17330. (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
  17331. (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
  17332. (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
  17333. (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
  17334. (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
  17335. (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
  17336. (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
  17337. (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
  17338. (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
  17339. (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
  17340. (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
  17341. (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
  17342. (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
  17343. (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
  17344. (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
  17345. (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
  17346. (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
  17347. (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
  17348. (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
  17349. (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
  17350. (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
  17351. (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
  17352. (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
  17353. (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
  17354. (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
  17355. (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
  17356. (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
  17357. (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
  17358. (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
  17359. (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
  17360. (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
  17361. (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
  17362. (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
  17363. (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
  17364. (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
  17365. (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
  17366. (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
  17367. (org-defkey org-mode-map (kbd "RET") #'org-return)
  17368. (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
  17369. (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
  17370. (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
  17371. (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
  17372. (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
  17373. (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
  17374. (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
  17375. (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
  17376. (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
  17377. (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
  17378. (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
  17379. (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
  17380. (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
  17381. (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
  17382. (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
  17383. (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
  17384. (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
  17385. (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
  17386. (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
  17387. (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
  17388. (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
  17389. (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
  17390. (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
  17391. (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
  17392. (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
  17393. (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
  17394. (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
  17395. (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
  17396. (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
  17397. (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
  17398. (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
  17399. (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
  17400. (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
  17401. (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
  17402. (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
  17403. (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
  17404. (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
  17405. (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
  17406. (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
  17407. (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
  17408. (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
  17409. (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
  17410. (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
  17411. (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
  17412. (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
  17413. (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
  17414. (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
  17415. (org-defkey org-mode-map (kbd "C-c C-,") #'org-insert-structure-template)
  17416. (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
  17417. (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
  17418. (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
  17419. (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
  17420. (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
  17421. (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
  17422. (define-key org-mode-map (kbd "C-c C-x C-c") #'org-columns)
  17423. (define-key org-mode-map (kbd "C-c C-x !") #'org-reload)
  17424. (define-key org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
  17425. (define-key org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
  17426. (define-key org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
  17427. ;;; Speed commands
  17428. (defconst org-speed-commands-default
  17429. '(
  17430. ("Outline Navigation")
  17431. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  17432. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  17433. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  17434. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  17435. ("F" . org-next-block)
  17436. ("B" . org-previous-block)
  17437. ("u" . (org-speed-move-safe 'outline-up-heading))
  17438. ("j" . org-goto)
  17439. ("g" . (org-refile t))
  17440. ("Outline Visibility")
  17441. ("c" . org-cycle)
  17442. ("C" . org-shifttab)
  17443. (" " . org-display-outline-path)
  17444. ("s" . org-narrow-to-subtree)
  17445. ("=" . org-columns)
  17446. ("Outline Structure Editing")
  17447. ("U" . org-metaup)
  17448. ("D" . org-metadown)
  17449. ("r" . org-metaright)
  17450. ("l" . org-metaleft)
  17451. ("R" . org-shiftmetaright)
  17452. ("L" . org-shiftmetaleft)
  17453. ("i" . (progn (forward-char 1) (call-interactively
  17454. 'org-insert-heading-respect-content)))
  17455. ("^" . org-sort)
  17456. ("w" . org-refile)
  17457. ("a" . org-archive-subtree-default-with-confirmation)
  17458. ("@" . org-mark-subtree)
  17459. ("#" . org-toggle-comment)
  17460. ("Clock Commands")
  17461. ("I" . org-clock-in)
  17462. ("O" . org-clock-out)
  17463. ("Meta Data Editing")
  17464. ("t" . org-todo)
  17465. ("," . (org-priority))
  17466. ("0" . (org-priority ?\ ))
  17467. ("1" . (org-priority ?A))
  17468. ("2" . (org-priority ?B))
  17469. ("3" . (org-priority ?C))
  17470. (":" . org-set-tags-command)
  17471. ("e" . org-set-effort)
  17472. ("E" . org-inc-effort)
  17473. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  17474. (org-entry-put (point) "APPT_WARNTIME" m)))
  17475. ("Agenda Views etc")
  17476. ("v" . org-agenda)
  17477. ("/" . org-sparse-tree)
  17478. ("Misc")
  17479. ("o" . org-open-at-point)
  17480. ("?" . org-speed-command-help)
  17481. ("<" . (org-agenda-set-restriction-lock 'subtree))
  17482. (">" . (org-agenda-remove-restriction-lock))
  17483. )
  17484. "The default speed commands.")
  17485. (defun org-print-speed-command (e)
  17486. (if (> (length (car e)) 1)
  17487. (progn
  17488. (princ "\n")
  17489. (princ (car e))
  17490. (princ "\n")
  17491. (princ (make-string (length (car e)) ?-))
  17492. (princ "\n"))
  17493. (princ (car e))
  17494. (princ " ")
  17495. (if (symbolp (cdr e))
  17496. (princ (symbol-name (cdr e)))
  17497. (prin1 (cdr e)))
  17498. (princ "\n")))
  17499. (defun org-speed-command-help ()
  17500. "Show the available speed commands."
  17501. (interactive)
  17502. (if (not org-use-speed-commands)
  17503. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  17504. (with-output-to-temp-buffer "*Help*"
  17505. (princ "User-defined Speed commands\n===========================\n")
  17506. (mapc #'org-print-speed-command org-speed-commands-user)
  17507. (princ "\n")
  17508. (princ "Built-in Speed commands\n=======================\n")
  17509. (mapc #'org-print-speed-command org-speed-commands-default))
  17510. (with-current-buffer "*Help*"
  17511. (setq truncate-lines t))))
  17512. (defun org-speed-move-safe (cmd)
  17513. "Execute CMD, but make sure that the cursor always ends up in a headline.
  17514. If not, return to the original position and throw an error."
  17515. (interactive)
  17516. (let ((pos (point)))
  17517. (call-interactively cmd)
  17518. (unless (and (bolp) (org-at-heading-p))
  17519. (goto-char pos)
  17520. (error "Boundary reached while executing %s" cmd))))
  17521. (defvar org-self-insert-command-undo-counter 0)
  17522. (defvar org-table-auto-blank-field) ; defined in org-table.el
  17523. (defvar org-speed-command nil)
  17524. (defun org-speed-command-activate (keys)
  17525. "Hook for activating single-letter speed commands.
  17526. `org-speed-commands-default' specifies a minimal command set.
  17527. Use `org-speed-commands-user' for further customization."
  17528. (when (or (and (bolp) (looking-at org-outline-regexp))
  17529. (and (functionp org-use-speed-commands)
  17530. (funcall org-use-speed-commands)))
  17531. (cdr (assoc keys (append org-speed-commands-user
  17532. org-speed-commands-default)))))
  17533. (defun org-babel-speed-command-activate (keys)
  17534. "Hook for activating single-letter code block commands."
  17535. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  17536. (cdr (assoc keys org-babel-key-bindings))))
  17537. (defcustom org-speed-command-hook
  17538. '(org-speed-command-activate org-babel-speed-command-activate)
  17539. "Hook for activating speed commands at strategic locations.
  17540. Hook functions are called in sequence until a valid handler is
  17541. found.
  17542. Each hook takes a single argument, a user-pressed command key
  17543. which is also a `self-insert-command' from the global map.
  17544. Within the hook, examine the cursor position and the command key
  17545. and return nil or a valid handler as appropriate. Handler could
  17546. be one of an interactive command, a function, or a form.
  17547. Set `org-use-speed-commands' to non-nil value to enable this
  17548. hook. The default setting is `org-speed-command-activate'."
  17549. :group 'org-structure
  17550. :version "24.1"
  17551. :type 'hook)
  17552. (defun org-self-insert-command (N)
  17553. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  17554. If the cursor is in a table looking at whitespace, the whitespace is
  17555. overwritten, and the table is not marked as requiring realignment."
  17556. (interactive "p")
  17557. (org-check-before-invisible-edit 'insert)
  17558. (cond
  17559. ((and org-use-speed-commands
  17560. (let ((kv (this-command-keys-vector)))
  17561. (setq org-speed-command
  17562. (run-hook-with-args-until-success
  17563. 'org-speed-command-hook
  17564. (make-string 1 (aref kv (1- (length kv))))))))
  17565. (cond
  17566. ((commandp org-speed-command)
  17567. (setq this-command org-speed-command)
  17568. (call-interactively org-speed-command))
  17569. ((functionp org-speed-command)
  17570. (funcall org-speed-command))
  17571. ((and org-speed-command (listp org-speed-command))
  17572. (eval org-speed-command))
  17573. (t (let (org-use-speed-commands)
  17574. (call-interactively 'org-self-insert-command)))))
  17575. ((and
  17576. (= N 1)
  17577. (not (org-region-active-p))
  17578. (org-at-table-p)
  17579. (progn
  17580. ;; Check if we blank the field, and if that triggers align.
  17581. (and (featurep 'org-table)
  17582. org-table-auto-blank-field
  17583. (memq last-command
  17584. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  17585. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  17586. ;; Got extra space, this field does not determine
  17587. ;; column width.
  17588. (let (org-table-may-need-update) (org-table-blank-field))
  17589. ;; No extra space, this field may determine column
  17590. ;; width.
  17591. (org-table-blank-field)))
  17592. t)
  17593. (looking-at "[^|\n]* |"))
  17594. ;; There is room for insertion without re-aligning the table.
  17595. (self-insert-command N)
  17596. (org-table-with-shrunk-field
  17597. (save-excursion
  17598. (skip-chars-forward "^|")
  17599. ;; Do not delete last space, which is
  17600. ;; `org-table-separator-space', but the regular space before
  17601. ;; it.
  17602. (delete-region (- (point) 2) (1- (point))))))
  17603. (t
  17604. (setq org-table-may-need-update t)
  17605. (self-insert-command N)
  17606. (org-fix-tags-on-the-fly)
  17607. (when org-self-insert-cluster-for-undo
  17608. (if (not (eq last-command 'org-self-insert-command))
  17609. (setq org-self-insert-command-undo-counter 1)
  17610. (if (>= org-self-insert-command-undo-counter 20)
  17611. (setq org-self-insert-command-undo-counter 1)
  17612. (and (> org-self-insert-command-undo-counter 0)
  17613. buffer-undo-list (listp buffer-undo-list)
  17614. (not (cadr buffer-undo-list)) ; remove nil entry
  17615. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  17616. (setq org-self-insert-command-undo-counter
  17617. (1+ org-self-insert-command-undo-counter))))))))
  17618. (defun org-check-before-invisible-edit (kind)
  17619. "Check is editing if kind KIND would be dangerous with invisible text around.
  17620. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  17621. ;; First, try to get out of here as quickly as possible, to reduce overhead
  17622. (when (and org-catch-invisible-edits
  17623. (or (not (boundp 'visible-mode)) (not visible-mode))
  17624. (or (get-char-property (point) 'invisible)
  17625. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  17626. ;; OK, we need to take a closer look. Do not consider
  17627. ;; invisibility obtained through text properties (e.g., link
  17628. ;; fontification), as it cannot be toggled.
  17629. (let* ((invisible-at-point
  17630. (pcase (get-char-property-and-overlay (point) 'invisible)
  17631. (`(,_ . ,(and (pred overlayp) o)) o)))
  17632. ;; Assume that point cannot land in the middle of an
  17633. ;; overlay, or between two overlays.
  17634. (invisible-before-point
  17635. (and (not invisible-at-point)
  17636. (not (bobp))
  17637. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  17638. (`(,_ . ,(and (pred overlayp) o)) o))))
  17639. (border-and-ok-direction
  17640. (or
  17641. ;; Check if we are acting predictably before invisible
  17642. ;; text.
  17643. (and invisible-at-point
  17644. (memq kind '(insert delete-backward)))
  17645. ;; Check if we are acting predictably after invisible text
  17646. ;; This works not well, and I have turned it off. It seems
  17647. ;; better to always show and stop after invisible text.
  17648. ;; (and (not invisible-at-point) invisible-before-point
  17649. ;; (memq kind '(insert delete)))
  17650. )))
  17651. (when (or invisible-at-point invisible-before-point)
  17652. (when (eq org-catch-invisible-edits 'error)
  17653. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  17654. (if (and org-custom-properties-overlays
  17655. (y-or-n-p "Display invisible properties in this buffer? "))
  17656. (org-toggle-custom-properties-visibility)
  17657. ;; Make the area visible
  17658. (save-excursion
  17659. (when invisible-before-point
  17660. (goto-char
  17661. (previous-single-char-property-change (point) 'invisible)))
  17662. ;; Remove whatever overlay is currently making yet-to-be
  17663. ;; edited text invisible. Also remove nested invisibility
  17664. ;; related overlays.
  17665. (delete-overlay (or invisible-at-point invisible-before-point))
  17666. (let ((origin (if invisible-at-point (point) (1- (point)))))
  17667. (while (pcase (get-char-property-and-overlay origin 'invisible)
  17668. (`(,_ . ,(and (pred overlayp) o))
  17669. (delete-overlay o)
  17670. t)))))
  17671. (cond
  17672. ((eq org-catch-invisible-edits 'show)
  17673. ;; That's it, we do the edit after showing
  17674. (message
  17675. "Unfolding invisible region around point before editing")
  17676. (sit-for 1))
  17677. ((and (eq org-catch-invisible-edits 'smart)
  17678. border-and-ok-direction)
  17679. (message "Unfolding invisible region around point before editing"))
  17680. (t
  17681. ;; Don't do the edit, make the user repeat it in full visibility
  17682. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  17683. (defun org-fix-tags-on-the-fly ()
  17684. "Align tags in headline at point.
  17685. Unlike to `org-set-tags', it ignores region and sorting."
  17686. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  17687. (org-at-heading-p))
  17688. (let ((org-ignore-region t)
  17689. (org-tags-sort-function nil))
  17690. (org-set-tags nil t))))
  17691. (defun org-delete-backward-char (N)
  17692. "Like `delete-backward-char', insert whitespace at field end in tables.
  17693. When deleting backwards, in tables this function will insert whitespace in
  17694. front of the next \"|\" separator, to keep the table aligned. The table will
  17695. still be marked for re-alignment if the field did fill the entire column,
  17696. because, in this case the deletion might narrow the column."
  17697. (interactive "p")
  17698. (save-match-data
  17699. (org-check-before-invisible-edit 'delete-backward)
  17700. (if (and (= N 1)
  17701. (not overwrite-mode)
  17702. (not (org-region-active-p))
  17703. (not (eq (char-before) ?|))
  17704. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  17705. (looking-at-p ".*?|")
  17706. (org-at-table-p))
  17707. (progn (forward-char -1) (org-delete-char 1))
  17708. (backward-delete-char N)
  17709. (org-fix-tags-on-the-fly))))
  17710. (defun org-delete-char (N)
  17711. "Like `delete-char', but insert whitespace at field end in tables.
  17712. When deleting characters, in tables this function will insert whitespace in
  17713. front of the next \"|\" separator, to keep the table aligned. The table will
  17714. still be marked for re-alignment if the field did fill the entire column,
  17715. because, in this case the deletion might narrow the column."
  17716. (interactive "p")
  17717. (save-match-data
  17718. (org-check-before-invisible-edit 'delete)
  17719. (cond
  17720. ((or (/= N 1)
  17721. (eq (char-after) ?|)
  17722. (save-excursion (skip-chars-backward " \t") (bolp))
  17723. (not (org-at-table-p)))
  17724. (delete-char N)
  17725. (org-fix-tags-on-the-fly))
  17726. ((looking-at ".\\(.*?\\)|")
  17727. (let* ((update? org-table-may-need-update)
  17728. (noalign (looking-at-p ".*? |")))
  17729. (delete-char 1)
  17730. (org-table-with-shrunk-field
  17731. (save-excursion
  17732. ;; Last space is `org-table-separator-space', so insert
  17733. ;; a regular one before it instead.
  17734. (goto-char (- (match-end 0) 2))
  17735. (insert " ")))
  17736. ;; If there were two spaces at the end, this field does not
  17737. ;; determine the width of the column.
  17738. (when noalign (setq org-table-may-need-update update?))))
  17739. (t
  17740. (delete-char N)))))
  17741. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  17742. (put 'org-self-insert-command 'delete-selection
  17743. (lambda ()
  17744. (not (run-hook-with-args-until-success
  17745. 'self-insert-uses-region-functions))))
  17746. (put 'orgtbl-self-insert-command 'delete-selection
  17747. (lambda ()
  17748. (not (run-hook-with-args-until-success
  17749. 'self-insert-uses-region-functions))))
  17750. (put 'org-delete-char 'delete-selection 'supersede)
  17751. (put 'org-delete-backward-char 'delete-selection 'supersede)
  17752. (put 'org-yank 'delete-selection 'yank)
  17753. ;; Make `flyspell-mode' delay after some commands
  17754. (put 'org-self-insert-command 'flyspell-delayed t)
  17755. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  17756. (put 'org-delete-char 'flyspell-delayed t)
  17757. (put 'org-delete-backward-char 'flyspell-delayed t)
  17758. ;; Make pabbrev-mode expand after Org mode commands
  17759. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  17760. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  17761. (defun org-transpose-words ()
  17762. "Transpose words for Org.
  17763. This uses the `org-mode-transpose-word-syntax-table' syntax
  17764. table, which interprets characters in `org-emphasis-alist' as
  17765. word constituents."
  17766. (interactive)
  17767. (with-syntax-table org-mode-transpose-word-syntax-table
  17768. (call-interactively 'transpose-words)))
  17769. (defvar org-ctrl-c-ctrl-c-hook nil
  17770. "Hook for functions attaching themselves to `C-c C-c'.
  17771. This can be used to add additional functionality to the C-c C-c
  17772. key which executes context-dependent commands. This hook is run
  17773. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  17774. run after the last test.
  17775. Each function will be called with no arguments. The function
  17776. must check if the context is appropriate for it to act. If yes,
  17777. it should do its thing and then return a non-nil value. If the
  17778. context is wrong, just do nothing and return nil.")
  17779. (defvar org-ctrl-c-ctrl-c-final-hook nil
  17780. "Hook for functions attaching themselves to `C-c C-c'.
  17781. This can be used to add additional functionality to the C-c C-c
  17782. key which executes context-dependent commands. This hook is run
  17783. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  17784. before the first test.
  17785. Each function will be called with no arguments. The function
  17786. must check if the context is appropriate for it to act. If yes,
  17787. it should do its thing and then return a non-nil value. If the
  17788. context is wrong, just do nothing and return nil.")
  17789. (defvar org-tab-first-hook nil
  17790. "Hook for functions to attach themselves to TAB.
  17791. See `org-ctrl-c-ctrl-c-hook' for more information.
  17792. This hook runs as the first action when TAB is pressed, even before
  17793. `org-cycle' messes around with the `outline-regexp' to cater for
  17794. inline tasks and plain list item folding.
  17795. If any function in this hook returns t, any other actions that
  17796. would have been caused by TAB (such as table field motion or visibility
  17797. cycling) will not occur.")
  17798. (defvar org-tab-after-check-for-table-hook nil
  17799. "Hook for functions to attach themselves to TAB.
  17800. See `org-ctrl-c-ctrl-c-hook' for more information.
  17801. This hook runs after it has been established that the cursor is not in a
  17802. table, but before checking if the cursor is in a headline or if global cycling
  17803. should be done.
  17804. If any function in this hook returns t, not other actions like visibility
  17805. cycling will be done.")
  17806. (defvar org-tab-after-check-for-cycling-hook nil
  17807. "Hook for functions to attach themselves to TAB.
  17808. See `org-ctrl-c-ctrl-c-hook' for more information.
  17809. This hook runs after it has been established that not table field motion and
  17810. not visibility should be done because of current context. This is probably
  17811. the place where a package like yasnippets can hook in.")
  17812. (defvar org-tab-before-tab-emulation-hook nil
  17813. "Hook for functions to attach themselves to TAB.
  17814. See `org-ctrl-c-ctrl-c-hook' for more information.
  17815. This hook runs after every other options for TAB have been exhausted, but
  17816. before indentation and \t insertion takes place.")
  17817. (defvar org-metaleft-hook nil
  17818. "Hook for functions attaching themselves to `M-left'.
  17819. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17820. (defvar org-metaright-hook nil
  17821. "Hook for functions attaching themselves to `M-right'.
  17822. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17823. (defvar org-metaup-hook nil
  17824. "Hook for functions attaching themselves to `M-up'.
  17825. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17826. (defvar org-metadown-hook nil
  17827. "Hook for functions attaching themselves to `M-down'.
  17828. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17829. (defvar org-shiftmetaleft-hook nil
  17830. "Hook for functions attaching themselves to `M-S-left'.
  17831. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17832. (defvar org-shiftmetaright-hook nil
  17833. "Hook for functions attaching themselves to `M-S-right'.
  17834. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17835. (defvar org-shiftmetaup-hook nil
  17836. "Hook for functions attaching themselves to `M-S-up'.
  17837. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17838. (defvar org-shiftmetadown-hook nil
  17839. "Hook for functions attaching themselves to `M-S-down'.
  17840. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17841. (defvar org-metareturn-hook nil
  17842. "Hook for functions attaching themselves to `M-RET'.
  17843. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17844. (defvar org-shiftup-hook nil
  17845. "Hook for functions attaching themselves to `S-up'.
  17846. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17847. (defvar org-shiftup-final-hook nil
  17848. "Hook for functions attaching themselves to `S-up'.
  17849. This one runs after all other options except shift-select have been excluded.
  17850. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17851. (defvar org-shiftdown-hook nil
  17852. "Hook for functions attaching themselves to `S-down'.
  17853. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17854. (defvar org-shiftdown-final-hook nil
  17855. "Hook for functions attaching themselves to `S-down'.
  17856. This one runs after all other options except shift-select have been excluded.
  17857. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17858. (defvar org-shiftleft-hook nil
  17859. "Hook for functions attaching themselves to `S-left'.
  17860. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17861. (defvar org-shiftleft-final-hook nil
  17862. "Hook for functions attaching themselves to `S-left'.
  17863. This one runs after all other options except shift-select have been excluded.
  17864. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17865. (defvar org-shiftright-hook nil
  17866. "Hook for functions attaching themselves to `S-right'.
  17867. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17868. (defvar org-shiftright-final-hook nil
  17869. "Hook for functions attaching themselves to `S-right'.
  17870. This one runs after all other options except shift-select have been excluded.
  17871. See `org-ctrl-c-ctrl-c-hook' for more information.")
  17872. (defun org-modifier-cursor-error ()
  17873. "Throw an error, a modified cursor command was applied in wrong context."
  17874. (user-error "This command is active in special context like tables, headlines or items"))
  17875. (defun org-shiftselect-error ()
  17876. "Throw an error because Shift-Cursor command was applied in wrong context."
  17877. (if (and (boundp 'shift-select-mode) shift-select-mode)
  17878. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  17879. (user-error "This command works only in special context like headlines or timestamps")))
  17880. (defun org-call-for-shift-select (cmd)
  17881. (let ((this-command-keys-shift-translated t))
  17882. (call-interactively cmd)))
  17883. (defun org-shifttab (&optional arg)
  17884. "Global visibility cycling or move to previous table field.
  17885. Call `org-table-previous-field' within a table.
  17886. When ARG is nil, cycle globally through visibility states.
  17887. When ARG is a numeric prefix, show contents of this level."
  17888. (interactive "P")
  17889. (cond
  17890. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  17891. ((integerp arg)
  17892. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  17893. (message "Content view to level: %d" arg)
  17894. (org-content (prefix-numeric-value arg2))
  17895. (org-cycle-show-empty-lines t)
  17896. (setq org-cycle-global-status 'overview)))
  17897. (t (call-interactively 'org-global-cycle))))
  17898. (defun org-shiftmetaleft ()
  17899. "Promote subtree or delete table column.
  17900. Calls `org-promote-subtree', `org-outdent-item-tree', or
  17901. `org-table-delete-column', depending on context. See the
  17902. individual commands for more information."
  17903. (interactive)
  17904. (cond
  17905. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  17906. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  17907. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  17908. ((if (not (org-region-active-p)) (org-at-item-p)
  17909. (save-excursion (goto-char (region-beginning))
  17910. (org-at-item-p)))
  17911. (call-interactively 'org-outdent-item-tree))
  17912. (t (org-modifier-cursor-error))))
  17913. (defun org-shiftmetaright ()
  17914. "Demote subtree or insert table column.
  17915. Calls `org-demote-subtree', `org-indent-item-tree', or
  17916. `org-table-insert-column', depending on context. See the
  17917. individual commands for more information."
  17918. (interactive)
  17919. (cond
  17920. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  17921. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  17922. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  17923. ((if (not (org-region-active-p)) (org-at-item-p)
  17924. (save-excursion (goto-char (region-beginning))
  17925. (org-at-item-p)))
  17926. (call-interactively 'org-indent-item-tree))
  17927. (t (org-modifier-cursor-error))))
  17928. (defun org-shiftmetaup (&optional _arg)
  17929. "Drag the line at point up.
  17930. In a table, kill the current row.
  17931. On a clock timestamp, update the value of the timestamp like `S-<up>'
  17932. but also adjust the previous clocked item in the clock history.
  17933. Everywhere else, drag the line at point up."
  17934. (interactive "P")
  17935. (cond
  17936. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  17937. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  17938. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17939. (call-interactively 'org-timestamp-up)))
  17940. (t (call-interactively 'org-drag-line-backward))))
  17941. (defun org-shiftmetadown (&optional _arg)
  17942. "Drag the line at point down.
  17943. In a table, insert an empty row at the current line.
  17944. On a clock timestamp, update the value of the timestamp like `S-<down>'
  17945. but also adjust the previous clocked item in the clock history.
  17946. Everywhere else, drag the line at point down."
  17947. (interactive "P")
  17948. (cond
  17949. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  17950. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  17951. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  17952. (call-interactively 'org-timestamp-down)))
  17953. (t (call-interactively 'org-drag-line-forward))))
  17954. (defsubst org-hidden-tree-error ()
  17955. (user-error
  17956. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  17957. (defun org-metaleft (&optional _arg)
  17958. "Promote heading, list item at point or move table column left.
  17959. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  17960. depending on context. With no specific context, calls the Emacs
  17961. default `backward-word'. See the individual commands for more
  17962. information.
  17963. This function runs the hook `org-metaleft-hook' as a first step,
  17964. and returns at first non-nil value."
  17965. (interactive "P")
  17966. (cond
  17967. ((run-hook-with-args-until-success 'org-metaleft-hook))
  17968. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  17969. ((org-with-limited-levels
  17970. (or (org-at-heading-p)
  17971. (and (org-region-active-p)
  17972. (save-excursion
  17973. (goto-char (region-beginning))
  17974. (org-at-heading-p)))))
  17975. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  17976. (call-interactively 'org-do-promote))
  17977. ;; At an inline task.
  17978. ((org-at-heading-p)
  17979. (call-interactively 'org-inlinetask-promote))
  17980. ((or (org-at-item-p)
  17981. (and (org-region-active-p)
  17982. (save-excursion
  17983. (goto-char (region-beginning))
  17984. (org-at-item-p))))
  17985. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  17986. (call-interactively 'org-outdent-item))
  17987. (t (call-interactively 'backward-word))))
  17988. (defun org-metaright (&optional _arg)
  17989. "Demote heading, list item at point or move table column right.
  17990. In front of a drawer or a block keyword, indent it correctly.
  17991. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  17992. `org-indent-drawer' or `org-indent-block' depending on context.
  17993. With no specific context, calls the Emacs default `forward-word'.
  17994. See the individual commands for more information.
  17995. This function runs the hook `org-metaright-hook' as a first step,
  17996. and returns at first non-nil value."
  17997. (interactive "P")
  17998. (cond
  17999. ((run-hook-with-args-until-success 'org-metaright-hook))
  18000. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18001. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18002. ((org-at-block-p) (call-interactively 'org-indent-block))
  18003. ((org-with-limited-levels
  18004. (or (org-at-heading-p)
  18005. (and (org-region-active-p)
  18006. (save-excursion
  18007. (goto-char (region-beginning))
  18008. (org-at-heading-p)))))
  18009. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18010. (call-interactively 'org-do-demote))
  18011. ;; At an inline task.
  18012. ((org-at-heading-p)
  18013. (call-interactively 'org-inlinetask-demote))
  18014. ((or (org-at-item-p)
  18015. (and (org-region-active-p)
  18016. (save-excursion
  18017. (goto-char (region-beginning))
  18018. (org-at-item-p))))
  18019. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18020. (call-interactively 'org-indent-item))
  18021. (t (call-interactively 'forward-word))))
  18022. (defun org-check-for-hidden (what)
  18023. "Check if there are hidden headlines/items in the current visual line.
  18024. WHAT can be either `headlines' or `items'. If the current line is
  18025. an outline or item heading and it has a folded subtree below it,
  18026. this function returns t, nil otherwise."
  18027. (let ((re (cond
  18028. ((eq what 'headlines) org-outline-regexp-bol)
  18029. ((eq what 'items) (org-item-beginning-re))
  18030. (t (error "This should not happen"))))
  18031. beg end)
  18032. (save-excursion
  18033. (catch 'exit
  18034. (unless (org-region-active-p)
  18035. (setq beg (point-at-bol))
  18036. (beginning-of-line 2)
  18037. (while (and (not (eobp)) ;; this is like `next-line'
  18038. (get-char-property (1- (point)) 'invisible))
  18039. (beginning-of-line 2))
  18040. (setq end (point))
  18041. (goto-char beg)
  18042. (goto-char (point-at-eol))
  18043. (setq end (max end (point)))
  18044. (while (re-search-forward re end t)
  18045. (when (get-char-property (match-beginning 0) 'invisible)
  18046. (throw 'exit t))))
  18047. nil))))
  18048. (defun org-metaup (&optional _arg)
  18049. "Move subtree up or move table row up.
  18050. Calls `org-move-subtree-up' or `org-table-move-row' or
  18051. `org-move-item-up', depending on context. See the individual commands
  18052. for more information."
  18053. (interactive "P")
  18054. (cond
  18055. ((run-hook-with-args-until-success 'org-metaup-hook))
  18056. ((org-region-active-p)
  18057. (let* ((a (min (region-beginning) (region-end)))
  18058. (b (1- (max (region-beginning) (region-end))))
  18059. (c (save-excursion (goto-char a)
  18060. (move-beginning-of-line 0)))
  18061. (d (save-excursion (goto-char a)
  18062. (move-end-of-line 0) (point))))
  18063. (transpose-regions a b c d)
  18064. (goto-char c)))
  18065. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18066. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18067. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18068. (t (org-drag-element-backward))))
  18069. (defun org-metadown (&optional _arg)
  18070. "Move subtree down or move table row down.
  18071. Calls `org-move-subtree-down' or `org-table-move-row' or
  18072. `org-move-item-down', depending on context. See the individual
  18073. commands for more information."
  18074. (interactive "P")
  18075. (cond
  18076. ((run-hook-with-args-until-success 'org-metadown-hook))
  18077. ((org-region-active-p)
  18078. (let* ((a (min (region-beginning) (region-end)))
  18079. (b (max (region-beginning) (region-end)))
  18080. (c (save-excursion (goto-char b)
  18081. (move-beginning-of-line 1)))
  18082. (d (save-excursion (goto-char b)
  18083. (move-end-of-line 1) (1+ (point)))))
  18084. (transpose-regions a b c d)
  18085. (goto-char d)))
  18086. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18087. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18088. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18089. (t (org-drag-element-forward))))
  18090. (defun org-shiftup (&optional arg)
  18091. "Increase item in timestamp or increase priority of current headline.
  18092. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18093. depending on context. See the individual commands for more information."
  18094. (interactive "P")
  18095. (cond
  18096. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18097. ((and org-support-shift-select (org-region-active-p))
  18098. (org-call-for-shift-select 'previous-line))
  18099. ((org-at-timestamp-p 'lax)
  18100. (call-interactively (if org-edit-timestamp-down-means-later
  18101. 'org-timestamp-down 'org-timestamp-up)))
  18102. ((and (not (eq org-support-shift-select 'always))
  18103. org-enable-priority-commands
  18104. (org-at-heading-p))
  18105. (call-interactively 'org-priority-up))
  18106. ((and (not org-support-shift-select) (org-at-item-p))
  18107. (call-interactively 'org-previous-item))
  18108. ((org-clocktable-try-shift 'up arg))
  18109. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18110. (org-support-shift-select
  18111. (org-call-for-shift-select 'previous-line))
  18112. (t (org-shiftselect-error))))
  18113. (defun org-shiftdown (&optional arg)
  18114. "Decrease item in timestamp or decrease priority of current headline.
  18115. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18116. depending on context. See the individual commands for more information."
  18117. (interactive "P")
  18118. (cond
  18119. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18120. ((and org-support-shift-select (org-region-active-p))
  18121. (org-call-for-shift-select 'next-line))
  18122. ((org-at-timestamp-p 'lax)
  18123. (call-interactively (if org-edit-timestamp-down-means-later
  18124. 'org-timestamp-up 'org-timestamp-down)))
  18125. ((and (not (eq org-support-shift-select 'always))
  18126. org-enable-priority-commands
  18127. (org-at-heading-p))
  18128. (call-interactively 'org-priority-down))
  18129. ((and (not org-support-shift-select) (org-at-item-p))
  18130. (call-interactively 'org-next-item))
  18131. ((org-clocktable-try-shift 'down arg))
  18132. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18133. (org-support-shift-select
  18134. (org-call-for-shift-select 'next-line))
  18135. (t (org-shiftselect-error))))
  18136. (defun org-shiftright (&optional arg)
  18137. "Cycle the thing at point or in the current line, depending on context.
  18138. Depending on context, this does one of the following:
  18139. - switch a timestamp at point one day into the future
  18140. - on a headline, switch to the next TODO keyword.
  18141. - on an item, switch entire list to the next bullet type
  18142. - on a property line, switch to the next allowed value
  18143. - on a clocktable definition line, move time block into the future"
  18144. (interactive "P")
  18145. (cond
  18146. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18147. ((and org-support-shift-select (org-region-active-p))
  18148. (org-call-for-shift-select 'forward-char))
  18149. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  18150. ((and (not (eq org-support-shift-select 'always))
  18151. (org-at-heading-p))
  18152. (let ((org-inhibit-logging
  18153. (not org-treat-S-cursor-todo-selection-as-state-change))
  18154. (org-inhibit-blocking
  18155. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18156. (org-call-with-arg 'org-todo 'right)))
  18157. ((or (and org-support-shift-select
  18158. (not (eq org-support-shift-select 'always))
  18159. (org-at-item-bullet-p))
  18160. (and (not org-support-shift-select) (org-at-item-p)))
  18161. (org-call-with-arg 'org-cycle-list-bullet nil))
  18162. ((and (not (eq org-support-shift-select 'always))
  18163. (org-at-property-p))
  18164. (call-interactively 'org-property-next-allowed-value))
  18165. ((org-clocktable-try-shift 'right arg))
  18166. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18167. (org-support-shift-select
  18168. (org-call-for-shift-select 'forward-char))
  18169. (t (org-shiftselect-error))))
  18170. (defun org-shiftleft (&optional arg)
  18171. "Cycle the thing at point or in the current line, depending on context.
  18172. Depending on context, this does one of the following:
  18173. - switch a timestamp at point one day into the past
  18174. - on a headline, switch to the previous TODO keyword.
  18175. - on an item, switch entire list to the previous bullet type
  18176. - on a property line, switch to the previous allowed value
  18177. - on a clocktable definition line, move time block into the past"
  18178. (interactive "P")
  18179. (cond
  18180. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18181. ((and org-support-shift-select (org-region-active-p))
  18182. (org-call-for-shift-select 'backward-char))
  18183. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  18184. ((and (not (eq org-support-shift-select 'always))
  18185. (org-at-heading-p))
  18186. (let ((org-inhibit-logging
  18187. (not org-treat-S-cursor-todo-selection-as-state-change))
  18188. (org-inhibit-blocking
  18189. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18190. (org-call-with-arg 'org-todo 'left)))
  18191. ((or (and org-support-shift-select
  18192. (not (eq org-support-shift-select 'always))
  18193. (org-at-item-bullet-p))
  18194. (and (not org-support-shift-select) (org-at-item-p)))
  18195. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  18196. ((and (not (eq org-support-shift-select 'always))
  18197. (org-at-property-p))
  18198. (call-interactively 'org-property-previous-allowed-value))
  18199. ((org-clocktable-try-shift 'left arg))
  18200. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  18201. (org-support-shift-select
  18202. (org-call-for-shift-select 'backward-char))
  18203. (t (org-shiftselect-error))))
  18204. (defun org-shiftcontrolright ()
  18205. "Switch to next TODO set."
  18206. (interactive)
  18207. (cond
  18208. ((and org-support-shift-select (org-region-active-p))
  18209. (org-call-for-shift-select 'forward-word))
  18210. ((and (not (eq org-support-shift-select 'always))
  18211. (org-at-heading-p))
  18212. (org-call-with-arg 'org-todo 'nextset))
  18213. (org-support-shift-select
  18214. (org-call-for-shift-select 'forward-word))
  18215. (t (org-shiftselect-error))))
  18216. (defun org-shiftcontrolleft ()
  18217. "Switch to previous TODO set."
  18218. (interactive)
  18219. (cond
  18220. ((and org-support-shift-select (org-region-active-p))
  18221. (org-call-for-shift-select 'backward-word))
  18222. ((and (not (eq org-support-shift-select 'always))
  18223. (org-at-heading-p))
  18224. (org-call-with-arg 'org-todo 'previousset))
  18225. (org-support-shift-select
  18226. (org-call-for-shift-select 'backward-word))
  18227. (t (org-shiftselect-error))))
  18228. (defun org-shiftcontrolup (&optional n)
  18229. "Change timestamps synchronously up in CLOCK log lines.
  18230. Optional argument N tells to change by that many units."
  18231. (interactive "P")
  18232. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18233. (let (org-support-shift-select)
  18234. (org-clock-timestamps-up n))
  18235. (user-error "Not at a clock log")))
  18236. (defun org-shiftcontroldown (&optional n)
  18237. "Change timestamps synchronously down in CLOCK log lines.
  18238. Optional argument N tells to change by that many units."
  18239. (interactive "P")
  18240. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18241. (let (org-support-shift-select)
  18242. (org-clock-timestamps-down n))
  18243. (user-error "Not at a clock log")))
  18244. (defun org-increase-number-at-point (&optional inc)
  18245. "Increment the number at point.
  18246. With an optional prefix numeric argument INC, increment using
  18247. this numeric value."
  18248. (interactive "p")
  18249. (if (not (number-at-point))
  18250. (user-error "Not on a number")
  18251. (unless inc (setq inc 1))
  18252. (let ((pos (point))
  18253. (beg (skip-chars-backward "-+^/*0-9eE."))
  18254. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  18255. (setq nap (buffer-substring-no-properties
  18256. (+ pos beg) (+ pos beg end)))
  18257. (delete-region (+ pos beg) (+ pos beg end))
  18258. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18259. (when (org-at-table-p)
  18260. (org-table-align)
  18261. (org-table-end-of-field 1))))
  18262. (defun org-decrease-number-at-point (&optional inc)
  18263. "Decrement the number at point.
  18264. With an optional prefix numeric argument INC, decrement using
  18265. this numeric value."
  18266. (interactive "p")
  18267. (org-increase-number-at-point (- (or inc 1))))
  18268. (defun org-ctrl-c-ret ()
  18269. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  18270. (interactive)
  18271. (cond
  18272. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18273. (t (call-interactively 'org-insert-heading))))
  18274. (defun org-find-visible ()
  18275. (let ((s (point)))
  18276. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18277. (get-char-property s 'invisible)))
  18278. s))
  18279. (defun org-find-invisible ()
  18280. (let ((s (point)))
  18281. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18282. (not (get-char-property s 'invisible))))
  18283. s))
  18284. (defun org-copy-visible (beg end)
  18285. "Copy the visible parts of the region."
  18286. (interactive "r")
  18287. (let ((result ""))
  18288. (while (/= beg end)
  18289. (when (get-char-property beg 'invisible)
  18290. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  18291. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  18292. (setq result (concat result (buffer-substring beg next)))
  18293. (setq beg next)))
  18294. (kill-new result)))
  18295. (defun org-copy-special ()
  18296. "Copy region in table or copy current subtree.
  18297. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18298. context. See the individual commands for more information."
  18299. (interactive)
  18300. (call-interactively
  18301. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18302. (defun org-cut-special ()
  18303. "Cut region in table or cut current subtree.
  18304. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  18305. context. See the individual commands for more information."
  18306. (interactive)
  18307. (call-interactively
  18308. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  18309. (defun org-paste-special (arg)
  18310. "Paste rectangular region into table, or past subtree relative to level.
  18311. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18312. See the individual commands for more information."
  18313. (interactive "P")
  18314. (if (org-at-table-p)
  18315. (org-table-paste-rectangle)
  18316. (org-paste-subtree arg)))
  18317. (defun org-edit-special (&optional arg)
  18318. "Call a special editor for the element at point.
  18319. When at a table, call the formula editor with `org-table-edit-formulas'.
  18320. When in a source code block, call `org-edit-src-code'.
  18321. When in a fixed-width region, call `org-edit-fixed-width-region'.
  18322. When in an export block, call `org-edit-export-block'.
  18323. When in a LaTeX environment, call `org-edit-latex-environment'.
  18324. When at an #+INCLUDE keyword, visit the included file.
  18325. When at a footnote reference, call `org-edit-footnote-reference'
  18326. On a link, call `ffap' to visit the link at point.
  18327. Otherwise, return a user error."
  18328. (interactive "P")
  18329. (let ((element (org-element-at-point)))
  18330. (barf-if-buffer-read-only)
  18331. (pcase (org-element-type element)
  18332. (`src-block
  18333. (if (not arg) (org-edit-src-code)
  18334. (let* ((info (org-babel-get-src-block-info))
  18335. (lang (nth 0 info))
  18336. (params (nth 2 info))
  18337. (session (cdr (assq :session params))))
  18338. (if (not session) (org-edit-src-code)
  18339. ;; At a src-block with a session and function called with
  18340. ;; an ARG: switch to the buffer related to the inferior
  18341. ;; process.
  18342. (switch-to-buffer
  18343. (funcall (intern (concat "org-babel-prep-session:" lang))
  18344. session params))))))
  18345. (`keyword
  18346. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  18347. (org-open-link-from-string
  18348. (format "[[%s]]"
  18349. (expand-file-name
  18350. (let ((value (org-element-property :value element)))
  18351. (cond ((org-file-url-p value)
  18352. (user-error "The file is specified as a URL, cannot be edited"))
  18353. ((not (org-string-nw-p value))
  18354. (user-error "No file to edit"))
  18355. ((string-match "\\`\"\\(.*?\\)\"" value)
  18356. (match-string 1 value))
  18357. ((string-match "\\`[^ \t\"]\\S-*" value)
  18358. (match-string 0 value))
  18359. (t (user-error "No valid file specified")))))))
  18360. (user-error "No special environment to edit here")))
  18361. (`table
  18362. (if (eq (org-element-property :type element) 'table.el)
  18363. (org-edit-table.el)
  18364. (call-interactively 'org-table-edit-formulas)))
  18365. ;; Only Org tables contain `table-row' type elements.
  18366. (`table-row (call-interactively 'org-table-edit-formulas))
  18367. (`example-block (org-edit-src-code))
  18368. (`export-block (org-edit-export-block))
  18369. (`fixed-width (org-edit-fixed-width-region))
  18370. (`latex-environment (org-edit-latex-environment))
  18371. (_
  18372. ;; No notable element at point. Though, we may be at a link or
  18373. ;; a footnote reference, which are objects. Thus, scan deeper.
  18374. (let ((context (org-element-context element)))
  18375. (pcase (org-element-type context)
  18376. (`footnote-reference (org-edit-footnote-reference))
  18377. (`inline-src-block (org-edit-inline-src-code))
  18378. (`link (call-interactively #'ffap))
  18379. (_ (user-error "No special environment to edit here"))))))))
  18380. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  18381. (defun org-ctrl-c-ctrl-c (&optional arg)
  18382. "Set tags in headline, or update according to changed information at point.
  18383. This command does many different things, depending on context:
  18384. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  18385. this is what we do.
  18386. - If the cursor is on a statistics cookie, update it.
  18387. - If the cursor is in a headline, prompt for tags and insert them
  18388. into the current line, aligned to `org-tags-column'. When called
  18389. with prefix arg, realign all tags in the current buffer.
  18390. - If the cursor is in one of the special #+KEYWORD lines, this
  18391. triggers scanning the buffer for these lines and updating the
  18392. information.
  18393. - If the cursor is inside a table, realign the table. This command
  18394. works even if the automatic table editor has been turned off.
  18395. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  18396. the entire table.
  18397. - If the cursor is at a footnote reference or definition, jump to
  18398. the corresponding definition or references, respectively.
  18399. - If the cursor is a the beginning of a dynamic block, update it.
  18400. - If the current buffer is a capture buffer, close note and file it.
  18401. - If the cursor is on a <<<target>>>, update radio targets and
  18402. corresponding links in this buffer.
  18403. - If the cursor is on a numbered item in a plain list, renumber the
  18404. ordered list.
  18405. - If the cursor is on a checkbox, toggle it.
  18406. - If the cursor is on a code block, evaluate it. The variable
  18407. `org-confirm-babel-evaluate' can be used to control prompting
  18408. before code block evaluation, by default every code block
  18409. evaluation requires confirmation. Code block evaluation can be
  18410. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  18411. (interactive "P")
  18412. (cond
  18413. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  18414. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  18415. (org-remove-occur-highlights)
  18416. (message "Temporary highlights/overlays removed from current buffer"))
  18417. ((and (local-variable-p 'org-finish-function)
  18418. (fboundp org-finish-function))
  18419. (funcall org-finish-function))
  18420. ((org-babel-hash-at-point))
  18421. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  18422. (t
  18423. (let* ((context
  18424. (org-element-lineage
  18425. (org-element-context)
  18426. ;; Limit to supported contexts.
  18427. '(babel-call clock dynamic-block footnote-definition
  18428. footnote-reference inline-babel-call inline-src-block
  18429. inlinetask item keyword node-property paragraph
  18430. plain-list planning property-drawer radio-target
  18431. src-block statistics-cookie table table-cell table-row
  18432. timestamp)
  18433. t))
  18434. (type (org-element-type context)))
  18435. ;; For convenience: at the first line of a paragraph on the same
  18436. ;; line as an item, apply function on that item instead.
  18437. (when (eq type 'paragraph)
  18438. (let ((parent (org-element-property :parent context)))
  18439. (when (and (eq (org-element-type parent) 'item)
  18440. (= (line-beginning-position)
  18441. (org-element-property :begin parent)))
  18442. (setq context parent)
  18443. (setq type 'item))))
  18444. ;; Act according to type of element or object at point.
  18445. ;;
  18446. ;; Do nothing on a blank line, except if it is contained in
  18447. ;; a src block. Hence, we first check if point is in such
  18448. ;; a block and then if it is at a blank line.
  18449. (pcase type
  18450. ((or `inline-src-block `src-block)
  18451. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  18452. (org-babel-eval-wipe-error-buffer)
  18453. (org-babel-execute-src-block
  18454. current-prefix-arg (org-babel-get-src-block-info nil context))))
  18455. ((guard (org-match-line "[ \t]*$"))
  18456. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  18457. (user-error
  18458. (substitute-command-keys
  18459. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  18460. ((or `babel-call `inline-babel-call)
  18461. (let ((info (org-babel-lob-get-info context)))
  18462. (when info (org-babel-execute-src-block nil info))))
  18463. (`clock (org-clock-update-time-maybe))
  18464. (`dynamic-block
  18465. (save-excursion
  18466. (goto-char (org-element-property :post-affiliated context))
  18467. (org-update-dblock)))
  18468. (`footnote-definition
  18469. (goto-char (org-element-property :post-affiliated context))
  18470. (call-interactively 'org-footnote-action))
  18471. (`footnote-reference (call-interactively #'org-footnote-action))
  18472. ((or `headline `inlinetask)
  18473. (save-excursion (goto-char (org-element-property :begin context))
  18474. (call-interactively #'org-set-tags)))
  18475. (`item
  18476. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  18477. ;; unconditionally, whereas `C-u' will toggle its presence.
  18478. ;; Without a universal argument, if the item has a checkbox,
  18479. ;; toggle it. Otherwise repair the list.
  18480. (let* ((box (org-element-property :checkbox context))
  18481. (struct (org-element-property :structure context))
  18482. (old-struct (copy-tree struct))
  18483. (parents (org-list-parents-alist struct))
  18484. (prevs (org-list-prevs-alist struct))
  18485. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  18486. (org-list-set-checkbox
  18487. (org-element-property :begin context) struct
  18488. (cond ((equal arg '(16)) "[-]")
  18489. ((and (not box) (equal arg '(4))) "[ ]")
  18490. ((or (not box) (equal arg '(4))) nil)
  18491. ((eq box 'on) "[ ]")
  18492. (t "[X]")))
  18493. ;; Mimic `org-list-write-struct' but with grabbing a return
  18494. ;; value from `org-list-struct-fix-box'.
  18495. (org-list-struct-fix-ind struct parents 2)
  18496. (org-list-struct-fix-item-end struct)
  18497. (org-list-struct-fix-bul struct prevs)
  18498. (org-list-struct-fix-ind struct parents)
  18499. (let ((block-item
  18500. (org-list-struct-fix-box struct parents prevs orderedp)))
  18501. (if (and box (equal struct old-struct))
  18502. (if (equal arg '(16))
  18503. (message "Checkboxes already reset")
  18504. (user-error "Cannot toggle this checkbox: %s"
  18505. (if (eq box 'on)
  18506. "all subitems checked"
  18507. "unchecked subitems")))
  18508. (org-list-struct-apply-struct struct old-struct)
  18509. (org-update-checkbox-count-maybe))
  18510. (when block-item
  18511. (message "Checkboxes were removed due to empty box at line %d"
  18512. (org-current-line block-item))))))
  18513. (`keyword
  18514. (let ((org-inhibit-startup-visibility-stuff t)
  18515. (org-startup-align-all-tables nil))
  18516. (when (boundp 'org-table-coordinate-overlays)
  18517. (mapc #'delete-overlay org-table-coordinate-overlays)
  18518. (setq org-table-coordinate-overlays nil))
  18519. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  18520. (message "Local setup has been refreshed"))
  18521. (`plain-list
  18522. ;; At a plain list, with a double C-u argument, set
  18523. ;; checkboxes of each item to "[-]", whereas a single one
  18524. ;; will toggle their presence according to the state of the
  18525. ;; first item in the list. Without an argument, repair the
  18526. ;; list.
  18527. (let* ((begin (org-element-property :contents-begin context))
  18528. (struct (org-element-property :structure context))
  18529. (old-struct (copy-tree struct))
  18530. (first-box (save-excursion
  18531. (goto-char begin)
  18532. (looking-at org-list-full-item-re)
  18533. (match-string-no-properties 3)))
  18534. (new-box (cond ((equal arg '(16)) "[-]")
  18535. ((equal arg '(4)) (unless first-box "[ ]"))
  18536. ((equal first-box "[X]") "[ ]")
  18537. (t "[X]"))))
  18538. (cond
  18539. (arg
  18540. (dolist (pos
  18541. (org-list-get-all-items
  18542. begin struct (org-list-prevs-alist struct)))
  18543. (org-list-set-checkbox pos struct new-box)))
  18544. ((and first-box (eq (point) begin))
  18545. ;; For convenience, when point is at bol on the first
  18546. ;; item of the list and no argument is provided, simply
  18547. ;; toggle checkbox of that item, if any.
  18548. (org-list-set-checkbox begin struct new-box)))
  18549. (org-list-write-struct
  18550. struct (org-list-parents-alist struct) old-struct)
  18551. (org-update-checkbox-count-maybe)))
  18552. ((or `property-drawer `node-property)
  18553. (call-interactively #'org-property-action))
  18554. (`radio-target
  18555. (call-interactively #'org-update-radio-target-regexp))
  18556. (`statistics-cookie
  18557. (call-interactively #'org-update-statistics-cookies))
  18558. ((or `table `table-cell `table-row)
  18559. ;; At a table, recalculate every field and align it. Also
  18560. ;; send the table if necessary. If the table has
  18561. ;; a `table.el' type, just give up. At a table row or cell,
  18562. ;; maybe recalculate line but always align table.
  18563. (if (eq (org-element-property :type context) 'table.el)
  18564. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  18565. Use `\\[org-edit-special]' to edit table.el tables"))
  18566. (if (or (eq type 'table)
  18567. ;; Check if point is at a TBLFM line.
  18568. (and (eq type 'table-row)
  18569. (= (point) (org-element-property :end context))))
  18570. (save-excursion
  18571. (if (org-at-TBLFM-p)
  18572. (progn (require 'org-table)
  18573. (org-table-calc-current-TBLFM))
  18574. (goto-char (org-element-property :contents-begin context))
  18575. (org-call-with-arg 'org-table-recalculate (or arg t))
  18576. (orgtbl-send-table 'maybe)))
  18577. (org-table-maybe-eval-formula)
  18578. (cond (arg (call-interactively #'org-table-recalculate))
  18579. ((org-table-maybe-recalculate-line))
  18580. (t (org-table-align))))))
  18581. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  18582. (org-timestamp-change 0 'day))
  18583. ((and `nil (guard (org-at-heading-p)))
  18584. ;; When point is on an unsupported object type, we can miss
  18585. ;; the fact that it also is at a heading. Handle it here.
  18586. (call-interactively #'org-set-tags))
  18587. ((guard
  18588. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  18589. (_
  18590. (user-error
  18591. (substitute-command-keys
  18592. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  18593. (defun org-mode-restart ()
  18594. (interactive)
  18595. (let ((indent-status (bound-and-true-p org-indent-mode)))
  18596. (funcall major-mode)
  18597. (hack-local-variables)
  18598. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  18599. (org-indent-mode -1))
  18600. (org-reset-file-cache))
  18601. (message "%s restarted" major-mode))
  18602. (defun org-kill-note-or-show-branches ()
  18603. "Abort storing current note, or call `outline-show-branches'."
  18604. (interactive)
  18605. (if (not org-finish-function)
  18606. (save-excursion
  18607. (save-restriction
  18608. (org-narrow-to-subtree)
  18609. (org-flag-subtree t)
  18610. (call-interactively 'outline-show-branches)
  18611. (org-hide-archived-subtrees (point-min) (point-max))))
  18612. (let ((org-note-abort t))
  18613. (funcall org-finish-function))))
  18614. (defun org-delete-indentation (&optional arg)
  18615. "Join current line to previous and fix whitespace at join.
  18616. If previous line is a headline add to headline title. Otherwise
  18617. the function calls `delete-indentation'.
  18618. With a non-nil optional argument, join it to the following one."
  18619. (interactive "*P")
  18620. (if (save-excursion
  18621. (beginning-of-line (if arg 1 0))
  18622. (let ((case-fold-search nil))
  18623. (looking-at org-complex-heading-regexp)))
  18624. ;; At headline.
  18625. (let ((tags-column (when (match-beginning 5)
  18626. (save-excursion (goto-char (match-beginning 5))
  18627. (current-column))))
  18628. (string (concat " " (progn (when arg (forward-line 1))
  18629. (org-trim (delete-and-extract-region
  18630. (line-beginning-position)
  18631. (line-end-position)))))))
  18632. (unless (bobp) (delete-region (point) (1- (point))))
  18633. (goto-char (or (match-end 4)
  18634. (match-beginning 5)
  18635. (match-end 0)))
  18636. (skip-chars-backward " \t")
  18637. (save-excursion (insert string))
  18638. ;; Adjust alignment of tags.
  18639. (cond
  18640. ((not tags-column)) ;no tags
  18641. (org-auto-align-tags (org-set-tags nil t))
  18642. (t (org--align-tags-here tags-column)))) ;preserve tags column
  18643. (delete-indentation arg)))
  18644. (defun org-open-line (n)
  18645. "Insert a new row in tables, call `open-line' elsewhere.
  18646. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  18647. As a special case, when a document starts with a table, allow to
  18648. call `open-line' on the very first character."
  18649. (interactive "*p")
  18650. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  18651. (org-table-insert-row)
  18652. (open-line n)))
  18653. (defun org-return (&optional indent)
  18654. "Goto next table row or insert a newline.
  18655. Calls `org-table-next-row' or `newline', depending on context.
  18656. When optional INDENT argument is non-nil, call
  18657. `newline-and-indent' instead of `newline'.
  18658. When `org-return-follows-link' is non-nil and point is on
  18659. a timestamp or a link, call `org-open-at-point'. However, it
  18660. will not happen if point is in a table or on a \"dead\"
  18661. object (e.g., within a comment). In these case, you need to use
  18662. `org-open-at-point' directly."
  18663. (interactive)
  18664. (let ((context (if org-return-follows-link (org-element-context)
  18665. (org-element-at-point))))
  18666. (cond
  18667. ;; In a table, call `org-table-next-row'. However, before first
  18668. ;; column or after last one, split the table.
  18669. ((or (and (eq (org-element-type context) 'table)
  18670. (>= (point) (org-element-property :contents-begin context))
  18671. (< (point) (org-element-property :contents-end context)))
  18672. (org-element-lineage context '(table-row table-cell) t))
  18673. (if (or (looking-at-p "[ \t]*$")
  18674. (save-excursion (skip-chars-backward " \t") (bolp)))
  18675. (insert "\n")
  18676. (org-table-justify-field-maybe)
  18677. (call-interactively #'org-table-next-row)))
  18678. ;; On a link or a timestamp, call `org-open-at-point' if
  18679. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  18680. ;; locations, e.g., in a comment, as `org-open-at-point'.
  18681. ((and org-return-follows-link
  18682. (or (and (eq 'link (org-element-type context))
  18683. ;; Ensure point is not on the white spaces after
  18684. ;; the link.
  18685. (let ((origin (point)))
  18686. (org-with-point-at (org-element-property :end context)
  18687. (skip-chars-backward " \t")
  18688. (> (point) origin))))
  18689. (org-in-regexp org-ts-regexp-both nil t)
  18690. (org-in-regexp org-tsr-regexp-both nil t)
  18691. (org-in-regexp org-any-link-re nil t)))
  18692. (call-interactively #'org-open-at-point))
  18693. ;; Insert newline in heading, but preserve tags.
  18694. ((and (not (bolp))
  18695. (save-excursion (beginning-of-line)
  18696. (let ((case-fold-search nil))
  18697. (looking-at org-complex-heading-regexp))))
  18698. ;; At headline. Split line. However, if point is on keyword,
  18699. ;; priority cookie or tags, do not break any of them: add
  18700. ;; a newline after the headline instead.
  18701. (let ((tags-column (and (match-beginning 5)
  18702. (save-excursion (goto-char (match-beginning 5))
  18703. (current-column))))
  18704. (string
  18705. (when (and (match-end 4) (org-point-in-group (point) 4))
  18706. (delete-and-extract-region (point) (match-end 4)))))
  18707. ;; Adjust tag alignment.
  18708. (cond
  18709. ((not (and tags-column string)))
  18710. (org-auto-align-tags (org-set-tags nil t))
  18711. (t (org--align-tags-here tags-column))) ;preserve tags column
  18712. (end-of-line)
  18713. (org-show-entry)
  18714. (if indent (newline-and-indent) (newline))
  18715. (when string (save-excursion (insert (org-trim string))))))
  18716. ;; In a list, make sure indenting keeps trailing text within.
  18717. ((and indent
  18718. (not (eolp))
  18719. (org-element-lineage context '(item)))
  18720. (let ((trailing-data
  18721. (delete-and-extract-region (point) (line-end-position))))
  18722. (newline-and-indent)
  18723. (save-excursion (insert trailing-data))))
  18724. (t
  18725. ;; Do not auto-fill when point is in an Org property drawer.
  18726. (let ((auto-fill-function (and (not (org-at-property-p))
  18727. auto-fill-function)))
  18728. (if indent
  18729. (newline-and-indent)
  18730. (newline)))))))
  18731. (defun org-return-indent ()
  18732. "Goto next table row or insert a newline and indent.
  18733. Calls `org-table-next-row' or `newline-and-indent', depending on
  18734. context. See the individual commands for more information."
  18735. (interactive)
  18736. (org-return t))
  18737. (defun org-ctrl-c-tab (&optional _arg)
  18738. "Toggle columns width in a table, or show children.
  18739. Call `org-table-toggle-column-width' if point is in a table.
  18740. Otherwise, call `org-show-children'."
  18741. (interactive "p")
  18742. (call-interactively
  18743. (if (org-at-table-p) #'org-table-toggle-column-width
  18744. #'org-show-children)))
  18745. (defun org-ctrl-c-star ()
  18746. "Compute table, or change heading status of lines.
  18747. Calls `org-table-recalculate' or `org-toggle-heading',
  18748. depending on context."
  18749. (interactive)
  18750. (cond
  18751. ((org-at-table-p)
  18752. (call-interactively 'org-table-recalculate))
  18753. (t
  18754. ;; Convert all lines in region to list items
  18755. (call-interactively 'org-toggle-heading))))
  18756. (defun org-ctrl-c-minus ()
  18757. "Insert separator line in table or modify bullet status of line.
  18758. Also turns a plain line or a region of lines into list items.
  18759. Calls `org-table-insert-hline', `org-toggle-item', or
  18760. `org-cycle-list-bullet', depending on context."
  18761. (interactive)
  18762. (cond
  18763. ((org-at-table-p)
  18764. (call-interactively 'org-table-insert-hline))
  18765. ((org-region-active-p)
  18766. (call-interactively 'org-toggle-item))
  18767. ((org-in-item-p)
  18768. (call-interactively 'org-cycle-list-bullet))
  18769. (t
  18770. (call-interactively 'org-toggle-item))))
  18771. (defun org-toggle-heading (&optional nstars)
  18772. "Convert headings to normal text, or items or text to headings.
  18773. If there is no active region, only convert the current line.
  18774. With a `\\[universal-argument]' prefix, convert the whole list at
  18775. point into heading.
  18776. In a region:
  18777. - If the first non blank line is a headline, remove the stars
  18778. from all headlines in the region.
  18779. - If it is a normal line, turn each and every normal line (i.e.,
  18780. not an heading or an item) in the region into headings. If you
  18781. want to convert only the first line of this region, use one
  18782. universal prefix argument.
  18783. - If it is a plain list item, turn all plain list items into headings.
  18784. When converting a line into a heading, the number of stars is chosen
  18785. such that the lines become children of the current entry. However,
  18786. when a numeric prefix argument is given, its value determines the
  18787. number of stars to add."
  18788. (interactive "P")
  18789. (let ((skip-blanks
  18790. (function
  18791. ;; Return beginning of first non-blank line, starting from
  18792. ;; line at POS.
  18793. (lambda (pos)
  18794. (save-excursion
  18795. (goto-char pos)
  18796. (while (org-at-comment-p) (forward-line))
  18797. (skip-chars-forward " \r\t\n")
  18798. (point-at-bol)))))
  18799. beg end toggled)
  18800. ;; Determine boundaries of changes. If a universal prefix has
  18801. ;; been given, put the list in a region. If region ends at a bol,
  18802. ;; do not consider the last line to be in the region.
  18803. (when (and current-prefix-arg (org-at-item-p))
  18804. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  18805. (org-mark-element))
  18806. (if (org-region-active-p)
  18807. (setq beg (funcall skip-blanks (region-beginning))
  18808. end (copy-marker (save-excursion
  18809. (goto-char (region-end))
  18810. (if (bolp) (point) (point-at-eol)))))
  18811. (setq beg (funcall skip-blanks (point-at-bol))
  18812. end (copy-marker (point-at-eol))))
  18813. ;; Ensure inline tasks don't count as headings.
  18814. (org-with-limited-levels
  18815. (save-excursion
  18816. (goto-char beg)
  18817. (cond
  18818. ;; Case 1. Started at an heading: de-star headings.
  18819. ((org-at-heading-p)
  18820. (while (< (point) end)
  18821. (when (org-at-heading-p t)
  18822. (looking-at org-outline-regexp) (replace-match "")
  18823. (setq toggled t))
  18824. (forward-line)))
  18825. ;; Case 2. Started at an item: change items into headlines.
  18826. ;; One star will be added by `org-list-to-subtree'.
  18827. ((org-at-item-p)
  18828. (while (< (point) end)
  18829. (when (org-at-item-p)
  18830. ;; Pay attention to cases when region ends before list.
  18831. (let* ((struct (org-list-struct))
  18832. (list-end
  18833. (min (org-list-get-bottom-point struct) (1+ end))))
  18834. (save-restriction
  18835. (narrow-to-region (point) list-end)
  18836. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  18837. (setq toggled t))
  18838. (forward-line)))
  18839. ;; Case 3. Started at normal text: make every line an heading,
  18840. ;; skipping headlines and items.
  18841. (t (let* ((stars
  18842. (make-string
  18843. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  18844. (add-stars
  18845. (cond (nstars "") ; stars from prefix only
  18846. ((equal stars "") "*") ; before first heading
  18847. (org-odd-levels-only "**") ; inside heading, odd
  18848. (t "*"))) ; inside heading, oddeven
  18849. (rpl (concat stars add-stars " "))
  18850. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  18851. (while (< (point) (if (equal nstars '(4)) lend end))
  18852. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  18853. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  18854. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  18855. (forward-line)))))))
  18856. (unless toggled (message "Cannot toggle heading from here"))))
  18857. (defun org-meta-return (&optional arg)
  18858. "Insert a new heading or wrap a region in a table.
  18859. Calls `org-insert-heading', `org-insert-item' or
  18860. `org-table-wrap-region', depending on context. When called with
  18861. an argument, unconditionally call `org-insert-heading'."
  18862. (interactive "P")
  18863. (org-check-before-invisible-edit 'insert)
  18864. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  18865. (call-interactively (cond (arg #'org-insert-heading)
  18866. ((org-at-table-p) #'org-table-wrap-region)
  18867. ((org-in-item-p) #'org-insert-item)
  18868. (t #'org-insert-heading)))))
  18869. ;;; Menu entries
  18870. (defsubst org-in-subtree-not-table-p ()
  18871. "Are we in a subtree and not in a table?"
  18872. (and (not (org-before-first-heading-p))
  18873. (not (org-at-table-p))))
  18874. ;; Define the Org mode menus
  18875. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  18876. '("Tbl"
  18877. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  18878. ["Next Field" org-cycle (org-at-table-p)]
  18879. ["Previous Field" org-shifttab (org-at-table-p)]
  18880. ["Next Row" org-return (org-at-table-p)]
  18881. "--"
  18882. ["Blank Field" org-table-blank-field (org-at-table-p)]
  18883. ["Edit Field" org-table-edit-field (org-at-table-p)]
  18884. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  18885. "--"
  18886. ("Column"
  18887. ["Move Column Left" org-metaleft (org-at-table-p)]
  18888. ["Move Column Right" org-metaright (org-at-table-p)]
  18889. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  18890. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  18891. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  18892. ("Row"
  18893. ["Move Row Up" org-metaup (org-at-table-p)]
  18894. ["Move Row Down" org-metadown (org-at-table-p)]
  18895. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  18896. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  18897. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  18898. "--"
  18899. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  18900. ("Rectangle"
  18901. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  18902. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  18903. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  18904. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  18905. "--"
  18906. ("Calculate"
  18907. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  18908. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  18909. ["Edit Formulas" org-edit-special (org-at-table-p)]
  18910. "--"
  18911. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  18912. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  18913. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  18914. "--"
  18915. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  18916. "--"
  18917. ["Sum Column/Rectangle" org-table-sum
  18918. (or (org-at-table-p) (org-region-active-p))]
  18919. ["Which Column?" org-table-current-column (org-at-table-p)])
  18920. ["Debug Formulas"
  18921. org-table-toggle-formula-debugger
  18922. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  18923. ["Show Col/Row Numbers"
  18924. org-table-toggle-coordinate-overlays
  18925. :style toggle
  18926. :selected (bound-and-true-p org-table-overlay-coordinates)]
  18927. "--"
  18928. ["Create" org-table-create (not (org-at-table-p))]
  18929. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  18930. ["Import from File" org-table-import (not (org-at-table-p))]
  18931. ["Export to File" org-table-export (org-at-table-p)]
  18932. "--"
  18933. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  18934. "--"
  18935. ("Plot"
  18936. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  18937. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  18938. (easy-menu-define org-org-menu org-mode-map "Org menu"
  18939. '("Org"
  18940. ("Show/Hide"
  18941. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  18942. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  18943. ["Sparse Tree..." org-sparse-tree t]
  18944. ["Reveal Context" org-reveal t]
  18945. ["Show All" org-show-all t]
  18946. "--"
  18947. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  18948. "--"
  18949. ["New Heading" org-insert-heading t]
  18950. ("Navigate Headings"
  18951. ["Up" outline-up-heading t]
  18952. ["Next" outline-next-visible-heading t]
  18953. ["Previous" outline-previous-visible-heading t]
  18954. ["Next Same Level" outline-forward-same-level t]
  18955. ["Previous Same Level" outline-backward-same-level t]
  18956. "--"
  18957. ["Jump" org-goto t])
  18958. ("Edit Structure"
  18959. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  18960. "--"
  18961. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  18962. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  18963. "--"
  18964. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  18965. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  18966. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  18967. "--"
  18968. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  18969. "--"
  18970. ["Copy visible text" org-copy-visible t]
  18971. "--"
  18972. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  18973. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  18974. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  18975. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  18976. "--"
  18977. ["Sort Region/Children" org-sort t]
  18978. "--"
  18979. ["Convert to odd levels" org-convert-to-odd-levels t]
  18980. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  18981. ("Editing"
  18982. ["Emphasis..." org-emphasize t]
  18983. ["Edit Source Example" org-edit-special t]
  18984. "--"
  18985. ["Footnote new/jump" org-footnote-action t]
  18986. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  18987. ("Archive"
  18988. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  18989. "--"
  18990. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  18991. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  18992. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  18993. )
  18994. "--"
  18995. ("Hyperlinks"
  18996. ["Store Link (Global)" org-store-link t]
  18997. ["Find existing link to here" org-occur-link-in-agenda-files t]
  18998. ["Insert Link" org-insert-link t]
  18999. ["Follow Link" org-open-at-point t]
  19000. "--"
  19001. ["Next link" org-next-link t]
  19002. ["Previous link" org-previous-link t]
  19003. "--"
  19004. ["Descriptive Links"
  19005. org-toggle-link-display
  19006. :style radio
  19007. :selected org-descriptive-links
  19008. ]
  19009. ["Literal Links"
  19010. org-toggle-link-display
  19011. :style radio
  19012. :selected (not org-descriptive-links)])
  19013. "--"
  19014. ("TODO Lists"
  19015. ["TODO/DONE/-" org-todo t]
  19016. ("Select keyword"
  19017. ["Next keyword" org-shiftright (org-at-heading-p)]
  19018. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19019. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19020. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19021. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19022. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19023. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  19024. "--"
  19025. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19026. :selected org-enforce-todo-dependencies :style toggle :active t]
  19027. "Settings for tree at point"
  19028. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19029. :selected (org-entry-get nil "ORDERED")
  19030. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19031. ["Do Children parallel" org-toggle-ordered-property :style radio
  19032. :selected (not (org-entry-get nil "ORDERED"))
  19033. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19034. "--"
  19035. ["Set Priority" org-priority t]
  19036. ["Priority Up" org-shiftup t]
  19037. ["Priority Down" org-shiftdown t]
  19038. "--"
  19039. ["Get news from all feeds" org-feed-update-all t]
  19040. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19041. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19042. ("TAGS and Properties"
  19043. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19044. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19045. "--"
  19046. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19047. ["Column view of properties" org-columns t]
  19048. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19049. ("Dates and Scheduling"
  19050. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19051. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19052. ("Change Date"
  19053. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  19054. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  19055. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  19056. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  19057. ["Compute Time Range" org-evaluate-time-range t]
  19058. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19059. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19060. "--"
  19061. ["Custom time format" org-toggle-time-stamp-overlays
  19062. :style radio :selected org-display-custom-times]
  19063. "--"
  19064. ["Goto Calendar" org-goto-calendar t]
  19065. ["Date from Calendar" org-date-from-calendar t]
  19066. "--"
  19067. ["Start/Restart Timer" org-timer-start t]
  19068. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19069. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19070. ["Insert Timer String" org-timer t]
  19071. ["Insert Timer Item" org-timer-item t])
  19072. ("Logging work"
  19073. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19074. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19075. ["Clock out" org-clock-out t]
  19076. ["Clock cancel" org-clock-cancel t]
  19077. "--"
  19078. ["Mark as default task" org-clock-mark-default-task t]
  19079. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19080. ["Goto running clock" org-clock-goto t]
  19081. "--"
  19082. ["Display times" org-clock-display t]
  19083. ["Create clock table" org-clock-report t]
  19084. "--"
  19085. ["Record DONE time"
  19086. (progn (setq org-log-done (not org-log-done))
  19087. (message "Switching to %s will %s record a timestamp"
  19088. (car org-done-keywords)
  19089. (if org-log-done "automatically" "not")))
  19090. :style toggle :selected org-log-done])
  19091. "--"
  19092. ["Agenda Command..." org-agenda t]
  19093. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19094. ("File List for Agenda")
  19095. ("Special views current file"
  19096. ["TODO Tree" org-show-todo-tree t]
  19097. ["Check Deadlines" org-check-deadlines t]
  19098. ["Tags/Property tree" org-match-sparse-tree t])
  19099. "--"
  19100. ["Export/Publish..." org-export-dispatch t]
  19101. ("LaTeX"
  19102. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  19103. :style toggle :selected org-cdlatex-mode]
  19104. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19105. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19106. ["Modify math symbol" org-cdlatex-math-modify
  19107. (org-inside-LaTeX-fragment-p)]
  19108. ["Insert citation" org-reftex-citation t])
  19109. "--"
  19110. ("MobileOrg"
  19111. ["Push Files and Views" org-mobile-push t]
  19112. ["Get Captured and Flagged" org-mobile-pull t]
  19113. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
  19114. "--"
  19115. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19116. "--"
  19117. ("Documentation"
  19118. ["Show Version" org-version t]
  19119. ["Info Documentation" org-info t])
  19120. ("Customize"
  19121. ["Browse Org Group" org-customize t]
  19122. "--"
  19123. ["Expand This Menu" org-create-customize-menu
  19124. (fboundp 'customize-menu-create)])
  19125. ["Send bug report" org-submit-bug-report t]
  19126. "--"
  19127. ("Refresh/Reload"
  19128. ["Refresh setup current buffer" org-mode-restart t]
  19129. ["Reload Org (after update)" org-reload t]
  19130. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  19131. ))
  19132. (defun org-info (&optional node)
  19133. "Read documentation for Org in the info system.
  19134. With optional NODE, go directly to that node."
  19135. (interactive)
  19136. (info (format "(org)%s" (or node ""))))
  19137. ;;;###autoload
  19138. (defun org-submit-bug-report ()
  19139. "Submit a bug report on Org via mail.
  19140. Don't hesitate to report any problems or inaccurate documentation.
  19141. If you don't have setup sending mail from (X)Emacs, please copy the
  19142. output buffer into your mail program, as it gives us important
  19143. information about your Org version and configuration."
  19144. (interactive)
  19145. (require 'reporter)
  19146. (defvar reporter-prompt-for-summary-p)
  19147. (org-load-modules-maybe)
  19148. (org-require-autoloaded-modules)
  19149. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19150. (reporter-submit-bug-report
  19151. "emacs-orgmode@gnu.org"
  19152. (org-version nil 'full)
  19153. (let (list)
  19154. (save-window-excursion
  19155. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19156. (delete-other-windows)
  19157. (erase-buffer)
  19158. (insert "You are about to submit a bug report to the Org mailing list.
  19159. We would like to add your full Org and Outline configuration to the
  19160. bug report. This greatly simplifies the work of the maintainer and
  19161. other experts on the mailing list.
  19162. HOWEVER, some variables you have customized may contain private
  19163. information. The names of customers, colleagues, or friends, might
  19164. appear in the form of file names, tags, todo states, or search strings.
  19165. If you answer yes to the prompt, you might want to check and remove
  19166. such private information before sending the email.")
  19167. (add-text-properties (point-min) (point-max) '(face org-warning))
  19168. (when (yes-or-no-p "Include your Org configuration ")
  19169. (mapatoms
  19170. (lambda (v)
  19171. (and (boundp v)
  19172. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19173. (or (and (symbol-value v)
  19174. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19175. (and
  19176. (get v 'custom-type) (get v 'standard-value)
  19177. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19178. (push v list)))))
  19179. (kill-buffer (get-buffer "*Warn about privacy*"))
  19180. list))
  19181. nil nil
  19182. "Remember to cover the basics, that is, what you expected to happen and
  19183. what in fact did happen. You don't know how to make a good report? See
  19184. https://orgmode.org/manual/Feedback.html#Feedback
  19185. Your bug report will be posted to the Org mailing list.
  19186. ------------------------------------------------------------------------")
  19187. (save-excursion
  19188. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19189. (replace-match "\\1Bug: \\3 [\\2]")))))
  19190. (defun org-install-agenda-files-menu ()
  19191. (let ((bl (buffer-list)))
  19192. (save-excursion
  19193. (while bl
  19194. (set-buffer (pop bl))
  19195. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19196. (when (derived-mode-p 'org-mode)
  19197. (easy-menu-change
  19198. '("Org") "File List for Agenda"
  19199. (append
  19200. (list
  19201. ["Edit File List" (org-edit-agenda-file-list) t]
  19202. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19203. ["Remove Current File from List" org-remove-file t]
  19204. ["Cycle through agenda files" org-cycle-agenda-files t]
  19205. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19206. "--")
  19207. (mapcar 'org-file-menu-entry
  19208. ;; Prevent initialization from failing.
  19209. (ignore-errors (org-agenda-files t)))))))))
  19210. ;;;; Documentation
  19211. (defun org-require-autoloaded-modules ()
  19212. (interactive)
  19213. (mapc #'require
  19214. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19215. org-table org-timer)))
  19216. ;;;###autoload
  19217. (defun org-reload (&optional uncompiled)
  19218. "Reload all Org Lisp files.
  19219. With prefix arg UNCOMPILED, load the uncompiled versions."
  19220. (interactive "P")
  19221. (require 'loadhist)
  19222. (let* ((org-dir (org-find-library-dir "org"))
  19223. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19224. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  19225. (remove-re (format "\\`%s\\'"
  19226. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19227. (feats (delete-dups
  19228. (mapcar 'file-name-sans-extension
  19229. (mapcar 'file-name-nondirectory
  19230. (delq nil
  19231. (mapcar 'feature-file
  19232. features))))))
  19233. (lfeat (append
  19234. (sort
  19235. (setq feats
  19236. (delq nil (mapcar
  19237. (lambda (f)
  19238. (if (and (string-match feature-re f)
  19239. (not (string-match remove-re f)))
  19240. f nil))
  19241. feats)))
  19242. 'string-lessp)
  19243. (list "org-version" "org")))
  19244. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  19245. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19246. load-uncore load-misses)
  19247. (setq load-misses
  19248. (delq 't
  19249. (mapcar (lambda (f)
  19250. (or (org-load-noerror-mustsuffix (concat org-dir f))
  19251. (and (string= org-dir contrib-dir)
  19252. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19253. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19254. (add-to-list 'load-uncore f 'append)
  19255. 't)
  19256. f))
  19257. lfeat)))
  19258. (when load-uncore
  19259. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19260. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  19261. (if load-misses
  19262. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19263. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19264. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19265. ;;;###autoload
  19266. (defun org-customize ()
  19267. "Call the customize function with org as argument."
  19268. (interactive)
  19269. (org-load-modules-maybe)
  19270. (org-require-autoloaded-modules)
  19271. (customize-browse 'org))
  19272. (defun org-create-customize-menu ()
  19273. "Create a full customization menu for Org mode, insert it into the menu."
  19274. (interactive)
  19275. (org-load-modules-maybe)
  19276. (org-require-autoloaded-modules)
  19277. (if (fboundp 'customize-menu-create)
  19278. (progn
  19279. (easy-menu-change
  19280. '("Org") "Customize"
  19281. `(["Browse Org group" org-customize t]
  19282. "--"
  19283. ,(customize-menu-create 'org)
  19284. ["Set" Custom-set t]
  19285. ["Save" Custom-save t]
  19286. ["Reset to Current" Custom-reset-current t]
  19287. ["Reset to Saved" Custom-reset-saved t]
  19288. ["Reset to Standard Settings" Custom-reset-standard t]))
  19289. (message "\"Org\"-menu now contains full customization menu"))
  19290. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  19291. ;;;; Miscellaneous stuff
  19292. ;;; Generally useful functions
  19293. (defun org-link-display-format (s)
  19294. "Replace links in string S with their description.
  19295. If there is no description, use the link target."
  19296. (save-match-data
  19297. (replace-regexp-in-string
  19298. org-bracket-link-analytic-regexp
  19299. (lambda (m)
  19300. (if (match-end 5) (match-string 5 m)
  19301. (concat (match-string 1 m) (match-string 3 m))))
  19302. s nil t)))
  19303. (defun org-toggle-link-display ()
  19304. "Toggle the literal or descriptive display of links."
  19305. (interactive)
  19306. (if org-descriptive-links
  19307. (progn (org-remove-from-invisibility-spec '(org-link))
  19308. (org-restart-font-lock)
  19309. (setq org-descriptive-links nil))
  19310. (progn (add-to-invisibility-spec '(org-link))
  19311. (org-restart-font-lock)
  19312. (setq org-descriptive-links t))))
  19313. (defun org-in-clocktable-p ()
  19314. "Check if the cursor is in a clocktable."
  19315. (let ((pos (point)) start)
  19316. (save-excursion
  19317. (end-of-line 1)
  19318. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19319. (setq start (match-beginning 0))
  19320. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19321. (>= (match-end 0) pos)
  19322. start))))
  19323. (defun org-in-verbatim-emphasis ()
  19324. (save-match-data
  19325. (and (org-in-regexp org-verbatim-re 2)
  19326. (>= (point) (match-beginning 3))
  19327. (<= (point) (match-end 4)))))
  19328. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19329. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  19330. (if (and marker (marker-buffer marker)
  19331. (buffer-live-p (marker-buffer marker)))
  19332. (progn
  19333. (pop-to-buffer-same-window (marker-buffer marker))
  19334. (when (or (> marker (point-max)) (< marker (point-min)))
  19335. (widen))
  19336. (goto-char marker)
  19337. (org-show-context 'org-goto))
  19338. (if bookmark
  19339. (bookmark-jump bookmark)
  19340. (error "Cannot find location"))))
  19341. (defun org-quote-csv-field (s)
  19342. "Quote field for inclusion in CSV material."
  19343. (if (string-match "[\",]" s)
  19344. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19345. s))
  19346. (defun org-force-self-insert (N)
  19347. "Needed to enforce self-insert under remapping."
  19348. (interactive "p")
  19349. (self-insert-command N))
  19350. (defun org-fill-template (template alist)
  19351. "Find each %key of ALIST in TEMPLATE and replace it."
  19352. (let ((case-fold-search nil))
  19353. (dolist (entry (sort (copy-sequence alist)
  19354. (lambda (a b) (< (length (car a)) (length (car b))))))
  19355. (setq template
  19356. (replace-regexp-in-string
  19357. (concat "%" (regexp-quote (car entry)))
  19358. (or (cdr entry) "") template t t)))
  19359. template))
  19360. (defun org-quote-vert (s)
  19361. "Replace \"|\" with \"\\vert\"."
  19362. (while (string-match "|" s)
  19363. (setq s (replace-match "\\vert" t t s)))
  19364. s)
  19365. (defun org-uuidgen-p (s)
  19366. "Is S an ID created by UUIDGEN?"
  19367. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  19368. (defun org-in-src-block-p (&optional inside)
  19369. "Whether point is in a code source block.
  19370. When INSIDE is non-nil, don't consider we are within a src block
  19371. when point is at #+BEGIN_SRC or #+END_SRC."
  19372. (let ((case-fold-search t))
  19373. (or (and (eq (get-char-property (point) 'src-block) t))
  19374. (and (not inside)
  19375. (save-match-data
  19376. (save-excursion
  19377. (beginning-of-line)
  19378. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  19379. (defun org-context ()
  19380. "Return a list of contexts of the current cursor position.
  19381. If several contexts apply, all are returned.
  19382. Each context entry is a list with a symbol naming the context, and
  19383. two positions indicating start and end of the context. Possible
  19384. contexts are:
  19385. :headline anywhere in a headline
  19386. :headline-stars on the leading stars in a headline
  19387. :todo-keyword on a TODO keyword (including DONE) in a headline
  19388. :tags on the TAGS in a headline
  19389. :priority on the priority cookie in a headline
  19390. :item on the first line of a plain list item
  19391. :item-bullet on the bullet/number of a plain list item
  19392. :checkbox on the checkbox in a plain list item
  19393. :table in an Org table
  19394. :table-special on a special filed in a table
  19395. :table-table in a table.el table
  19396. :clocktable in a clocktable
  19397. :src-block in a source block
  19398. :link on a hyperlink
  19399. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  19400. :target on a <<target>>
  19401. :radio-target on a <<<radio-target>>>
  19402. :latex-fragment on a LaTeX fragment
  19403. :latex-preview on a LaTeX fragment with overlaid preview image
  19404. This function expects the position to be visible because it uses font-lock
  19405. faces as a help to recognize the following contexts: :table-special, :link,
  19406. and :keyword."
  19407. (let* ((f (get-text-property (point) 'face))
  19408. (faces (if (listp f) f (list f)))
  19409. (case-fold-search t)
  19410. (p (point)) clist o)
  19411. ;; First the large context
  19412. (cond
  19413. ((org-at-heading-p t)
  19414. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  19415. (when (progn
  19416. (beginning-of-line 1)
  19417. (looking-at org-todo-line-tags-regexp))
  19418. (push (org-point-in-group p 1 :headline-stars) clist)
  19419. (push (org-point-in-group p 2 :todo-keyword) clist)
  19420. (push (org-point-in-group p 4 :tags) clist))
  19421. (goto-char p)
  19422. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  19423. (when (looking-at "\\[#[A-Z0-9]\\]")
  19424. (push (org-point-in-group p 0 :priority) clist)))
  19425. ((org-at-item-p)
  19426. (push (org-point-in-group p 2 :item-bullet) clist)
  19427. (push (list :item (point-at-bol)
  19428. (save-excursion (org-end-of-item) (point)))
  19429. clist)
  19430. (and (org-at-item-checkbox-p)
  19431. (push (org-point-in-group p 0 :checkbox) clist)))
  19432. ((org-at-table-p)
  19433. (push (list :table (org-table-begin) (org-table-end)) clist)
  19434. (when (memq 'org-formula faces)
  19435. (push (list :table-special
  19436. (previous-single-property-change p 'face)
  19437. (next-single-property-change p 'face)) clist)))
  19438. ((org-at-table-p 'any)
  19439. (push (list :table-table) clist)))
  19440. (goto-char p)
  19441. (let ((case-fold-search t))
  19442. ;; New the "medium" contexts: clocktables, source blocks
  19443. (cond ((org-in-clocktable-p)
  19444. (push (list :clocktable
  19445. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  19446. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  19447. (match-beginning 1))
  19448. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  19449. (match-end 0))) clist))
  19450. ((org-in-src-block-p)
  19451. (push (list :src-block
  19452. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  19453. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  19454. (match-beginning 1))
  19455. (and (search-forward "#+END_SRC" nil t)
  19456. (match-beginning 0))) clist))))
  19457. (goto-char p)
  19458. ;; Now the small context
  19459. (cond
  19460. ((org-at-timestamp-p)
  19461. (push (org-point-in-group p 0 :timestamp) clist))
  19462. ((memq 'org-link faces)
  19463. (push (list :link
  19464. (previous-single-property-change p 'face)
  19465. (next-single-property-change p 'face)) clist))
  19466. ((memq 'org-special-keyword faces)
  19467. (push (list :keyword
  19468. (previous-single-property-change p 'face)
  19469. (next-single-property-change p 'face)) clist))
  19470. ((org-at-target-p)
  19471. (push (org-point-in-group p 0 :target) clist)
  19472. (goto-char (1- (match-beginning 0)))
  19473. (when (looking-at org-radio-target-regexp)
  19474. (push (org-point-in-group p 0 :radio-target) clist))
  19475. (goto-char p))
  19476. ((setq o (cl-some
  19477. (lambda (o)
  19478. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  19479. o))
  19480. (overlays-at (point))))
  19481. (push (list :latex-fragment
  19482. (overlay-start o) (overlay-end o)) clist)
  19483. (push (list :latex-preview
  19484. (overlay-start o) (overlay-end o)) clist))
  19485. ((org-inside-LaTeX-fragment-p)
  19486. ;; FIXME: positions wrong.
  19487. (push (list :latex-fragment (point) (point)) clist)))
  19488. (setq clist (nreverse (delq nil clist)))
  19489. clist))
  19490. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  19491. "Non-nil when point is between matches of START-RE and END-RE.
  19492. Also return a non-nil value when point is on one of the matches.
  19493. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  19494. buffer positions. Default values are the positions of headlines
  19495. surrounding the point.
  19496. The functions returns a cons cell whose car (resp. cdr) is the
  19497. position before START-RE (resp. after END-RE)."
  19498. (save-match-data
  19499. (let ((pos (point))
  19500. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  19501. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  19502. beg end)
  19503. (save-excursion
  19504. ;; Point is on a block when on START-RE or if START-RE can be
  19505. ;; found before it...
  19506. (and (or (org-in-regexp start-re)
  19507. (re-search-backward start-re limit-up t))
  19508. (setq beg (match-beginning 0))
  19509. ;; ... and END-RE after it...
  19510. (goto-char (match-end 0))
  19511. (re-search-forward end-re limit-down t)
  19512. (> (setq end (match-end 0)) pos)
  19513. ;; ... without another START-RE in-between.
  19514. (goto-char (match-beginning 0))
  19515. (not (re-search-backward start-re (1+ beg) t))
  19516. ;; Return value.
  19517. (cons beg end))))))
  19518. (defun org-in-block-p (names)
  19519. "Non-nil when point belongs to a block whose name belongs to NAMES.
  19520. NAMES is a list of strings containing names of blocks.
  19521. Return first block name matched, or nil. Beware that in case of
  19522. nested blocks, the returned name may not belong to the closest
  19523. block from point."
  19524. (save-match-data
  19525. (catch 'exit
  19526. (let ((case-fold-search t)
  19527. (lim-up (save-excursion (outline-previous-heading)))
  19528. (lim-down (save-excursion (outline-next-heading))))
  19529. (dolist (name names)
  19530. (let ((n (regexp-quote name)))
  19531. (when (org-between-regexps-p
  19532. (concat "^[ \t]*#\\+begin_" n)
  19533. (concat "^[ \t]*#\\+end_" n)
  19534. lim-up lim-down)
  19535. (throw 'exit n)))))
  19536. nil)))
  19537. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  19538. "Call `multi-occur' with buffers for all agenda files."
  19539. (interactive "sOrg-files matching: ")
  19540. (let* ((files (org-agenda-files))
  19541. (tnames (mapcar #'file-truename files))
  19542. (extra org-agenda-text-search-extra-files))
  19543. (when (eq (car extra) 'agenda-archives)
  19544. (setq extra (cdr extra))
  19545. (setq files (org-add-archive-files files)))
  19546. (dolist (f extra)
  19547. (unless (member (file-truename f) tnames)
  19548. (unless (member f files) (setq files (append files (list f))))
  19549. (setq tnames (append tnames (list (file-truename f))))))
  19550. (multi-occur
  19551. (mapcar (lambda (x)
  19552. (with-current-buffer
  19553. ;; FIXME: Why not just (find-file-noselect x)?
  19554. ;; Is it to avoid the "revert buffer" prompt?
  19555. (or (get-file-buffer x) (find-file-noselect x))
  19556. (widen)
  19557. (current-buffer)))
  19558. files)
  19559. regexp)))
  19560. (add-hook 'occur-mode-find-occurrence-hook
  19561. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  19562. (defun org-occur-link-in-agenda-files ()
  19563. "Create a link and search for it in the agendas.
  19564. The link is not stored in `org-stored-links', it is just created
  19565. for the search purpose."
  19566. (interactive)
  19567. (let ((link (condition-case nil
  19568. (org-store-link nil)
  19569. (error "Unable to create a link to here"))))
  19570. (org-occur-in-agenda-files (regexp-quote link))))
  19571. (defun org-back-over-empty-lines ()
  19572. "Move backwards over whitespace, to the beginning of the first empty line.
  19573. Returns the number of empty lines passed."
  19574. (let ((pos (point)))
  19575. (if (cdr (assq 'heading org-blank-before-new-entry))
  19576. (skip-chars-backward " \t\n\r")
  19577. (unless (eobp)
  19578. (forward-line -1)))
  19579. (beginning-of-line 2)
  19580. (goto-char (min (point) pos))
  19581. (count-lines (point) pos)))
  19582. (defun org-switch-to-buffer-other-window (&rest args)
  19583. "Switch to buffer in a second window on the current frame.
  19584. In particular, do not allow pop-up frames.
  19585. Returns the newly created buffer."
  19586. (org-no-popups
  19587. (apply 'switch-to-buffer-other-window args)))
  19588. (defun org-replace-escapes (string table)
  19589. "Replace %-escapes in STRING with values in TABLE.
  19590. TABLE is an association list with keys like \"%a\" and string values.
  19591. The sequences in STRING may contain normal field width and padding information,
  19592. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  19593. so values can contain further %-escapes if they are define later in TABLE."
  19594. (let ((tbl (copy-alist table))
  19595. (case-fold-search nil)
  19596. (pchg 0)
  19597. re rpl)
  19598. (dolist (e tbl)
  19599. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  19600. (when (and (cdr e) (string-match re (cdr e)))
  19601. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  19602. (safe "SREF"))
  19603. (add-text-properties 0 3 (list 'sref sref) safe)
  19604. (setcdr e (replace-match safe t t (cdr e)))))
  19605. (while (string-match re string)
  19606. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  19607. (cdr e)))
  19608. (setq string (replace-match rpl t t string))))
  19609. (while (setq pchg (next-property-change pchg string))
  19610. (let ((sref (get-text-property pchg 'sref string)))
  19611. (when (and sref (string-match "SREF" string pchg))
  19612. (setq string (replace-match sref t t string)))))
  19613. string))
  19614. ;;; TODO: Only called once, from ox-odt which should probably use
  19615. ;;; org-export-inline-image-p or something.
  19616. (defun org-file-image-p (file)
  19617. "Return non-nil if FILE is an image."
  19618. (save-match-data
  19619. (string-match (image-file-name-regexp) file)))
  19620. (defun org-get-cursor-date (&optional with-time)
  19621. "Return the date at cursor in as a time.
  19622. This works in the calendar and in the agenda, anywhere else it just
  19623. returns the current time.
  19624. If WITH-TIME is non-nil, returns the time of the event at point (in
  19625. the agenda) or the current time of the day."
  19626. (let (date day defd tp hod mod)
  19627. (when with-time
  19628. (setq tp (get-text-property (point) 'time))
  19629. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  19630. (setq hod (string-to-number (match-string 1 tp))
  19631. mod (string-to-number (match-string 2 tp))))
  19632. (or tp (let ((now (decode-time)))
  19633. (setq hod (nth 2 now)
  19634. mod (nth 1 now)))))
  19635. (cond
  19636. ((eq major-mode 'calendar-mode)
  19637. (setq date (calendar-cursor-to-date)
  19638. defd (encode-time 0 (or mod 0) (or hod 0)
  19639. (nth 1 date) (nth 0 date) (nth 2 date))))
  19640. ((eq major-mode 'org-agenda-mode)
  19641. (setq day (get-text-property (point) 'day))
  19642. (when day
  19643. (setq date (calendar-gregorian-from-absolute day)
  19644. defd (encode-time 0 (or mod 0) (or hod 0)
  19645. (nth 1 date) (nth 0 date) (nth 2 date))))))
  19646. (or defd (current-time))))
  19647. (defun org-mark-subtree (&optional up)
  19648. "Mark the current subtree.
  19649. This puts point at the start of the current subtree, and mark at
  19650. the end. If a numeric prefix UP is given, move up into the
  19651. hierarchy of headlines by UP levels before marking the subtree."
  19652. (interactive "P")
  19653. (org-with-limited-levels
  19654. (cond ((org-at-heading-p) (beginning-of-line))
  19655. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  19656. (t (outline-previous-visible-heading 1))))
  19657. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  19658. (if (called-interactively-p 'any)
  19659. (call-interactively 'org-mark-element)
  19660. (org-mark-element)))
  19661. ;;; Indentation
  19662. (defvar org-element-greater-elements)
  19663. (defun org--get-expected-indentation (element contentsp)
  19664. "Expected indentation column for current line, according to ELEMENT.
  19665. ELEMENT is an element containing point. CONTENTSP is non-nil
  19666. when indentation is to be computed according to contents of
  19667. ELEMENT."
  19668. (let ((type (org-element-type element))
  19669. (start (org-element-property :begin element))
  19670. (post-affiliated (org-element-property :post-affiliated element)))
  19671. (org-with-wide-buffer
  19672. (cond
  19673. (contentsp
  19674. (cl-case type
  19675. ((diary-sexp footnote-definition) 0)
  19676. ((headline inlinetask nil)
  19677. (if (not org-adapt-indentation) 0
  19678. (let ((level (org-current-level)))
  19679. (if level (1+ level) 0))))
  19680. ((item plain-list) (org-list-item-body-column post-affiliated))
  19681. (t
  19682. (goto-char start)
  19683. (org-get-indentation))))
  19684. ((memq type '(headline inlinetask nil))
  19685. (if (org-match-line "[ \t]*$")
  19686. (org--get-expected-indentation element t)
  19687. 0))
  19688. ((memq type '(diary-sexp footnote-definition)) 0)
  19689. ;; First paragraph of a footnote definition or an item.
  19690. ;; Indent like parent.
  19691. ((< (line-beginning-position) start)
  19692. (org--get-expected-indentation
  19693. (org-element-property :parent element) t))
  19694. ;; At first line: indent according to previous sibling, if any,
  19695. ;; ignoring footnote definitions and inline tasks, or parent's
  19696. ;; contents.
  19697. ((= (line-beginning-position) start)
  19698. (catch 'exit
  19699. (while t
  19700. (if (= (point-min) start) (throw 'exit 0)
  19701. (goto-char (1- start))
  19702. (let* ((previous (org-element-at-point))
  19703. (parent previous))
  19704. (while (and parent (<= (org-element-property :end parent) start))
  19705. (setq previous parent
  19706. parent (org-element-property :parent parent)))
  19707. (cond
  19708. ((not previous) (throw 'exit 0))
  19709. ((> (org-element-property :end previous) start)
  19710. (throw 'exit (org--get-expected-indentation previous t)))
  19711. ((memq (org-element-type previous)
  19712. '(footnote-definition inlinetask))
  19713. (setq start (org-element-property :begin previous)))
  19714. (t (goto-char (org-element-property :begin previous))
  19715. (throw 'exit
  19716. (if (bolp) (org-get-indentation)
  19717. ;; At first paragraph in an item or
  19718. ;; a footnote definition.
  19719. (org--get-expected-indentation
  19720. (org-element-property :parent previous) t))))))))))
  19721. ;; Otherwise, move to the first non-blank line above.
  19722. (t
  19723. (beginning-of-line)
  19724. (let ((pos (point)))
  19725. (skip-chars-backward " \r\t\n")
  19726. (cond
  19727. ;; Two blank lines end a footnote definition or a plain
  19728. ;; list. When we indent an empty line after them, the
  19729. ;; containing list or footnote definition is over, so it
  19730. ;; qualifies as a previous sibling. Therefore, we indent
  19731. ;; like its first line.
  19732. ((and (memq type '(footnote-definition plain-list))
  19733. (> (count-lines (point) pos) 2))
  19734. (goto-char start)
  19735. (org-get-indentation))
  19736. ;; Line above is the first one of a paragraph at the
  19737. ;; beginning of an item or a footnote definition. Indent
  19738. ;; like parent.
  19739. ((< (line-beginning-position) start)
  19740. (org--get-expected-indentation
  19741. (org-element-property :parent element) t))
  19742. ;; Line above is the beginning of an element, i.e., point
  19743. ;; was originally on the blank lines between element's start
  19744. ;; and contents.
  19745. ((= (line-beginning-position) post-affiliated)
  19746. (org--get-expected-indentation element t))
  19747. ;; POS is after contents in a greater element. Indent like
  19748. ;; the beginning of the element.
  19749. ((and (memq type org-element-greater-elements)
  19750. (let ((cend (org-element-property :contents-end element)))
  19751. (and cend (<= cend pos))))
  19752. ;; As a special case, if point is at the end of a footnote
  19753. ;; definition or an item, indent like the very last element
  19754. ;; within. If that last element is an item, indent like
  19755. ;; its contents.
  19756. (if (memq type '(footnote-definition item plain-list))
  19757. (let ((last (org-element-at-point)))
  19758. (goto-char pos)
  19759. (org--get-expected-indentation
  19760. last (eq (org-element-type last) 'item)))
  19761. (goto-char start)
  19762. (org-get-indentation)))
  19763. ;; In any other case, indent like the current line.
  19764. (t (org-get-indentation)))))))))
  19765. (defun org--align-node-property ()
  19766. "Align node property at point.
  19767. Alignment is done according to `org-property-format', which see."
  19768. (when (save-excursion
  19769. (beginning-of-line)
  19770. (looking-at org-property-re))
  19771. (replace-match
  19772. (concat (match-string 4)
  19773. (org-trim
  19774. (format org-property-format (match-string 1) (match-string 3))))
  19775. t t)))
  19776. (defun org-indent-line ()
  19777. "Indent line depending on context.
  19778. Indentation is done according to the following rules:
  19779. - Footnote definitions, diary sexps, headlines and inline tasks
  19780. have to start at column 0.
  19781. - On the very first line of an element, consider, in order, the
  19782. next rules until one matches:
  19783. 1. If there's a sibling element before, ignoring footnote
  19784. definitions and inline tasks, indent like its first line.
  19785. 2. If element has a parent, indent like its contents. More
  19786. precisely, if parent is an item, indent after the
  19787. description part, if any, or the bullet (see
  19788. `org-list-description-max-indent'). Else, indent like
  19789. parent's first line.
  19790. 3. Otherwise, indent relatively to current level, if
  19791. `org-adapt-indentation' is non-nil, or to left margin.
  19792. - On a blank line at the end of an element, indent according to
  19793. the type of the element. More precisely
  19794. 1. If element is a plain list, an item, or a footnote
  19795. definition, indent like the very last element within.
  19796. 2. If element is a paragraph, indent like its last non blank
  19797. line.
  19798. 3. Otherwise, indent like its very first line.
  19799. - In the code part of a source block, use language major mode
  19800. to indent current line if `org-src-tab-acts-natively' is
  19801. non-nil. If it is nil, do nothing.
  19802. - Otherwise, indent like the first non-blank line above.
  19803. The function doesn't indent an item as it could break the whole
  19804. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  19805. `\\[org-shiftmetaright]'.
  19806. Also align node properties according to `org-property-format'."
  19807. (interactive)
  19808. (cond
  19809. ((org-at-heading-p) 'noindent)
  19810. (t
  19811. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  19812. (type (org-element-type element)))
  19813. (cond ((and (memq type '(plain-list item))
  19814. (= (line-beginning-position)
  19815. (org-element-property :post-affiliated element)))
  19816. 'noindent)
  19817. ((and (eq type 'latex-environment)
  19818. (>= (point) (org-element-property :post-affiliated element))
  19819. (< (point) (org-with-wide-buffer
  19820. (goto-char (org-element-property :end element))
  19821. (skip-chars-backward " \r\t\n")
  19822. (line-beginning-position 2))))
  19823. 'noindent)
  19824. ((and (eq type 'src-block)
  19825. org-src-tab-acts-natively
  19826. (> (line-beginning-position)
  19827. (org-element-property :post-affiliated element))
  19828. (< (line-beginning-position)
  19829. (org-with-wide-buffer
  19830. (goto-char (org-element-property :end element))
  19831. (skip-chars-backward " \r\t\n")
  19832. (line-beginning-position))))
  19833. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  19834. (t
  19835. (let ((column (org--get-expected-indentation element nil)))
  19836. ;; Preserve current column.
  19837. (if (<= (current-column) (current-indentation))
  19838. (indent-line-to column)
  19839. (save-excursion (indent-line-to column))))
  19840. ;; Align node property. Also preserve current column.
  19841. (when (eq type 'node-property)
  19842. (let ((column (current-column)))
  19843. (org--align-node-property)
  19844. (org-move-to-column column)))))))))
  19845. (defun org-indent-region (start end)
  19846. "Indent each non-blank line in the region.
  19847. Called from a program, START and END specify the region to
  19848. indent. The function will not indent contents of example blocks,
  19849. verse blocks and export blocks as leading white spaces are
  19850. assumed to be significant there."
  19851. (interactive "r")
  19852. (save-excursion
  19853. (goto-char start)
  19854. (skip-chars-forward " \r\t\n")
  19855. (unless (eobp) (beginning-of-line))
  19856. (let ((indent-to
  19857. (lambda (ind pos)
  19858. ;; Set IND as indentation for all lines between point and
  19859. ;; POS. Blank lines are ignored. Leave point after POS
  19860. ;; once done.
  19861. (let ((limit (copy-marker pos)))
  19862. (while (< (point) limit)
  19863. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  19864. (forward-line))
  19865. (set-marker limit nil))))
  19866. (end (copy-marker end)))
  19867. (while (< (point) end)
  19868. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  19869. (let* ((element (org-element-at-point))
  19870. (type (org-element-type element))
  19871. (element-end (copy-marker (org-element-property :end element)))
  19872. (ind (org--get-expected-indentation element nil)))
  19873. (cond
  19874. ;; Element indented as a single block. Example blocks
  19875. ;; preserving indentation are a special case since the
  19876. ;; "contents" must not be indented whereas the block
  19877. ;; boundaries can.
  19878. ((or (memq type '(export-block latex-environment))
  19879. (and (eq type 'example-block)
  19880. (not
  19881. (or org-src-preserve-indentation
  19882. (org-element-property :preserve-indent element)))))
  19883. (let ((offset (- ind (org-get-indentation))))
  19884. (unless (zerop offset)
  19885. (indent-rigidly (org-element-property :begin element)
  19886. (org-element-property :end element)
  19887. offset)))
  19888. (goto-char element-end))
  19889. ;; Elements indented line wise. Be sure to exclude
  19890. ;; example blocks (preserving indentation) and source
  19891. ;; blocks from this category as they are treated
  19892. ;; specially later.
  19893. ((or (memq type '(paragraph table table-row))
  19894. (not (or (org-element-property :contents-begin element)
  19895. (memq type '(example-block src-block)))))
  19896. (when (eq type 'node-property)
  19897. (org--align-node-property)
  19898. (beginning-of-line))
  19899. (funcall indent-to ind (min element-end end)))
  19900. ;; Elements consisting of three parts: before the
  19901. ;; contents, the contents, and after the contents. The
  19902. ;; contents are treated specially, according to the
  19903. ;; element type, or not indented at all. Other parts are
  19904. ;; indented as a single block.
  19905. (t
  19906. (let* ((post (copy-marker
  19907. (org-element-property :post-affiliated element)))
  19908. (cbeg
  19909. (copy-marker
  19910. (cond
  19911. ((not (org-element-property :contents-begin element))
  19912. ;; Fake contents for source blocks.
  19913. (org-with-wide-buffer
  19914. (goto-char post)
  19915. (line-beginning-position 2)))
  19916. ((memq type '(footnote-definition item plain-list))
  19917. ;; Contents in these elements could start on
  19918. ;; the same line as the beginning of the
  19919. ;; element. Make sure we start indenting
  19920. ;; from the second line.
  19921. (org-with-wide-buffer
  19922. (goto-char post)
  19923. (end-of-line)
  19924. (skip-chars-forward " \r\t\n")
  19925. (if (eobp) (point) (line-beginning-position))))
  19926. (t (org-element-property :contents-begin element)))))
  19927. (cend (copy-marker
  19928. (or (org-element-property :contents-end element)
  19929. ;; Fake contents for source blocks.
  19930. (org-with-wide-buffer
  19931. (goto-char element-end)
  19932. (skip-chars-backward " \r\t\n")
  19933. (line-beginning-position)))
  19934. t)))
  19935. ;; Do not change items indentation individually as it
  19936. ;; might break the list as a whole. On the other
  19937. ;; hand, when at a plain list, indent it as a whole.
  19938. (cond ((eq type 'plain-list)
  19939. (let ((offset (- ind (org-get-indentation))))
  19940. (unless (zerop offset)
  19941. (indent-rigidly (org-element-property :begin element)
  19942. (org-element-property :end element)
  19943. offset))
  19944. (goto-char cbeg)))
  19945. ((eq type 'item) (goto-char cbeg))
  19946. (t (funcall indent-to ind (min cbeg end))))
  19947. (when (< (point) end)
  19948. (cl-case type
  19949. ((example-block verse-block))
  19950. (src-block
  19951. ;; In a source block, indent source code
  19952. ;; according to language major mode, but only if
  19953. ;; `org-src-tab-acts-natively' is non-nil.
  19954. (when (and (< (point) end) org-src-tab-acts-natively)
  19955. (ignore-errors
  19956. (org-babel-do-in-edit-buffer
  19957. (indent-region (point-min) (point-max))))))
  19958. (t (org-indent-region (point) (min cend end))))
  19959. (goto-char (min cend end))
  19960. (when (< (point) end)
  19961. (funcall indent-to ind (min element-end end))))
  19962. (set-marker post nil)
  19963. (set-marker cbeg nil)
  19964. (set-marker cend nil))))
  19965. (set-marker element-end nil))))
  19966. (set-marker end nil))))
  19967. (defun org-indent-drawer ()
  19968. "Indent the drawer at point."
  19969. (interactive)
  19970. (unless (save-excursion
  19971. (beginning-of-line)
  19972. (looking-at-p org-drawer-regexp))
  19973. (user-error "Not at a drawer"))
  19974. (let ((element (org-element-at-point)))
  19975. (unless (memq (org-element-type element) '(drawer property-drawer))
  19976. (user-error "Not at a drawer"))
  19977. (org-with-wide-buffer
  19978. (org-indent-region (org-element-property :begin element)
  19979. (org-element-property :end element))))
  19980. (message "Drawer at point indented"))
  19981. (defun org-indent-block ()
  19982. "Indent the block at point."
  19983. (interactive)
  19984. (unless (save-excursion
  19985. (beginning-of-line)
  19986. (let ((case-fold-search t))
  19987. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  19988. (user-error "Not at a block"))
  19989. (let ((element (org-element-at-point)))
  19990. (unless (memq (org-element-type element)
  19991. '(comment-block center-block dynamic-block example-block
  19992. export-block quote-block special-block
  19993. src-block verse-block))
  19994. (user-error "Not at a block"))
  19995. (org-with-wide-buffer
  19996. (org-indent-region (org-element-property :begin element)
  19997. (org-element-property :end element))))
  19998. (message "Block at point indented"))
  19999. ;;; Filling
  20000. ;; We use our own fill-paragraph and auto-fill functions.
  20001. ;; `org-fill-paragraph' relies on adaptive filling and context
  20002. ;; checking. Appropriate `fill-prefix' is computed with
  20003. ;; `org-adaptive-fill-function'.
  20004. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  20005. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  20006. ;; `org-adaptive-fill-function' value. Internally,
  20007. ;; `org-comment-line-break-function' breaks the line.
  20008. ;; `org-setup-filling' installs filling and auto-filling related
  20009. ;; variables during `org-mode' initialization.
  20010. (defun org-setup-filling ()
  20011. (require 'org-element)
  20012. ;; Prevent auto-fill from inserting unwanted new items.
  20013. (when (boundp 'fill-nobreak-predicate)
  20014. (setq-local
  20015. fill-nobreak-predicate
  20016. (org-uniquify
  20017. (append fill-nobreak-predicate
  20018. '(org-fill-line-break-nobreak-p
  20019. org-fill-n-macro-as-item-nobreak-p
  20020. org-fill-paragraph-with-timestamp-nobreak-p)))))
  20021. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  20022. (setq-local paragraph-start paragraph-ending)
  20023. (setq-local paragraph-separate paragraph-ending))
  20024. (setq-local fill-paragraph-function 'org-fill-paragraph)
  20025. (setq-local auto-fill-inhibit-regexp nil)
  20026. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  20027. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  20028. (setq-local comment-line-break-function 'org-comment-line-break-function))
  20029. (defun org-fill-line-break-nobreak-p ()
  20030. "Non-nil when a new line at point would create an Org line break."
  20031. (save-excursion
  20032. (skip-chars-backward "[ \t]")
  20033. (skip-chars-backward "\\\\")
  20034. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  20035. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  20036. "Non-nil when a new line at point would split a timestamp."
  20037. (and (org-at-timestamp-p 'lax)
  20038. (not (looking-at org-ts-regexp-both))))
  20039. (defun org-fill-n-macro-as-item-nobreak-p ()
  20040. "Non-nil when a new line at point would create a new list."
  20041. ;; During export, a "n" macro followed by a dot or a closing
  20042. ;; parenthesis can end up being parsed as a new list item.
  20043. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  20044. (defvar orgtbl-line-start-regexp) ; From org-table.el
  20045. (defun org-adaptive-fill-function ()
  20046. "Compute a fill prefix for the current line.
  20047. Return fill prefix, as a string, or nil if current line isn't
  20048. meant to be filled. For convenience, if `adaptive-fill-regexp'
  20049. matches in paragraphs or comments, use it."
  20050. (org-with-wide-buffer
  20051. (unless (org-at-heading-p)
  20052. (let* ((p (line-beginning-position))
  20053. (element (save-excursion
  20054. (beginning-of-line)
  20055. (org-element-at-point)))
  20056. (type (org-element-type element))
  20057. (post-affiliated (org-element-property :post-affiliated element)))
  20058. (unless (< p post-affiliated)
  20059. (cl-case type
  20060. (comment
  20061. (save-excursion
  20062. (beginning-of-line)
  20063. (looking-at "[ \t]*")
  20064. (concat (match-string 0) "# ")))
  20065. (footnote-definition "")
  20066. ((item plain-list)
  20067. (make-string (org-list-item-body-column post-affiliated) ?\s))
  20068. (paragraph
  20069. ;; Fill prefix is usually the same as the current line,
  20070. ;; unless the paragraph is at the beginning of an item.
  20071. (let ((parent (org-element-property :parent element)))
  20072. (save-excursion
  20073. (beginning-of-line)
  20074. (cond ((eq (org-element-type parent) 'item)
  20075. (make-string (org-list-item-body-column
  20076. (org-element-property :begin parent))
  20077. ?\s))
  20078. ((and adaptive-fill-regexp
  20079. ;; Locally disable
  20080. ;; `adaptive-fill-function' to let
  20081. ;; `fill-context-prefix' handle
  20082. ;; `adaptive-fill-regexp' variable.
  20083. (let (adaptive-fill-function)
  20084. (fill-context-prefix
  20085. post-affiliated
  20086. (org-element-property :end element)))))
  20087. ((looking-at "[ \t]+") (match-string 0))
  20088. (t "")))))
  20089. (comment-block
  20090. ;; Only fill contents if P is within block boundaries.
  20091. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  20092. (forward-line)
  20093. (point)))
  20094. (cend (save-excursion
  20095. (goto-char (org-element-property :end element))
  20096. (skip-chars-backward " \r\t\n")
  20097. (line-beginning-position))))
  20098. (when (and (>= p cbeg) (< p cend))
  20099. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  20100. (match-string 0)
  20101. ""))))))))))
  20102. (defun org-fill-element (&optional justify)
  20103. "Fill element at point, when applicable.
  20104. This function only applies to comment blocks, comments, example
  20105. blocks and paragraphs. Also, as a special case, re-align table
  20106. when point is at one.
  20107. If JUSTIFY is non-nil (interactively, with prefix argument),
  20108. justify as well. If `sentence-end-double-space' is non-nil, then
  20109. period followed by one space does not end a sentence, so don't
  20110. break a line there. The variable `fill-column' controls the
  20111. width for filling.
  20112. For convenience, when point is at a plain list, an item or
  20113. a footnote definition, try to fill the first paragraph within."
  20114. (with-syntax-table org-mode-transpose-word-syntax-table
  20115. ;; Move to end of line in order to get the first paragraph within
  20116. ;; a plain list or a footnote definition.
  20117. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  20118. ;; First check if point is in a blank line at the beginning of
  20119. ;; the buffer. In that case, ignore filling.
  20120. (cl-case (org-element-type element)
  20121. ;; Use major mode filling function is src blocks.
  20122. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  20123. ;; Align Org tables, leave table.el tables as-is.
  20124. (table-row (org-table-align) t)
  20125. (table
  20126. (when (eq (org-element-property :type element) 'org)
  20127. (save-excursion
  20128. (goto-char (org-element-property :post-affiliated element))
  20129. (org-table-align)))
  20130. t)
  20131. (paragraph
  20132. ;; Paragraphs may contain `line-break' type objects.
  20133. (let ((beg (max (point-min)
  20134. (org-element-property :contents-begin element)))
  20135. (end (min (point-max)
  20136. (org-element-property :contents-end element))))
  20137. ;; Do nothing if point is at an affiliated keyword.
  20138. (if (< (line-end-position) beg) t
  20139. ;; Fill paragraph, taking line breaks into account.
  20140. (save-excursion
  20141. (goto-char beg)
  20142. (let ((cuts (list beg)))
  20143. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  20144. (when (eq 'line-break
  20145. (org-element-type
  20146. (save-excursion (backward-char)
  20147. (org-element-context))))
  20148. (push (point) cuts)))
  20149. (dolist (c (delq end cuts))
  20150. (fill-region-as-paragraph c end justify)
  20151. (setq end c))))
  20152. t)))
  20153. ;; Contents of `comment-block' type elements should be
  20154. ;; filled as plain text, but only if point is within block
  20155. ;; markers.
  20156. (comment-block
  20157. (let* ((case-fold-search t)
  20158. (beg (save-excursion
  20159. (goto-char (org-element-property :begin element))
  20160. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  20161. (forward-line)
  20162. (point)))
  20163. (end (save-excursion
  20164. (goto-char (org-element-property :end element))
  20165. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  20166. (line-beginning-position))))
  20167. (if (or (< (point) beg) (> (point) end)) t
  20168. (fill-region-as-paragraph
  20169. (save-excursion (end-of-line)
  20170. (re-search-backward "^[ \t]*$" beg 'move)
  20171. (line-beginning-position))
  20172. (save-excursion (beginning-of-line)
  20173. (re-search-forward "^[ \t]*$" end 'move)
  20174. (line-beginning-position))
  20175. justify))))
  20176. ;; Fill comments.
  20177. (comment
  20178. (let ((begin (org-element-property :post-affiliated element))
  20179. (end (org-element-property :end element)))
  20180. (when (and (>= (point) begin) (<= (point) end))
  20181. (let ((begin (save-excursion
  20182. (end-of-line)
  20183. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  20184. (progn (forward-line) (point))
  20185. begin)))
  20186. (end (save-excursion
  20187. (end-of-line)
  20188. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  20189. (1- (line-beginning-position))
  20190. (skip-chars-backward " \r\t\n")
  20191. (line-end-position)))))
  20192. ;; Do not fill comments when at a blank line.
  20193. (when (> end begin)
  20194. (let ((fill-prefix
  20195. (save-excursion
  20196. (beginning-of-line)
  20197. (looking-at "[ \t]*#")
  20198. (let ((comment-prefix (match-string 0)))
  20199. (goto-char (match-end 0))
  20200. (if (looking-at adaptive-fill-regexp)
  20201. (concat comment-prefix (match-string 0))
  20202. (concat comment-prefix " "))))))
  20203. (save-excursion
  20204. (fill-region-as-paragraph begin end justify))))))
  20205. t))
  20206. ;; Ignore every other element.
  20207. (otherwise t)))))
  20208. (defun org-fill-paragraph (&optional justify region)
  20209. "Fill element at point, when applicable.
  20210. This function only applies to comment blocks, comments, example
  20211. blocks and paragraphs. Also, as a special case, re-align table
  20212. when point is at one.
  20213. For convenience, when point is at a plain list, an item or
  20214. a footnote definition, try to fill the first paragraph within.
  20215. If JUSTIFY is non-nil (interactively, with prefix argument),
  20216. justify as well. If `sentence-end-double-space' is non-nil, then
  20217. period followed by one space does not end a sentence, so don't
  20218. break a line there. The variable `fill-column' controls the
  20219. width for filling.
  20220. The REGION argument is non-nil if called interactively; in that
  20221. case, if Transient Mark mode is enabled and the mark is active,
  20222. fill each of the elements in the active region, instead of just
  20223. filling the current element."
  20224. (interactive (progn
  20225. (barf-if-buffer-read-only)
  20226. (list (if current-prefix-arg 'full) t)))
  20227. (cond
  20228. ((and region transient-mark-mode mark-active
  20229. (not (eq (region-beginning) (region-end))))
  20230. (let ((origin (point-marker))
  20231. (start (region-beginning)))
  20232. (unwind-protect
  20233. (progn
  20234. (goto-char (region-end))
  20235. (while (> (point) start)
  20236. (org-backward-paragraph)
  20237. (org-fill-element justify)))
  20238. (goto-char origin)
  20239. (set-marker origin nil))))
  20240. (t (org-fill-element justify))))
  20241. (defun org-auto-fill-function ()
  20242. "Auto-fill function."
  20243. ;; Check if auto-filling is meaningful.
  20244. (let ((fc (current-fill-column)))
  20245. (when (and fc (> (current-column) fc))
  20246. (let* ((fill-prefix (org-adaptive-fill-function))
  20247. ;; Enforce empty fill prefix, if required. Otherwise, it
  20248. ;; will be computed again.
  20249. (adaptive-fill-mode (not (equal fill-prefix ""))))
  20250. (when fill-prefix (do-auto-fill))))))
  20251. (defun org-comment-line-break-function (&optional soft)
  20252. "Break line at point and indent, continuing comment if within one.
  20253. The inserted newline is marked hard if variable
  20254. `use-hard-newlines' is true, unless optional argument SOFT is
  20255. non-nil."
  20256. (if soft (insert-and-inherit ?\n) (newline 1))
  20257. (save-excursion (forward-char -1) (delete-horizontal-space))
  20258. (delete-horizontal-space)
  20259. (indent-to-left-margin)
  20260. (insert-before-markers-and-inherit fill-prefix))
  20261. ;;; Fixed Width Areas
  20262. (defun org-toggle-fixed-width ()
  20263. "Toggle fixed-width markup.
  20264. Add or remove fixed-width markup on current line, whenever it
  20265. makes sense. Return an error otherwise.
  20266. If a region is active and if it contains only fixed-width areas
  20267. or blank lines, remove all fixed-width markup in it. If the
  20268. region contains anything else, convert all non-fixed-width lines
  20269. to fixed-width ones.
  20270. Blank lines at the end of the region are ignored unless the
  20271. region only contains such lines."
  20272. (interactive)
  20273. (if (not (org-region-active-p))
  20274. ;; No region:
  20275. ;;
  20276. ;; Remove fixed width marker only in a fixed-with element.
  20277. ;;
  20278. ;; Add fixed width maker in paragraphs, in blank lines after
  20279. ;; elements or at the beginning of a headline or an inlinetask,
  20280. ;; and before any one-line elements (e.g., a clock).
  20281. (progn
  20282. (beginning-of-line)
  20283. (let* ((element (org-element-at-point))
  20284. (type (org-element-type element)))
  20285. (cond
  20286. ((and (eq type 'fixed-width)
  20287. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  20288. (replace-match
  20289. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  20290. ((and (memq type '(babel-call clock comment diary-sexp headline
  20291. horizontal-rule keyword paragraph
  20292. planning))
  20293. (<= (org-element-property :post-affiliated element) (point)))
  20294. (skip-chars-forward " \t")
  20295. (insert ": "))
  20296. ((and (looking-at-p "[ \t]*$")
  20297. (or (eq type 'inlinetask)
  20298. (save-excursion
  20299. (skip-chars-forward " \r\t\n")
  20300. (<= (org-element-property :end element) (point)))))
  20301. (delete-region (point) (line-end-position))
  20302. (org-indent-line)
  20303. (insert ": "))
  20304. (t (user-error "Cannot insert a fixed-width line here")))))
  20305. ;; Region active.
  20306. (let* ((begin (save-excursion
  20307. (goto-char (region-beginning))
  20308. (line-beginning-position)))
  20309. (end (copy-marker
  20310. (save-excursion
  20311. (goto-char (region-end))
  20312. (unless (eolp) (beginning-of-line))
  20313. (if (save-excursion (re-search-backward "\\S-" begin t))
  20314. (progn (skip-chars-backward " \r\t\n") (point))
  20315. (point)))))
  20316. (all-fixed-width-p
  20317. (catch 'not-all-p
  20318. (save-excursion
  20319. (goto-char begin)
  20320. (skip-chars-forward " \r\t\n")
  20321. (when (eobp) (throw 'not-all-p nil))
  20322. (while (< (point) end)
  20323. (let ((element (org-element-at-point)))
  20324. (if (eq (org-element-type element) 'fixed-width)
  20325. (goto-char (org-element-property :end element))
  20326. (throw 'not-all-p nil))))
  20327. t))))
  20328. (if all-fixed-width-p
  20329. (save-excursion
  20330. (goto-char begin)
  20331. (while (< (point) end)
  20332. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  20333. (replace-match
  20334. "" nil nil nil
  20335. (if (= (line-end-position) (match-end 0)) 0 1)))
  20336. (forward-line)))
  20337. (let ((min-ind (point-max)))
  20338. ;; Find minimum indentation across all lines.
  20339. (save-excursion
  20340. (goto-char begin)
  20341. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  20342. (setq min-ind 0)
  20343. (catch 'zerop
  20344. (while (< (point) end)
  20345. (unless (looking-at-p "[ \t]*$")
  20346. (let ((ind (org-get-indentation)))
  20347. (setq min-ind (min min-ind ind))
  20348. (when (zerop ind) (throw 'zerop t))))
  20349. (forward-line)))))
  20350. ;; Loop over all lines and add fixed-width markup everywhere
  20351. ;; but in fixed-width lines.
  20352. (save-excursion
  20353. (goto-char begin)
  20354. (while (< (point) end)
  20355. (cond
  20356. ((org-at-heading-p)
  20357. (insert ": ")
  20358. (forward-line)
  20359. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  20360. (insert ":")
  20361. (forward-line)))
  20362. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  20363. (let* ((element (org-element-at-point))
  20364. (element-end (org-element-property :end element)))
  20365. (if (eq (org-element-type element) 'fixed-width)
  20366. (progn (goto-char element-end)
  20367. (skip-chars-backward " \r\t\n")
  20368. (forward-line))
  20369. (let ((limit (min end element-end)))
  20370. (while (< (point) limit)
  20371. (org-move-to-column min-ind t)
  20372. (insert ": ")
  20373. (forward-line))))))
  20374. (t
  20375. (org-move-to-column min-ind t)
  20376. (insert ": ")
  20377. (forward-line)))))))
  20378. (set-marker end nil))))
  20379. ;;; Blocks
  20380. (defun org-block-map (function &optional start end)
  20381. "Call FUNCTION at the head of all source blocks in the current buffer.
  20382. Optional arguments START and END can be used to limit the range."
  20383. (let ((start (or start (point-min)))
  20384. (end (or end (point-max))))
  20385. (save-excursion
  20386. (goto-char start)
  20387. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  20388. (save-excursion
  20389. (save-match-data
  20390. (goto-char (match-beginning 0))
  20391. (funcall function)))))))
  20392. (defun org-next-block (arg &optional backward block-regexp)
  20393. "Jump to the next block.
  20394. With a prefix argument ARG, jump forward ARG many blocks.
  20395. When BACKWARD is non-nil, jump to the previous block.
  20396. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  20397. Match data is set according to this regexp when the function
  20398. returns.
  20399. Return point at beginning of the opening line of found block.
  20400. Throw an error if no block is found."
  20401. (interactive "p")
  20402. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  20403. (case-fold-search t)
  20404. (search-fn (if backward #'re-search-backward #'re-search-forward))
  20405. (count (or arg 1))
  20406. (origin (point))
  20407. last-element)
  20408. (if backward (beginning-of-line) (end-of-line))
  20409. (while (and (> count 0) (funcall search-fn re nil t))
  20410. (let ((element (save-excursion
  20411. (goto-char (match-beginning 0))
  20412. (save-match-data (org-element-at-point)))))
  20413. (when (and (memq (org-element-type element)
  20414. '(center-block comment-block dynamic-block
  20415. example-block export-block quote-block
  20416. special-block src-block verse-block))
  20417. (<= (match-beginning 0)
  20418. (org-element-property :post-affiliated element)))
  20419. (setq last-element element)
  20420. (cl-decf count))))
  20421. (if (= count 0)
  20422. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  20423. (save-match-data (org-show-context)))
  20424. (goto-char origin)
  20425. (user-error "No %s code blocks" (if backward "previous" "further")))))
  20426. (defun org-previous-block (arg &optional block-regexp)
  20427. "Jump to the previous block.
  20428. With a prefix argument ARG, jump backward ARG many source blocks.
  20429. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  20430. (interactive "p")
  20431. (org-next-block arg t block-regexp))
  20432. ;;; Comments
  20433. ;; Org comments syntax is quite complex. It requires the entire line
  20434. ;; to be just a comment. Also, even with the right syntax at the
  20435. ;; beginning of line, some elements (e.g., verse-block or
  20436. ;; example-block) don't accept comments. Usual Emacs comment commands
  20437. ;; cannot cope with those requirements. Therefore, Org replaces them.
  20438. ;; Org still relies on `comment-dwim', but cannot trust
  20439. ;; `comment-only-p'. So, `comment-region-function' and
  20440. ;; `uncomment-region-function' both point
  20441. ;; to`org-comment-or-uncomment-region'. Eventually,
  20442. ;; `org-insert-comment' takes care of insertion of comments at the
  20443. ;; beginning of line.
  20444. ;; `org-setup-comments-handling' install comments related variables
  20445. ;; during `org-mode' initialization.
  20446. (defun org-setup-comments-handling ()
  20447. (interactive)
  20448. (setq-local comment-use-syntax nil)
  20449. (setq-local comment-start "# ")
  20450. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  20451. (setq-local comment-insert-comment-function 'org-insert-comment)
  20452. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  20453. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  20454. (defun org-insert-comment ()
  20455. "Insert an empty comment above current line.
  20456. If the line is empty, insert comment at its beginning. When
  20457. point is within a source block, comment according to the related
  20458. major mode."
  20459. (if (let ((element (org-element-at-point)))
  20460. (and (eq (org-element-type element) 'src-block)
  20461. (< (save-excursion
  20462. (goto-char (org-element-property :post-affiliated element))
  20463. (line-end-position))
  20464. (point))
  20465. (> (save-excursion
  20466. (goto-char (org-element-property :end element))
  20467. (skip-chars-backward " \r\t\n")
  20468. (line-beginning-position))
  20469. (point))))
  20470. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  20471. (beginning-of-line)
  20472. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  20473. (open-line 1))
  20474. (org-indent-line)
  20475. (insert "# ")))
  20476. (defvar comment-empty-lines) ; From newcomment.el.
  20477. (defun org-comment-or-uncomment-region (beg end &rest _)
  20478. "Comment or uncomment each non-blank line in the region.
  20479. Uncomment each non-blank line between BEG and END if it only
  20480. contains commented lines. Otherwise, comment them. If region is
  20481. strictly within a source block, use appropriate comment syntax."
  20482. (if (let ((element (org-element-at-point)))
  20483. (and (eq (org-element-type element) 'src-block)
  20484. (< (save-excursion
  20485. (goto-char (org-element-property :post-affiliated element))
  20486. (line-end-position))
  20487. beg)
  20488. (>= (save-excursion
  20489. (goto-char (org-element-property :end element))
  20490. (skip-chars-backward " \r\t\n")
  20491. (line-beginning-position))
  20492. end)))
  20493. ;; Translate region boundaries for the Org buffer to the source
  20494. ;; buffer.
  20495. (let ((offset (- end beg)))
  20496. (save-excursion
  20497. (goto-char beg)
  20498. (org-babel-do-in-edit-buffer
  20499. (comment-or-uncomment-region (point) (+ offset (point))))))
  20500. (save-restriction
  20501. ;; Restrict region
  20502. (narrow-to-region (save-excursion (goto-char beg)
  20503. (skip-chars-forward " \r\t\n" end)
  20504. (line-beginning-position))
  20505. (save-excursion (goto-char end)
  20506. (skip-chars-backward " \r\t\n" beg)
  20507. (line-end-position)))
  20508. (let ((uncommentp
  20509. ;; UNCOMMENTP is non-nil when every non blank line between
  20510. ;; BEG and END is a comment.
  20511. (save-excursion
  20512. (goto-char (point-min))
  20513. (while (and (not (eobp))
  20514. (let ((element (org-element-at-point)))
  20515. (and (eq (org-element-type element) 'comment)
  20516. (goto-char (min (point-max)
  20517. (org-element-property
  20518. :end element)))))))
  20519. (eobp))))
  20520. (if uncommentp
  20521. ;; Only blank lines and comments in region: uncomment it.
  20522. (save-excursion
  20523. (goto-char (point-min))
  20524. (while (not (eobp))
  20525. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  20526. (replace-match "" nil nil nil 1))
  20527. (forward-line)))
  20528. ;; Comment each line in region.
  20529. (let ((min-indent (point-max)))
  20530. ;; First find the minimum indentation across all lines.
  20531. (save-excursion
  20532. (goto-char (point-min))
  20533. (while (and (not (eobp)) (not (zerop min-indent)))
  20534. (unless (looking-at "[ \t]*$")
  20535. (setq min-indent (min min-indent (current-indentation))))
  20536. (forward-line)))
  20537. ;; Then loop over all lines.
  20538. (save-excursion
  20539. (goto-char (point-min))
  20540. (while (not (eobp))
  20541. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  20542. ;; Don't get fooled by invisible text (e.g. link path)
  20543. ;; when moving to column MIN-INDENT.
  20544. (let ((buffer-invisibility-spec nil))
  20545. (org-move-to-column min-indent t))
  20546. (insert comment-start))
  20547. (forward-line)))))))))
  20548. (defun org-comment-dwim (_arg)
  20549. "Call the comment command you mean.
  20550. Call `org-toggle-comment' if on a heading, otherwise call
  20551. `comment-dwim', within a source edit buffer if needed."
  20552. (interactive "*P")
  20553. (cond ((org-at-heading-p)
  20554. (call-interactively #'org-toggle-comment))
  20555. ((org-in-src-block-p)
  20556. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  20557. (t (call-interactively #'comment-dwim))))
  20558. ;;; Timestamps API
  20559. ;; This section contains tools to operate on, or create, timestamp
  20560. ;; objects, as returned by, e.g. `org-element-context'.
  20561. (defun org-timestamp-from-string (s)
  20562. "Convert Org timestamp S, as a string, into a timestamp object.
  20563. Return nil if S is not a valid timestamp string."
  20564. (when (org-string-nw-p s)
  20565. (with-temp-buffer
  20566. (save-excursion (insert s))
  20567. (org-element-timestamp-parser))))
  20568. (defun org-timestamp-from-time (time &optional with-time inactive)
  20569. "Convert a time value into a timestamp object.
  20570. TIME is an Emacs internal time representation, as returned, e.g.,
  20571. by `current-time'.
  20572. When optional argument WITH-TIME is non-nil, return a timestamp
  20573. object with a time part, i.e., with hours and minutes.
  20574. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  20575. return an active timestamp."
  20576. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  20577. (org-element-create 'timestamp
  20578. (list :type (if inactive 'inactive 'active)
  20579. :year-start year
  20580. :month-start month
  20581. :day-start day
  20582. :hour-start (and with-time hour)
  20583. :minute-start (and with-time minute)))))
  20584. (defun org-timestamp-to-time (timestamp &optional end)
  20585. "Convert TIMESTAMP object into an Emacs internal time value.
  20586. Use end of date range or time range when END is non-nil.
  20587. Otherwise, use its start."
  20588. (apply #'encode-time
  20589. (cons 0
  20590. (mapcar
  20591. (lambda (prop) (or (org-element-property prop timestamp) 0))
  20592. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  20593. '(:minute-start :hour-start :day-start :month-start
  20594. :year-start))))))
  20595. (defun org-timestamp-has-time-p (timestamp)
  20596. "Non-nil when TIMESTAMP has a time specified."
  20597. (org-element-property :hour-start timestamp))
  20598. (defun org-timestamp-format (timestamp format &optional end utc)
  20599. "Format a TIMESTAMP object into a string.
  20600. FORMAT is a format specifier to be passed to
  20601. `format-time-string'.
  20602. When optional argument END is non-nil, use end of date-range or
  20603. time-range, if possible.
  20604. When optional argument UTC is non-nil, time is be expressed as
  20605. Universal Time."
  20606. (format-time-string format (org-timestamp-to-time timestamp end)
  20607. (and utc t)))
  20608. (defun org-timestamp-split-range (timestamp &optional end)
  20609. "Extract a TIMESTAMP object from a date or time range.
  20610. END, when non-nil, means extract the end of the range.
  20611. Otherwise, extract its start.
  20612. Return a new timestamp object."
  20613. (let ((type (org-element-property :type timestamp)))
  20614. (if (memq type '(active inactive diary)) timestamp
  20615. (let ((split-ts (org-element-copy timestamp)))
  20616. ;; Set new type.
  20617. (org-element-put-property
  20618. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  20619. ;; Copy start properties over end properties if END is
  20620. ;; non-nil. Otherwise, copy end properties over `start' ones.
  20621. (let ((p-alist '((:minute-start . :minute-end)
  20622. (:hour-start . :hour-end)
  20623. (:day-start . :day-end)
  20624. (:month-start . :month-end)
  20625. (:year-start . :year-end))))
  20626. (dolist (p-cell p-alist)
  20627. (org-element-put-property
  20628. split-ts
  20629. (funcall (if end #'car #'cdr) p-cell)
  20630. (org-element-property
  20631. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  20632. ;; Eventually refresh `:raw-value'.
  20633. (org-element-put-property split-ts :raw-value nil)
  20634. (org-element-put-property
  20635. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  20636. (defun org-timestamp-translate (timestamp &optional boundary)
  20637. "Translate TIMESTAMP object to custom format.
  20638. Format string is defined in `org-time-stamp-custom-formats',
  20639. which see.
  20640. When optional argument BOUNDARY is non-nil, it is either the
  20641. symbol `start' or `end'. In this case, only translate the
  20642. starting or ending part of TIMESTAMP if it is a date or time
  20643. range. Otherwise, translate both parts.
  20644. Return timestamp as-is if `org-display-custom-times' is nil or if
  20645. it has a `diary' type."
  20646. (let ((type (org-element-property :type timestamp)))
  20647. (if (or (not org-display-custom-times) (eq type 'diary))
  20648. (org-element-interpret-data timestamp)
  20649. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  20650. org-time-stamp-custom-formats)))
  20651. (if (and (not boundary) (memq type '(active-range inactive-range)))
  20652. (concat (org-timestamp-format timestamp fmt)
  20653. "--"
  20654. (org-timestamp-format timestamp fmt t))
  20655. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  20656. ;;; Other stuff
  20657. (defvar reftex-docstruct-symbol)
  20658. (defvar org--rds)
  20659. (defun org-reftex-citation ()
  20660. "Use reftex-citation to insert a citation into the buffer.
  20661. This looks for a line like
  20662. #+BIBLIOGRAPHY: foo plain option:-d
  20663. and derives from it that foo.bib is the bibliography file relevant
  20664. for this document. It then installs the necessary environment for RefTeX
  20665. to work in this buffer and calls `reftex-citation' to insert a citation
  20666. into the buffer.
  20667. Export of such citations to both LaTeX and HTML is handled by the contributed
  20668. package ox-bibtex by Taru Karttunen."
  20669. (interactive)
  20670. (let ((reftex-docstruct-symbol 'org--rds)
  20671. org--rds bib)
  20672. (org-with-wide-buffer
  20673. (let ((case-fold-search t)
  20674. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  20675. (if (not (save-excursion
  20676. (or (re-search-forward re nil t)
  20677. (re-search-backward re nil t))))
  20678. (user-error "No bibliography defined in file")
  20679. (setq bib (concat (match-string 1) ".bib")
  20680. org--rds (list (list 'bib bib))))))
  20681. (call-interactively 'reftex-citation)))
  20682. ;;;; Functions extending outline functionality
  20683. (defun org-beginning-of-line (&optional n)
  20684. "Go to the beginning of the current visible line.
  20685. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  20686. symbol `reversed', on the first attempt move to where the
  20687. headline text starts, and only move to beginning of line when the
  20688. cursor is already before the start of the text of the headline.
  20689. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  20690. start of the text on the second attempt.
  20691. With argument N not nil or 1, move forward N - 1 lines first."
  20692. (interactive "^p")
  20693. (let ((origin (point))
  20694. (special (pcase org-special-ctrl-a/e
  20695. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  20696. deactivate-mark)
  20697. ;; First move to a visible line.
  20698. (if (bound-and-true-p visual-line-mode)
  20699. (beginning-of-visual-line n)
  20700. (move-beginning-of-line n)
  20701. ;; `move-beginning-of-line' may leave point after invisible
  20702. ;; characters if line starts with such of these (e.g., with
  20703. ;; a link at column 0). Really move to the beginning of the
  20704. ;; current visible line.
  20705. (beginning-of-line))
  20706. (cond
  20707. ;; No special behavior. Point is already at the beginning of
  20708. ;; a line, logical or visual.
  20709. ((not special))
  20710. ;; `beginning-of-visual-line' left point before logical beginning
  20711. ;; of line: point is at the beginning of a visual line. Bail
  20712. ;; out.
  20713. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  20714. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  20715. ;; At a headline, special position is before the title, but
  20716. ;; after any TODO keyword or priority cookie.
  20717. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  20718. (line-end-position)))
  20719. (bol (point)))
  20720. (if (eq special 'reversed)
  20721. (when (and (= origin bol) (eq last-command this-command))
  20722. (goto-char refpos))
  20723. (when (or (> origin refpos) (= origin bol))
  20724. (goto-char refpos)))))
  20725. ((and (looking-at org-list-full-item-re)
  20726. (memq (org-element-type (save-match-data (org-element-at-point)))
  20727. '(item plain-list)))
  20728. ;; Set special position at first white space character after
  20729. ;; bullet, and check-box, if any.
  20730. (let ((after-bullet
  20731. (let ((box (match-end 3)))
  20732. (cond ((not box) (match-end 1))
  20733. ((eq (char-after box) ?\s) (1+ box))
  20734. (t box)))))
  20735. (if (eq special 'reversed)
  20736. (when (and (= (point) origin) (eq last-command this-command))
  20737. (goto-char after-bullet))
  20738. (when (or (> origin after-bullet) (= (point) origin))
  20739. (goto-char after-bullet)))))
  20740. ;; No special context. Point is already at beginning of line.
  20741. (t nil))))
  20742. (defun org-end-of-line (&optional n)
  20743. "Go to the end of the line, but before ellipsis, if any.
  20744. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  20745. symbol `reversed', ignore tags on the first attempt, and only
  20746. move to after the tags when the cursor is already beyond the end
  20747. of the headline.
  20748. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  20749. on the second attempt.
  20750. With argument N not nil or 1, move forward N - 1 lines first."
  20751. (interactive "^p")
  20752. (let ((origin (point))
  20753. (special (pcase org-special-ctrl-a/e
  20754. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  20755. deactivate-mark)
  20756. ;; First move to a visible line.
  20757. (if (bound-and-true-p visual-line-mode)
  20758. (beginning-of-visual-line n)
  20759. (move-beginning-of-line n))
  20760. (cond
  20761. ;; At a headline, with tags.
  20762. ((and special
  20763. (save-excursion
  20764. (beginning-of-line)
  20765. (let ((case-fold-search nil))
  20766. (looking-at org-complex-heading-regexp)))
  20767. (match-end 5))
  20768. (let ((tags (save-excursion
  20769. (goto-char (match-beginning 5))
  20770. (skip-chars-backward " \t")
  20771. (point)))
  20772. (visual-end (and (bound-and-true-p visual-line-mode)
  20773. (save-excursion
  20774. (end-of-visual-line)
  20775. (point)))))
  20776. ;; If `end-of-visual-line' brings us before end of line or
  20777. ;; even tags, i.e., the headline spans over multiple visual
  20778. ;; lines, move there.
  20779. (cond ((and visual-end
  20780. (< visual-end tags)
  20781. (<= origin visual-end))
  20782. (goto-char visual-end))
  20783. ((eq special 'reversed)
  20784. (if (and (= origin (line-end-position))
  20785. (eq this-command last-command))
  20786. (goto-char tags)
  20787. (end-of-line)))
  20788. (t
  20789. (if (or (< origin tags) (= origin (line-end-position)))
  20790. (goto-char tags)
  20791. (end-of-line))))))
  20792. ((bound-and-true-p visual-line-mode)
  20793. (let ((bol (line-beginning-position)))
  20794. (end-of-visual-line)
  20795. ;; If `end-of-visual-line' gets us past the ellipsis at the
  20796. ;; end of a line, backtrack and use `end-of-line' instead.
  20797. (when (/= bol (line-beginning-position))
  20798. (goto-char bol)
  20799. (end-of-line))))
  20800. (t (end-of-line)))))
  20801. (defun org-backward-sentence (&optional _arg)
  20802. "Go to beginning of sentence, or beginning of table field.
  20803. This will call `backward-sentence' or `org-table-beginning-of-field',
  20804. depending on context."
  20805. (interactive)
  20806. (let* ((element (org-element-at-point))
  20807. (contents-begin (org-element-property :contents-begin element))
  20808. (table (org-element-lineage element '(table) t)))
  20809. (if (and table
  20810. (> (point) contents-begin)
  20811. (<= (point) (org-element-property :contents-end table)))
  20812. (call-interactively #'org-table-beginning-of-field)
  20813. (save-restriction
  20814. (when (and contents-begin
  20815. (< (point-min) contents-begin)
  20816. (> (point) contents-begin))
  20817. (narrow-to-region contents-begin
  20818. (org-element-property :contents-end element)))
  20819. (call-interactively #'backward-sentence)))))
  20820. (defun org-forward-sentence (&optional _arg)
  20821. "Go to end of sentence, or end of table field.
  20822. This will call `forward-sentence' or `org-table-end-of-field',
  20823. depending on context."
  20824. (interactive)
  20825. (if (and (org-at-heading-p)
  20826. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  20827. (save-restriction
  20828. (narrow-to-region (line-beginning-position) (line-end-position))
  20829. (call-interactively #'forward-sentence))
  20830. (let* ((element (org-element-at-point))
  20831. (contents-end (org-element-property :contents-end element))
  20832. (table (org-element-lineage element '(table) t)))
  20833. (if (and table
  20834. (>= (point) (org-element-property :contents-begin table))
  20835. (< (point) contents-end))
  20836. (call-interactively #'org-table-end-of-field)
  20837. (save-restriction
  20838. (when (and contents-end
  20839. (> (point-max) contents-end)
  20840. ;; Skip blank lines between elements.
  20841. (< (org-element-property :end element)
  20842. (save-excursion (goto-char contents-end)
  20843. (skip-chars-forward " \r\t\n"))))
  20844. (narrow-to-region (org-element-property :contents-begin element)
  20845. contents-end))
  20846. ;; End of heading is considered as the end of a sentence.
  20847. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  20848. (call-interactively #'forward-sentence)))))))
  20849. (defun org-kill-line (&optional _arg)
  20850. "Kill line, to tags or end of line."
  20851. (interactive)
  20852. (cond
  20853. ((or (not org-special-ctrl-k)
  20854. (bolp)
  20855. (not (org-at-heading-p)))
  20856. (when (and (get-char-property (line-end-position) 'invisible)
  20857. org-ctrl-k-protect-subtree
  20858. (or (eq org-ctrl-k-protect-subtree 'error)
  20859. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  20860. (user-error
  20861. (substitute-command-keys
  20862. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  20863. (call-interactively
  20864. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  20865. ((looking-at org-tag-line-re)
  20866. (let ((end (save-excursion
  20867. (goto-char (match-beginning 1))
  20868. (skip-chars-backward " \t"))))
  20869. (if (<= end (point)) ;on tags part
  20870. (kill-region (point) (line-end-position))
  20871. (kill-region (point) end)))
  20872. (org-set-tags nil t))
  20873. (t (kill-region (point) (line-end-position)))))
  20874. (defun org-yank (&optional arg)
  20875. "Yank. If the kill is a subtree, treat it specially.
  20876. This command will look at the current kill and check if is a single
  20877. subtree, or a series of subtrees[1]. If it passes the test, and if the
  20878. cursor is at the beginning of a line or after the stars of a currently
  20879. empty headline, then the yank is handled specially. How exactly depends
  20880. on the value of the following variables.
  20881. `org-yank-folded-subtrees'
  20882. By default, this variable is non-nil, which results in
  20883. subtree(s) being folded after insertion, except if doing so
  20884. would swallow text after the yanked text.
  20885. `org-yank-adjusted-subtrees'
  20886. When non-nil (the default value is nil), the subtree will be
  20887. promoted or demoted in order to fit into the local outline tree
  20888. structure, which means that the level will be adjusted so that it
  20889. becomes the smaller one of the two *visible* surrounding headings.
  20890. Any prefix to this command will cause `yank' to be called directly with
  20891. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  20892. will just
  20893. plainly yank the text as it is.
  20894. \[1] The test checks if the first non-white line is a heading
  20895. and if there are no other headings with fewer stars."
  20896. (interactive "P")
  20897. (org-yank-generic 'yank arg))
  20898. (defun org-yank-generic (command arg)
  20899. "Perform some yank-like command.
  20900. This function implements the behavior described in the `org-yank'
  20901. documentation. However, it has been generalized to work for any
  20902. interactive command with similar behavior."
  20903. ;; pretend to be command COMMAND
  20904. (setq this-command command)
  20905. (if arg
  20906. (call-interactively command)
  20907. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  20908. (and (org-kill-is-subtree-p)
  20909. (or (bolp)
  20910. (and (looking-at "[ \t]*$")
  20911. (string-match
  20912. "\\`\\*+\\'"
  20913. (buffer-substring (point-at-bol) (point)))))))
  20914. swallowp)
  20915. (cond
  20916. ((and subtreep org-yank-folded-subtrees)
  20917. (let ((beg (point))
  20918. end)
  20919. (if (and subtreep org-yank-adjusted-subtrees)
  20920. (org-paste-subtree nil nil 'for-yank)
  20921. (call-interactively command))
  20922. (setq end (point))
  20923. (goto-char beg)
  20924. (when (and (bolp) subtreep
  20925. (not (setq swallowp
  20926. (org-yank-folding-would-swallow-text beg end))))
  20927. (org-with-limited-levels
  20928. (or (looking-at org-outline-regexp)
  20929. (re-search-forward org-outline-regexp-bol end t))
  20930. (while (and (< (point) end) (looking-at org-outline-regexp))
  20931. (outline-hide-subtree)
  20932. (org-cycle-show-empty-lines 'folded)
  20933. (condition-case nil
  20934. (outline-forward-same-level 1)
  20935. (error (goto-char end))))))
  20936. (when swallowp
  20937. (message
  20938. "Inserted text not folded because that would swallow text"))
  20939. (goto-char end)
  20940. (skip-chars-forward " \t\n\r")
  20941. (beginning-of-line 1)
  20942. (push-mark beg 'nomsg)))
  20943. ((and subtreep org-yank-adjusted-subtrees)
  20944. (let ((beg (point-at-bol)))
  20945. (org-paste-subtree nil nil 'for-yank)
  20946. (push-mark beg 'nomsg)))
  20947. (t
  20948. (call-interactively command))))))
  20949. (defun org-yank-folding-would-swallow-text (beg end)
  20950. "Would hide-subtree at BEG swallow any text after END?"
  20951. (let (level)
  20952. (org-with-limited-levels
  20953. (save-excursion
  20954. (goto-char beg)
  20955. (when (or (looking-at org-outline-regexp)
  20956. (re-search-forward org-outline-regexp-bol end t))
  20957. (setq level (org-outline-level)))
  20958. (goto-char end)
  20959. (skip-chars-forward " \t\r\n\v\f")
  20960. (not (or (eobp)
  20961. (and (bolp) (looking-at-p org-outline-regexp)
  20962. (<= (org-outline-level) level))))))))
  20963. (defun org-back-to-heading (&optional invisible-ok)
  20964. "Call `outline-back-to-heading', but provide a better error message."
  20965. (condition-case nil
  20966. (outline-back-to-heading invisible-ok)
  20967. (error (error "Before first headline at position %d in buffer %s"
  20968. (point) (current-buffer)))))
  20969. (defun org-before-first-heading-p ()
  20970. "Before first heading?"
  20971. (save-excursion
  20972. (end-of-line)
  20973. (null (re-search-backward org-outline-regexp-bol nil t))))
  20974. (defun org-at-heading-p (&optional ignored)
  20975. (outline-on-heading-p t))
  20976. (defun org-in-commented-heading-p (&optional no-inheritance)
  20977. "Non-nil if point is under a commented heading.
  20978. This function also checks ancestors of the current headline,
  20979. unless optional argument NO-INHERITANCE is non-nil."
  20980. (cond
  20981. ((org-before-first-heading-p) nil)
  20982. ((let ((headline (nth 4 (org-heading-components))))
  20983. (and headline
  20984. (let ((case-fold-search nil))
  20985. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  20986. headline)))))
  20987. (no-inheritance nil)
  20988. (t
  20989. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  20990. (defun org-at-comment-p nil
  20991. "Is cursor in a commented line?"
  20992. (save-excursion
  20993. (save-match-data
  20994. (beginning-of-line)
  20995. (looking-at "^[ \t]*# "))))
  20996. (defun org-at-drawer-p nil
  20997. "Is cursor at a drawer keyword?"
  20998. (save-excursion
  20999. (move-beginning-of-line 1)
  21000. (looking-at org-drawer-regexp)))
  21001. (defun org-at-block-p nil
  21002. "Is cursor at a block keyword?"
  21003. (save-excursion
  21004. (move-beginning-of-line 1)
  21005. (looking-at org-block-regexp)))
  21006. (defun org-point-at-end-of-empty-headline ()
  21007. "If point is at the end of an empty headline, return t, else nil.
  21008. If the heading only contains a TODO keyword, it is still still considered
  21009. empty."
  21010. (let ((case-fold-search nil))
  21011. (and (looking-at "[ \t]*$")
  21012. org-todo-line-regexp
  21013. (save-excursion
  21014. (beginning-of-line)
  21015. (looking-at org-todo-line-regexp)
  21016. (string= (match-string 3) "")))))
  21017. (defun org-at-heading-or-item-p ()
  21018. (or (org-at-heading-p) (org-at-item-p)))
  21019. (defun org-at-target-p ()
  21020. (or (org-in-regexp org-radio-target-regexp)
  21021. (org-in-regexp org-target-regexp)))
  21022. ;; Compatibility alias with Org versions < 7.8.03
  21023. (defalias 'org-on-target-p 'org-at-target-p)
  21024. (defun org-up-heading-all (arg)
  21025. "Move to the heading line of which the present line is a subheading.
  21026. This function considers both visible and invisible heading lines.
  21027. With argument, move up ARG levels."
  21028. (outline-up-heading arg t))
  21029. (defun org-up-heading-safe ()
  21030. "Move to the heading line of which the present line is a subheading.
  21031. This version will not throw an error. It will return the level of the
  21032. headline found, or nil if no higher level is found.
  21033. Also, this function will be a lot faster than `outline-up-heading',
  21034. because it relies on stars being the outline starters. This can really
  21035. make a significant difference in outlines with very many siblings."
  21036. (when (ignore-errors (org-back-to-heading t))
  21037. (let ((level-up (1- (funcall outline-level))))
  21038. (and (> level-up 0)
  21039. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  21040. (funcall outline-level)))))
  21041. (defun org-first-sibling-p ()
  21042. "Is this heading the first child of its parents?"
  21043. (interactive)
  21044. (let ((re org-outline-regexp-bol)
  21045. level l)
  21046. (unless (org-at-heading-p t)
  21047. (user-error "Not at a heading"))
  21048. (setq level (funcall outline-level))
  21049. (save-excursion
  21050. (if (not (re-search-backward re nil t))
  21051. t
  21052. (setq l (funcall outline-level))
  21053. (< l level)))))
  21054. (defun org-goto-sibling (&optional previous)
  21055. "Goto the next sibling, even if it is invisible.
  21056. When PREVIOUS is set, go to the previous sibling instead. Returns t
  21057. when a sibling was found. When none is found, return nil and don't
  21058. move point."
  21059. (let ((fun (if previous 're-search-backward 're-search-forward))
  21060. (pos (point))
  21061. (re org-outline-regexp-bol)
  21062. level l)
  21063. (when (ignore-errors (org-back-to-heading t))
  21064. (setq level (funcall outline-level))
  21065. (catch 'exit
  21066. (or previous (forward-char 1))
  21067. (while (funcall fun re nil t)
  21068. (setq l (funcall outline-level))
  21069. (when (< l level) (goto-char pos) (throw 'exit nil))
  21070. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21071. (goto-char pos)
  21072. nil))))
  21073. (defun org-show-siblings ()
  21074. "Show all siblings of the current headline."
  21075. (save-excursion
  21076. (while (org-goto-sibling) (org-flag-heading nil)))
  21077. (save-excursion
  21078. (while (org-goto-sibling 'previous)
  21079. (org-flag-heading nil))))
  21080. (defun org-goto-first-child ()
  21081. "Goto the first child, even if it is invisible.
  21082. Return t when a child was found. Otherwise don't move point and
  21083. return nil."
  21084. (let (level (pos (point)) (re org-outline-regexp-bol))
  21085. (when (ignore-errors (org-back-to-heading t))
  21086. (setq level (outline-level))
  21087. (forward-char 1)
  21088. (if (and (re-search-forward re nil t) (> (outline-level) level))
  21089. (progn (goto-char (match-beginning 0)) t)
  21090. (goto-char pos) nil))))
  21091. (defun org-show-hidden-entry ()
  21092. "Show an entry where even the heading is hidden."
  21093. (save-excursion
  21094. (org-show-entry)))
  21095. (defun org-flag-heading (flag &optional entry)
  21096. "Flag the current heading. FLAG non-nil means make invisible.
  21097. When ENTRY is non-nil, show the entire entry."
  21098. (save-excursion
  21099. (org-back-to-heading t)
  21100. ;; Check if we should show the entire entry
  21101. (if (not entry)
  21102. (org-flag-region
  21103. (line-end-position 0) (line-end-position) flag 'outline)
  21104. (org-show-entry)
  21105. (save-excursion
  21106. (and (outline-next-heading)
  21107. (org-flag-heading nil))))))
  21108. (defun org-get-next-sibling ()
  21109. "Move to next heading of the same level, and return point.
  21110. If there is no such heading, return nil.
  21111. This is like outline-next-sibling, but invisible headings are ok."
  21112. (let ((level (funcall outline-level)))
  21113. (outline-next-heading)
  21114. (while (and (not (eobp)) (> (funcall outline-level) level))
  21115. (outline-next-heading))
  21116. (unless (or (eobp) (< (funcall outline-level) level))
  21117. (point))))
  21118. (defun org-get-last-sibling ()
  21119. "Move to previous heading of the same level, and return point.
  21120. If there is no such heading, return nil."
  21121. (let ((opoint (point))
  21122. (level (funcall outline-level)))
  21123. (outline-previous-heading)
  21124. (when (and (/= (point) opoint) (outline-on-heading-p t))
  21125. (while (and (> (funcall outline-level) level)
  21126. (not (bobp)))
  21127. (outline-previous-heading))
  21128. (unless (< (funcall outline-level) level)
  21129. (point)))))
  21130. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  21131. "Goto to the end of a subtree."
  21132. ;; This contains an exact copy of the original function, but it uses
  21133. ;; `org-back-to-heading', to make it work also in invisible
  21134. ;; trees. And is uses an invisible-ok argument.
  21135. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  21136. ;; Furthermore, when used inside Org, finding the end of a large subtree
  21137. ;; with many children and grandchildren etc, this can be much faster
  21138. ;; than the outline version.
  21139. (org-back-to-heading invisible-ok)
  21140. (let ((first t)
  21141. (level (funcall outline-level)))
  21142. (if (and (derived-mode-p 'org-mode) (< level 1000))
  21143. ;; A true heading (not a plain list item), in Org
  21144. ;; This means we can easily find the end by looking
  21145. ;; only for the right number of stars. Using a regexp to do
  21146. ;; this is so much faster than using a Lisp loop.
  21147. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  21148. (forward-char 1)
  21149. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  21150. ;; something else, do it the slow way
  21151. (while (and (not (eobp))
  21152. (or first (> (funcall outline-level) level)))
  21153. (setq first nil)
  21154. (outline-next-heading)))
  21155. (unless to-heading
  21156. (when (memq (preceding-char) '(?\n ?\^M))
  21157. ;; Go to end of line before heading
  21158. (forward-char -1)
  21159. (when (memq (preceding-char) '(?\n ?\^M))
  21160. ;; leave blank line before heading
  21161. (forward-char -1)))))
  21162. (point))
  21163. (defun org-end-of-meta-data (&optional full)
  21164. "Skip planning line and properties drawer in current entry.
  21165. When optional argument FULL is non-nil, also skip empty lines,
  21166. clocking lines and regular drawers at the beginning of the
  21167. entry."
  21168. (org-back-to-heading t)
  21169. (forward-line)
  21170. (when (looking-at-p org-planning-line-re) (forward-line))
  21171. (when (looking-at org-property-drawer-re)
  21172. (goto-char (match-end 0))
  21173. (forward-line))
  21174. (when (and full (not (org-at-heading-p)))
  21175. (catch 'exit
  21176. (let ((end (save-excursion (outline-next-heading) (point)))
  21177. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  21178. (while (not (eobp))
  21179. (cond ((looking-at-p org-drawer-regexp)
  21180. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21181. (forward-line)
  21182. (throw 'exit t)))
  21183. ((looking-at-p re) (forward-line))
  21184. (t (throw 'exit t))))))))
  21185. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  21186. "Move forward to the ARG'th subheading at same level as this one.
  21187. Stop at the first and last subheadings of a superior heading.
  21188. Normally this only looks at visible headings, but when INVISIBLE-OK is
  21189. non-nil it will also look at invisible ones."
  21190. (interactive "p")
  21191. (let ((backward? (and arg (< arg 0))))
  21192. (if (org-before-first-heading-p)
  21193. (if backward? (goto-char (point-min)) (outline-next-heading))
  21194. (org-back-to-heading invisible-ok)
  21195. (unless backward? (end-of-line)) ;do not match current headline
  21196. (let ((level (- (match-end 0) (match-beginning 0) 1))
  21197. (f (if backward? #'re-search-backward #'re-search-forward))
  21198. (count (if arg (abs arg) 1))
  21199. (result (point)))
  21200. (while (and (> count 0)
  21201. (funcall f org-outline-regexp-bol nil 'move))
  21202. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  21203. (cond ((< l level) (setq count 0))
  21204. ((and (= l level)
  21205. (or invisible-ok
  21206. (not (org-invisible-p
  21207. (line-beginning-position)))))
  21208. (cl-decf count)
  21209. (when (= l level) (setq result (point)))))))
  21210. (goto-char result))
  21211. (beginning-of-line))))
  21212. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  21213. "Move backward to the ARG'th subheading at same level as this one.
  21214. Stop at the first and last subheadings of a superior heading."
  21215. (interactive "p")
  21216. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  21217. (defun org-next-visible-heading (arg)
  21218. "Move to the next visible heading.
  21219. This function wraps `outline-next-visible-heading' with
  21220. `org-with-limited-levels' in order to skip over inline tasks and
  21221. respect customization of `org-odd-levels-only'."
  21222. (interactive "p")
  21223. (org-with-limited-levels
  21224. (outline-next-visible-heading arg)))
  21225. (defun org-previous-visible-heading (arg)
  21226. "Move to the previous visible heading.
  21227. This function wraps `outline-previous-visible-heading' with
  21228. `org-with-limited-levels' in order to skip over inline tasks and
  21229. respect customization of `org-odd-levels-only'."
  21230. (interactive "p")
  21231. (org-with-limited-levels
  21232. (outline-previous-visible-heading arg)))
  21233. (defun org-forward-paragraph ()
  21234. "Move forward to beginning of next paragraph or equivalent.
  21235. The function moves point to the beginning of the next visible
  21236. structural element, which can be a paragraph, a table, a list
  21237. item, etc. It also provides some special moves for convenience:
  21238. - On an affiliated keyword, jump to the beginning of the
  21239. relative element.
  21240. - On an item or a footnote definition, move to the second
  21241. element inside, if any.
  21242. - On a table or a property drawer, jump after it.
  21243. - On a verse or source block, stop after blank lines."
  21244. (interactive)
  21245. (unless (eobp)
  21246. (let* ((deactivate-mark nil)
  21247. (element (org-element-at-point))
  21248. (type (org-element-type element))
  21249. (post-affiliated (org-element-property :post-affiliated element))
  21250. (contents-begin (org-element-property :contents-begin element))
  21251. (contents-end (org-element-property :contents-end element))
  21252. (end (let ((end (org-element-property :end element)) (parent element))
  21253. (while (and (setq parent (org-element-property :parent parent))
  21254. (= (org-element-property :contents-end parent) end))
  21255. (setq end (org-element-property :end parent)))
  21256. end)))
  21257. (cond ((not element)
  21258. (skip-chars-forward " \r\t\n")
  21259. (or (eobp) (beginning-of-line)))
  21260. ;; On affiliated keywords, move to element's beginning.
  21261. ((< (point) post-affiliated)
  21262. (goto-char post-affiliated))
  21263. ;; At a table row, move to the end of the table. Similarly,
  21264. ;; at a node property, move to the end of the property
  21265. ;; drawer.
  21266. ((memq type '(node-property table-row))
  21267. (goto-char (org-element-property
  21268. :end (org-element-property :parent element))))
  21269. ((memq type '(property-drawer table)) (goto-char end))
  21270. ;; Consider blank lines as separators in verse and source
  21271. ;; blocks to ease editing.
  21272. ((memq type '(src-block verse-block))
  21273. (when (eq type 'src-block)
  21274. (setq contents-end
  21275. (save-excursion (goto-char end)
  21276. (skip-chars-backward " \r\t\n")
  21277. (line-beginning-position))))
  21278. (beginning-of-line)
  21279. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  21280. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  21281. (goto-char end)
  21282. (skip-chars-forward " \r\t\n")
  21283. (if (= (point) contents-end) (goto-char end)
  21284. (beginning-of-line))))
  21285. ;; With no contents, just skip element.
  21286. ((not contents-begin) (goto-char end))
  21287. ;; If contents are invisible, skip the element altogether.
  21288. ((org-invisible-p (line-end-position))
  21289. (cl-case type
  21290. (headline
  21291. (org-with-limited-levels (outline-next-visible-heading 1)))
  21292. ;; At a plain list, make sure we move to the next item
  21293. ;; instead of skipping the whole list.
  21294. (plain-list (forward-char)
  21295. (org-forward-paragraph))
  21296. (otherwise (goto-char end))))
  21297. ((>= (point) contents-end) (goto-char end))
  21298. ((>= (point) contents-begin)
  21299. ;; This can only happen on paragraphs and plain lists.
  21300. (cl-case type
  21301. (paragraph (goto-char end))
  21302. ;; At a plain list, try to move to second element in
  21303. ;; first item, if possible.
  21304. (plain-list (end-of-line)
  21305. (org-forward-paragraph))))
  21306. ;; When contents start on the middle of a line (e.g. in
  21307. ;; items and footnote definitions), try to reach first
  21308. ;; element starting after current line.
  21309. ((> (line-end-position) contents-begin)
  21310. (end-of-line)
  21311. (org-forward-paragraph))
  21312. (t (goto-char contents-begin))))))
  21313. (defun org-backward-paragraph ()
  21314. "Move backward to start of previous paragraph or equivalent.
  21315. The function moves point to the beginning of the current
  21316. structural element, which can be a paragraph, a table, a list
  21317. item, etc., or to the beginning of the previous visible one if
  21318. point is already there. It also provides some special moves for
  21319. convenience:
  21320. - On an affiliated keyword, jump to the first one.
  21321. - On a table or a property drawer, move to its beginning.
  21322. - On comment, example, export, src and verse blocks, stop
  21323. before blank lines."
  21324. (interactive)
  21325. (unless (bobp)
  21326. (let* ((deactivate-mark nil)
  21327. (element (org-element-at-point))
  21328. (type (org-element-type element))
  21329. (contents-end (org-element-property :contents-end element))
  21330. (post-affiliated (org-element-property :post-affiliated element))
  21331. (begin (org-element-property :begin element))
  21332. (special? ;blocks handled specially
  21333. (memq type '(comment-block example-block export-block src-block
  21334. verse-block)))
  21335. (contents-begin
  21336. (if special?
  21337. ;; These types have no proper contents. Fake line
  21338. ;; below the block opening line as contents beginning.
  21339. (save-excursion (goto-char begin) (line-beginning-position 2))
  21340. (org-element-property :contents-begin element))))
  21341. (cond
  21342. ((not element) (goto-char (point-min)))
  21343. ((= (point) begin)
  21344. (backward-char)
  21345. (org-backward-paragraph))
  21346. ((<= (point) post-affiliated) (goto-char begin))
  21347. ;; Special behavior: on a table or a property drawer, move to
  21348. ;; its beginning.
  21349. ((memq type '(node-property table-row))
  21350. (goto-char (org-element-property
  21351. :post-affiliated (org-element-property :parent element))))
  21352. (special?
  21353. (if (<= (point) contents-begin) (goto-char post-affiliated)
  21354. ;; Inside a verse block, see blank lines as paragraph
  21355. ;; separators.
  21356. (let ((origin (point)))
  21357. (skip-chars-backward " \r\t\n" contents-begin)
  21358. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  21359. (skip-chars-forward " \r\t\n" origin)
  21360. (if (= (point) origin) (goto-char contents-begin)
  21361. (beginning-of-line))))))
  21362. ((eq type 'paragraph) (goto-char contents-begin)
  21363. ;; When at first paragraph in an item or a footnote definition,
  21364. ;; move directly to beginning of line.
  21365. (let ((parent-contents
  21366. (org-element-property
  21367. :contents-begin (org-element-property :parent element))))
  21368. (when (and parent-contents (= parent-contents contents-begin))
  21369. (beginning-of-line))))
  21370. ;; At the end of a greater element, move to the beginning of
  21371. ;; the last element within.
  21372. ((and contents-end (>= (point) contents-end))
  21373. (goto-char (1- contents-end))
  21374. (org-backward-paragraph))
  21375. (t (goto-char (or post-affiliated begin))))
  21376. ;; Ensure we never leave point invisible.
  21377. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  21378. (defun org-forward-element ()
  21379. "Move forward by one element.
  21380. Move to the next element at the same level, when possible."
  21381. (interactive)
  21382. (cond ((eobp) (user-error "Cannot move further down"))
  21383. ((org-with-limited-levels (org-at-heading-p))
  21384. (let ((origin (point)))
  21385. (goto-char (org-end-of-subtree nil t))
  21386. (unless (org-with-limited-levels (org-at-heading-p))
  21387. (goto-char origin)
  21388. (user-error "Cannot move further down"))))
  21389. (t
  21390. (let* ((elem (org-element-at-point))
  21391. (end (org-element-property :end elem))
  21392. (parent (org-element-property :parent elem)))
  21393. (cond ((and parent (= (org-element-property :contents-end parent) end))
  21394. (goto-char (org-element-property :end parent)))
  21395. ((integer-or-marker-p end) (goto-char end))
  21396. (t (message "No element at point")))))))
  21397. (defun org-backward-element ()
  21398. "Move backward by one element.
  21399. Move to the previous element at the same level, when possible."
  21400. (interactive)
  21401. (cond ((bobp) (user-error "Cannot move further up"))
  21402. ((org-with-limited-levels (org-at-heading-p))
  21403. ;; At a headline, move to the previous one, if any, or stay
  21404. ;; here.
  21405. (let ((origin (point)))
  21406. (org-with-limited-levels (org-backward-heading-same-level 1))
  21407. ;; When current headline has no sibling above, move to its
  21408. ;; parent.
  21409. (when (= (point) origin)
  21410. (or (org-with-limited-levels (org-up-heading-safe))
  21411. (progn (goto-char origin)
  21412. (user-error "Cannot move further up"))))))
  21413. (t
  21414. (let* ((elem (org-element-at-point))
  21415. (beg (org-element-property :begin elem)))
  21416. (cond
  21417. ;; Move to beginning of current element if point isn't
  21418. ;; there already.
  21419. ((null beg) (message "No element at point"))
  21420. ((/= (point) beg) (goto-char beg))
  21421. (t (goto-char beg)
  21422. (skip-chars-backward " \r\t\n")
  21423. (unless (bobp)
  21424. (let ((prev (org-element-at-point)))
  21425. (goto-char (org-element-property :begin prev))
  21426. (while (and (setq prev (org-element-property :parent prev))
  21427. (<= (org-element-property :end prev) beg))
  21428. (goto-char (org-element-property :begin prev)))))))))))
  21429. (defun org-up-element ()
  21430. "Move to upper element."
  21431. (interactive)
  21432. (if (org-with-limited-levels (org-at-heading-p))
  21433. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  21434. (let* ((elem (org-element-at-point))
  21435. (parent (org-element-property :parent elem)))
  21436. (if parent (goto-char (org-element-property :begin parent))
  21437. (if (org-with-limited-levels (org-before-first-heading-p))
  21438. (user-error "No surrounding element")
  21439. (org-with-limited-levels (org-back-to-heading)))))))
  21440. (defun org-down-element ()
  21441. "Move to inner element."
  21442. (interactive)
  21443. (let ((element (org-element-at-point)))
  21444. (cond
  21445. ((memq (org-element-type element) '(plain-list table))
  21446. (goto-char (org-element-property :contents-begin element))
  21447. (forward-char))
  21448. ((memq (org-element-type element) org-element-greater-elements)
  21449. ;; If contents are hidden, first disclose them.
  21450. (when (org-invisible-p (line-end-position)) (org-cycle))
  21451. (goto-char (or (org-element-property :contents-begin element)
  21452. (user-error "No content for this element"))))
  21453. (t (user-error "No inner element")))))
  21454. (defun org-drag-element-backward ()
  21455. "Move backward element at point."
  21456. (interactive)
  21457. (let ((elem (or (org-element-at-point)
  21458. (user-error "No element at point"))))
  21459. (if (eq (org-element-type elem) 'headline)
  21460. ;; Preserve point when moving a whole tree, even if point was
  21461. ;; on blank lines below the headline.
  21462. (let ((offset (skip-chars-backward " \t\n")))
  21463. (unwind-protect (org-move-subtree-up)
  21464. (forward-char (- offset))))
  21465. (let ((prev-elem
  21466. (save-excursion
  21467. (goto-char (org-element-property :begin elem))
  21468. (skip-chars-backward " \r\t\n")
  21469. (unless (bobp)
  21470. (let* ((beg (org-element-property :begin elem))
  21471. (prev (org-element-at-point))
  21472. (up prev))
  21473. (while (and (setq up (org-element-property :parent up))
  21474. (<= (org-element-property :end up) beg))
  21475. (setq prev up))
  21476. prev)))))
  21477. ;; Error out if no previous element or previous element is
  21478. ;; a parent of the current one.
  21479. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  21480. (user-error "Cannot drag element backward")
  21481. (let ((pos (point)))
  21482. (org-element-swap-A-B prev-elem elem)
  21483. (goto-char (+ (org-element-property :begin prev-elem)
  21484. (- pos (org-element-property :begin elem))))))))))
  21485. (defun org-drag-element-forward ()
  21486. "Move forward element at point."
  21487. (interactive)
  21488. (let* ((pos (point))
  21489. (elem (or (org-element-at-point)
  21490. (user-error "No element at point"))))
  21491. (when (= (point-max) (org-element-property :end elem))
  21492. (user-error "Cannot drag element forward"))
  21493. (goto-char (org-element-property :end elem))
  21494. (let ((next-elem (org-element-at-point)))
  21495. (when (or (org-element-nested-p elem next-elem)
  21496. (and (eq (org-element-type next-elem) 'headline)
  21497. (not (eq (org-element-type elem) 'headline))))
  21498. (goto-char pos)
  21499. (user-error "Cannot drag element forward"))
  21500. ;; Compute new position of point: it's shifted by NEXT-ELEM
  21501. ;; body's length (without final blanks) and by the length of
  21502. ;; blanks between ELEM and NEXT-ELEM.
  21503. (let ((size-next (- (save-excursion
  21504. (goto-char (org-element-property :end next-elem))
  21505. (skip-chars-backward " \r\t\n")
  21506. (forward-line)
  21507. ;; Small correction if buffer doesn't end
  21508. ;; with a newline character.
  21509. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  21510. (org-element-property :begin next-elem)))
  21511. (size-blank (- (org-element-property :end elem)
  21512. (save-excursion
  21513. (goto-char (org-element-property :end elem))
  21514. (skip-chars-backward " \r\t\n")
  21515. (forward-line)
  21516. (point)))))
  21517. (org-element-swap-A-B elem next-elem)
  21518. (goto-char (+ pos size-next size-blank))))))
  21519. (defun org-drag-line-forward (arg)
  21520. "Drag the line at point ARG lines forward."
  21521. (interactive "p")
  21522. (dotimes (_ (abs arg))
  21523. (let ((c (current-column)))
  21524. (if (< 0 arg)
  21525. (progn
  21526. (beginning-of-line 2)
  21527. (transpose-lines 1)
  21528. (beginning-of-line 0))
  21529. (transpose-lines 1)
  21530. (beginning-of-line -1))
  21531. (org-move-to-column c))))
  21532. (defun org-drag-line-backward (arg)
  21533. "Drag the line at point ARG lines backward."
  21534. (interactive "p")
  21535. (org-drag-line-forward (- arg)))
  21536. (defun org-mark-element ()
  21537. "Put point at beginning of this element, mark at end.
  21538. Interactively, if this command is repeated or (in Transient Mark
  21539. mode) if the mark is active, it marks the next element after the
  21540. ones already marked."
  21541. (interactive)
  21542. (let (deactivate-mark)
  21543. (if (and (called-interactively-p 'any)
  21544. (or (and (eq last-command this-command) (mark t))
  21545. (and transient-mark-mode mark-active)))
  21546. (set-mark
  21547. (save-excursion
  21548. (goto-char (mark))
  21549. (goto-char (org-element-property :end (org-element-at-point)))))
  21550. (let ((element (org-element-at-point)))
  21551. (end-of-line)
  21552. (push-mark (org-element-property :end element) t t)
  21553. (goto-char (org-element-property :begin element))))))
  21554. (defun org-narrow-to-element ()
  21555. "Narrow buffer to current element."
  21556. (interactive)
  21557. (let ((elem (org-element-at-point)))
  21558. (cond
  21559. ((eq (car elem) 'headline)
  21560. (narrow-to-region
  21561. (org-element-property :begin elem)
  21562. (org-element-property :end elem)))
  21563. ((memq (car elem) org-element-greater-elements)
  21564. (narrow-to-region
  21565. (org-element-property :contents-begin elem)
  21566. (org-element-property :contents-end elem)))
  21567. (t
  21568. (narrow-to-region
  21569. (org-element-property :begin elem)
  21570. (org-element-property :end elem))))))
  21571. (defun org-transpose-element ()
  21572. "Transpose current and previous elements, keeping blank lines between.
  21573. Point is moved after both elements."
  21574. (interactive)
  21575. (org-skip-whitespace)
  21576. (let ((end (org-element-property :end (org-element-at-point))))
  21577. (org-drag-element-backward)
  21578. (goto-char end)))
  21579. (defun org-unindent-buffer ()
  21580. "Un-indent the visible part of the buffer.
  21581. Relative indentation (between items, inside blocks, etc.) isn't
  21582. modified."
  21583. (interactive)
  21584. (unless (eq major-mode 'org-mode)
  21585. (user-error "Cannot un-indent a buffer not in Org mode"))
  21586. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  21587. (unindent-tree
  21588. (lambda (contents)
  21589. (dolist (element (reverse contents))
  21590. (if (memq (org-element-type element) '(headline section))
  21591. (funcall unindent-tree (org-element-contents element))
  21592. (save-excursion
  21593. (save-restriction
  21594. (narrow-to-region
  21595. (org-element-property :begin element)
  21596. (org-element-property :end element))
  21597. (org-do-remove-indentation))))))))
  21598. (funcall unindent-tree (org-element-contents parse-tree))))
  21599. (defun org-make-options-regexp (kwds &optional extra)
  21600. "Make a regular expression for keyword lines.
  21601. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  21602. when non-nil, is a regexp matching keywords names."
  21603. (concat "^[ \t]*#\\+\\("
  21604. (regexp-opt kwds)
  21605. (and extra (concat (and kwds "\\|") extra))
  21606. "\\):[ \t]*\\(.*\\)"))
  21607. ;;; Finish up
  21608. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  21609. (lambda () (add-hook 'change-major-mode-hook
  21610. 'org-show-all 'append 'local)))
  21611. (provide 'org)
  21612. (run-hooks 'org-load-hook)
  21613. ;;; org.el ends here